Как вывести переменную на обе команды?
У меня есть переменные member и time, мне нужно, чтоб при окончании голосования выдавалась роль на определенное время. Сама проблема в том, что в конце не выдается роль по завершению голосования
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def startvote(ctx, member = discord.Member = None):
if member == None:
return
channel = ctx.channel
emb = discord.Embed(title=f'@everyone ЩАС КТО-ТО УЛЕТИТ В НОКАУТ.', description=f"Улетает {member.mention}",
colour=discord.Color.blue())
message = await ctx.send(embed=emb)
await message.add_reaction('✅')
await message.add_reaction('❌')
global message_id
message_id = message.id
@client.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def endvote(ctx):
channel = ctx.channel
message = await channel.fetch_message(message_id)
resactions = [reaction for reaction in message.reactions if reaction.emoji in ['✅', '❌']]
result = ''
for reaction in resactions:
result += reaction.emoji + ": " + str(reaction.count - 1)
emb = discord.Embed(title=f'Короче', description='Итог голосования: ' + str(result),
colour=discord.Color.orange())
await ctx.send(embed=emb)
if int(result[3]) > int(result[7]):
await member.add_roles(1016473374731534386)
await asyncio.sleep(time)
await member.remove_roles(1016473374731534386)
else:
await ctx.send("каким образом он не улетел?")
Ответы (1 шт):
Автор решения: Universall
→ Ссылка
Рабочий вариант выглядеть как-то так (Ошибки и алгоритм я описал в комментариях):
import asyncio
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!!", intents=intents)
role_id = 123 # id роли, которую нужно выдать
vote_message_id: int = 0
vote_member_id: int = 0
async def temp_role(member: discord.Member, role: discord.Role, time: int) -> None:
await member.add_roles(role) # Выдаем роль
await asyncio.sleep(time) # Асинхронно ждём
await member.remove_roles(role) # Забираем роль
@bot.command(name='startvote')
@commands.has_permissions(administrator=True)
async def start_vote(ctx: commands.Context, member: discord.Member = None) -> None: # Аннотация типов указывается так "переменная: тип = None", а не "переменная = тип = None"
global vote_message_id, vote_member_id
if member is None:
await ctx.channel.send("Укажите пользователя")
return
embed = discord.Embed(title=f'ЩАС КТО-ТО УЛЕТИТ В НОКАУТ.', description=f"Улетает {member.mention}", colour=discord.Color.blue())
message = await ctx.channel.send(embed=embed)
asyncio.create_task(message.add_reaction('✅'))
asyncio.create_task(message.add_reaction('❌'))
vote_message_id = message.id # сохраняем пользователя и сообщение в глобальную переменную
vote_member_id = member.id
@bot.command(name='endvote')
@commands.has_permissions(administrator=True)
async def end_vote(ctx: commands.Context) -> None:
global vote_message_id, vote_member_id
if not vote_message_id or not vote_member_id:
await ctx.channel.send("Голосование ещё не начиналось")
return
member = await ctx.guild.fetch_member(vote_member_id) # Получаем объект пользователя
message = await ctx.channel.fetch_message(vote_message_id) # Получаем объект сообщения
role = ctx.guild.get_role(role_id)
reactions = [reaction for reaction in message.reactions if reaction.emoji in ['✅', '❌']] # Считаем голоса
reactions_yes = reactions[0].count
reactions_no = reactions[1].count
embed = discord.Embed(title="Результаты", description=f"{reactions_yes}:{reactions_no}", colour=discord.Color.orange())
await ctx.channel.send(embed=embed)
if reactions_yes > reactions_no:
asyncio.create_task(temp_role(member, role, 10)) # Выдаём роль; 10 (в секундах) - на сколько нужно выдать роль
vote_message_id = 0 # Обнуляем пользователя и сообщение
vote_member_id = 0
if __name__ == '__main__':
bot.run("token")