Discord.py Discord_components Как заставить кнопки прикрепленные к эмбеду работать после перезапуска бота
столкнулся с проблемой, которую не могу решить своими силами. Перепробовал уже кучу вариантов написания, с переносом в один модуль, с использованием различных вариантов решения. Но всегда прихожу к одному и тому же, после перезапуска бота не работают кнопки в сообщениях.
Прикладываю код main файла, где подключаются все модули через Cog.
from datetime import datetime
from operator import ne
from queue import Empty
from types import new_class
from unicodedata import name
from attr import field
import discord
from discord.ext import commands
from discord_components import DiscordComponents, Button, ButtonStyle
from cmd_raid import Raidcog
from cmd_dyp import Dypcog
from cmd_moder import Modcog
from cmd_event import Eventcog
#Глобальные пемеренные:
dypid = 0
#Токен для подключения бота
TOKEN = "123"
#Меняем префикс, убираем команду help
bot = commands.Bot(command_prefix=('mo='), intents = discord.Intents.all(), help_command=None)
#Сообщение в консоль при запуске бота
@bot.event
async def on_ready():
DiscordComponents(bot)
print("BOT LOADING...")
#Подключение модулей с командами
bot.add_cog(Raidcog(bot))
bot.add_cog(Dypcog(bot))
bot.add_cog(Modcog(bot))
bot.add_cog(Eventcog(bot))
bot.run(TOKEN)
И сам код модуля с проверкой нажатия на кнопки:
from datetime import datetime
from operator import ne
from queue import Empty
from types import new_class
from unicodedata import name
from attr import field
import discord
from discord.ext import commands
from discord_components import DiscordComponents, Button, ButtonStyle
class Eventcog(commands.Cog):
def __init__(self, bot):
self.bot = bot
DiscordComponents(commands.bot)
print('CMD EVENT LOADING...')
#Добавить новость в канал 'Расписание'
@commands.command()
async def addevent(self, news, sday='', stime='', stype='', chan='', voip='', ntext=''):
if news.message.author.guild_permissions.manage_roles:
await news.channel.purge(limit = 1)
namea = ''
timestamp = datetime.now()
if news.author.nick is None:
namea=news.author.name
else:
namea=news.author.nick
if stype == 'PVE':
await news.send('<@&913796484762316800>')
addnews=discord.Embed(title=f'{sday} в {stime} пойдём в {stype} рейд на {chan}. Голосовой канал: {voip}', description=f'**Цель рейда:** {ntext}', color=0x4dff00)
addnews.set_footer(text=f'Создал ивент: {namea}. Дата создания: {timestamp.strftime(r"%d.%m.%y %H:%M")}')
addnews.add_field(name='✅ Придут: (0)', value='-', inline=True)
addnews.add_field(name='❌ Не придут: (0)', value='-', inline=True)
addnews.add_field(name='❔ Не знаю: (0)', value='-', inline=True)
msg = await news.send(
embed=addnews,
components = [
[
Button(style = ButtonStyle.grey, label = '✅', custom_id = "abtn"),
Button(style = ButtonStyle.grey, label = '❌', custom_id = "dbtn"),
Button(style = ButtonStyle.grey, label = '❔', custom_id = "ibtn"),
Button(style = ButtonStyle.green, label = 'Закрыть', custom_id = "delbtn"),
]
])
if stype == 'PVP':
await news.send('<@&913796484762316800>')
addnews=discord.Embed(title=f'{sday} в {stime} пойдём в {stype} рейд на {chan}. Голосовой канал: {voip}', description=f'**Цель рейда:** {ntext}', color=0x4dff00)
addnews.set_footer(text=f'Создал ивент: {namea}. Дата создания: {timestamp.strftime(r"%d.%m.%y %H:%M")}')
addnews.add_field(name='✅ Придут: (0)', value='-', inline=True)
addnews.add_field(name='❌ Не придут: (0)', value='-', inline=True)
addnews.add_field(name='❔ Не знаю: (0)', value='-', inline=True)
msg = await news.send(
embed=addnews,
components = [
[
Button(style = ButtonStyle.grey, label = '✅', custom_id = "abtn"),
Button(style = ButtonStyle.grey, label = '❌', custom_id = "dbtn"),
Button(style = ButtonStyle.grey, label = '❔', custom_id = "ibtn"),
Button(style = ButtonStyle.green, label = 'Закрыть', custom_id = "delbtn"),
]
])
if stype == 'TRAIN':
msg = await news.send('<@&913796484762316800>')
addnews=discord.Embed(title=f'{sday} в {stime} состоится PVP-тренировка на {chan}. Голосовой канал: {voip}', description=f'**Формат тренировки:** {ntext}', color=0xfff700)
addnews.set_footer(text=f'Создал ивент: {namea}. Дата создания: {timestamp.strftime(r"%d.%m.%y %H:%M")}')
addnews.add_field(name='✅ Придут: (0)', value='-', inline=True)
addnews.add_field(name='❌ Не придут: (0)', value='-', inline=True)
addnews.add_field(name='❔ Не знаю: (0)', value='-', inline=True)
await news.send(
embed=addnews,
components = [
[
Button(style = ButtonStyle.grey, label = '✅', custom_id = "abtn"),
Button(style = ButtonStyle.grey, label = '❌', custom_id = "dbtn"),
Button(style = ButtonStyle.grey, label = '❔', custom_id = "ibtn"),
Button(style = ButtonStyle.green, label = 'Закрыть', custom_id = "delbtn"),
]
])
acceptlist = ['-']
declinelist = ['-']
idklist = ['-']
whiletrue = 0
#Делаем бесконечный цикл ожидающий нажатие кнопки
while whiletrue == 0:
interaction = await self.bot.wait_for('button_click')
#Отслеживание первой кнопки
if interaction.component.custom_id == 'abtn':
if msg.id == interaction.message.id:
memb = interaction.user
if memb.nick is None:
if memb.name not in acceptlist:
acceptlist.append(memb.name)
if '-' in acceptlist:
acceptlist.remove('-')
if acceptlist==[]:
acceptlist.append('-')
if memb.name in declinelist:
declinelist.remove(memb.name)
if '-' in declinelist:
declinelist.remove('-')
if declinelist==[]:
declinelist.append('-')
if memb.name in idklist:
idklist.remove(memb.name)
if '-' in idklist:
idklist.remove('-')
if idklist==[]:
idklist.append('-')
else:
if memb.nick not in acceptlist:
acceptlist.append(memb.nick)
if '-' in acceptlist:
acceptlist.remove('-')
if acceptlist==[]:
acceptlist.append('-')
if memb.nick in declinelist:
declinelist.remove(memb.nick)
if '-' in declinelist:
declinelist.remove('-')
if declinelist==[]:
declinelist.append('-')
if memb.nick in idklist:
idklist.remove(memb.nick)
if '-' in idklist:
idklist.remove('-')
if idklist==[]:
idklist.append('-')
a1 = '\n'
a2 = f'{a1} {a1.join(acceptlist)}'
b1 = '\n'
b2 = f'{b1} {b1.join(declinelist)}'
c1 = '\n'
c2 = f'{c1} {c1.join(idklist)}'
a2len = len(acceptlist)
if a2len == 1:
if '-' in acceptlist:
a2len = a2len-1
b2len = len(declinelist)
if b2len == 1:
if '-' in declinelist:
b2len = b2len-1
c2len = len(idklist)
if c2len == 1:
if '-' in idklist:
c2len = c2len-1
embednew=discord.Embed(title=f'{sday} в {stime} пойдём в {stype} рейд на {chan}. Голосовой канал: {voip}', description=f'**Цель рейда:** {ntext}', color=0x4dff00)
embednew.set_footer(text=f'Создал ивент: {namea}. Дата создания: {timestamp.strftime(r"%d.%m.%y %H:%M")}')
embednew.add_field(name=f'✅ Придут: ({a2len})', value=f'{a2}', inline=True)
embednew.add_field(name=f'❌ Не придут: ({b2len})', value=f'{b2}', inline=True)
embednew.add_field(name=f'❔ Не знаю: ({c2len})', value=f'{c2}', inline=True)
await msg.edit(embed=embednew)
await interaction.respond(type=6)
#Отслеживание второй кнопки
if interaction.component.custom_id == 'dbtn':
if msg.id == interaction.message.id:
memb = interaction.user
if memb.nick is None:
if memb.name not in declinelist:
declinelist.append(memb.name)
if '-' in declinelist:
declinelist.remove('-')
if declinelist==[]:
declinelist.append('-')
if memb.name in acceptlist:
acceptlist.remove(memb.name)
if '-' in acceptlist:
acceptlist.remove('-')
if acceptlist==[]:
acceptlist.append('-')
if memb.name in idklist:
idklist.remove(memb.name)
if '-' in idklist:
idklist.remove('-')
if idklist==[]:
idklist.append('-')
else:
if memb.nick not in declinelist:
declinelist.append(memb.nick)
if '-' in declinelist:
declinelist.remove('-')
if declinelist==[]:
declinelist.append('-')
if memb.nick in acceptlist:
acceptlist.remove(memb.nick)
if '-' in acceptlist:
acceptlist.remove('-')
if acceptlist==[]:
acceptlist.append('-')
if memb.nick in idklist:
idklist.remove(memb.nick)
if '-' in idklist:
idklist.remove('-')
if idklist==[]:
idklist.append('-')
a1 = '\n'
a2 = f'{a1} {a1.join(acceptlist)}'
b1 = '\n'
b2 = f'{b1} {b1.join(declinelist)}'
c1 = '\n'
c2 = f'{c1} {c1.join(idklist)}'
a2len = len(acceptlist)
if a2len == 1:
if '-' in acceptlist:
a2len = a2len-1
b2len = len(declinelist)
if b2len == 1:
if '-' in declinelist:
b2len = b2len-1
c2len = len(idklist)
if c2len == 1:
if '-' in idklist:
c2len = c2len-1
embednew=discord.Embed(title=f'{sday} в {stime} пойдём в {stype} рейд на {chan}. Голосовой канал: {voip}', description=f'**Цель рейда:** {ntext}', color=0x4dff00)
embednew.set_footer(text=f'Создал ивент: {namea}. Дата создания: {timestamp.strftime(r"%d.%m.%y %H:%M")}')
embednew.add_field(name=f'✅ Придут: ({a2len})', value=f'{a2}', inline=True)
embednew.add_field(name=f'❌ Не придут: ({b2len})', value=f'{b2}', inline=True)
embednew.add_field(name=f'❔ Не знаю: ({c2len})', value=f'{c2}', inline=True)
await msg.edit(embed=embednew)
await interaction.respond(type=6)
#Отслеживание Третьей кнопки
if interaction.component.custom_id == 'ibtn':
if msg.id == interaction.message.id:
memb = interaction.user
if memb.nick is None:
if memb.name not in idklist:
idklist.append(memb.name)
if '-' in idklist:
idklist.remove('-')
if idklist==[]:
idklist.append('-')
if memb.name in acceptlist:
acceptlist.remove(memb.name)
if '-' in acceptlist:
acceptlist.remove('-')
if acceptlist==[]:
acceptlist.append('-')
if memb.name in declinelist:
declinelist.remove(memb.name)
if '-' in declinelist:
declinelist.remove('-')
if declinelist==[]:
declinelist.append('-')
else:
if memb.nick not in idklist:
idklist.append(memb.nick)
if '-' in idklist:
idklist.remove('-')
if idklist==[]:
idklist.append('-')
if memb.nick in acceptlist:
acceptlist.remove(memb.nick)
if '-' in acceptlist:
acceptlist.remove('-')
if acceptlist==[]:
acceptlist.append('-')
if memb.nick in declinelist:
declinelist.remove(memb.nick)
if '-' in declinelist:
declinelist.remove('-')
if declinelist==[]:
declinelist.append('-')
a1 = '\n'
a2 = f'{a1} {a1.join(acceptlist)}'
b1 = '\n'
b2 = f'{b1} {b1.join(declinelist)}'
c1 = '\n'
c2 = f'{c1} {c1.join(idklist)}'
a2len = len(acceptlist)
if a2len == 1:
if '-' in acceptlist:
a2len = a2len-1
b2len = len(declinelist)
if b2len == 1:
if '-' in declinelist:
b2len = b2len-1
c2len = len(idklist)
if c2len == 1:
if '-' in idklist:
c2len = c2len-1
embednew=discord.Embed(title=f'{sday} в {stime} пойдём в {stype} рейд на {chan}. Голосовой канал: {voip}', description=f'**Цель рейда:** {ntext}', color=0x4dff00)
embednew.set_footer(text=f'Создал ивент: {namea}. Дата создания: {timestamp.strftime(r"%d.%m.%y %H:%M")}')
embednew.add_field(name=f'✅ Придут: ({a2len})', value=f'{a2}', inline=True)
embednew.add_field(name=f'❌ Не придут: ({b2len})', value=f'{b2}', inline=True)
embednew.add_field(name=f'❔ Не знаю: ({c2len})', value=f'{c2}', inline=True)
await msg.edit(embed=embednew)
await interaction.respond(type=6)
if interaction.component.custom_id == 'delbtn':
if msg.id == interaction.message.id:
memb = interaction.user
if memb.nick == namea or memb.name == namea or memb.nick == '[U4] Unicode':
await interaction.respond(content = f'Закрыт сбор участников события c датой "{sday}" и временем "{stime}"')
await msg.edit(
components = [
[
Button(style = ButtonStyle.grey, label = '✅', custom_id = "abtn", disabled=True),
Button(style = ButtonStyle.grey, label = '❌', custom_id = "dbtn", disabled=True),
Button(style = ButtonStyle.grey, label = '❔', custom_id = "ibtn", disabled=True),
Button(style = ButtonStyle.green, label = 'Закрыть', custom_id = "delbtn", disabled=True),
]
])
whiletrue = 1
else:
await interaction.respond(content = 'Только автор события может закрыть сбор участников')
else:
if news.author.nick is None:
await news.channel.purge(limit = 1)
await news.send(f'**{news.author.name},** вы не можете добавлять события в расписание')
else:
await news.channel.purge(limit = 1)
await news.send(f'**{news.author.nick},** вы не можете добавлять события в расписание')
До перезапуска бота с этим кодом само собой всё работает отлично, но так же логично что после перезапуска код не работает, так как команда еще не вызвана и цикл не запущен. Подскажите как вынести цикл за предел команды, что бы он работал.
По задумке люди кликая по кнопке попадают в определённый филд и формируется список потенциальных участников эвента.
Ответы (1 шт):
в общем, в коде невозможно использовать interaction.component.custom_id,
используй interaction.component.label