Всем привет! У меня тут вот ошибка взаимодействия. Использую библиотеку DiscordComponents а именно SelectMenu.
Так вот, когда я выбираю в меню какую то категорию, то он мне выводит сообщение, а когда я хочу поменять данную категорию, мне выводит «Ошибка взаимодействия»
Код:
@bot.command()
async def help(ctx):
home = discord.Embed(
title=’ Help’,
description=’Чтобы получить справку по категориям команд бота используйте меню, которое есть под сообщением.nn’
‘Не работает меню? Пропишите «s.help Модерация/Рейтинг/Активности/Экономика/Информация/Развлечения/Прочее«’,
colour=discord.Color.purple()
)
home.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await ctx.send(
embed=home,
components=[
Select(
placeholder=»Выберите категорию»,
options=[
SelectOption(label=»Модерация», value=»Модерация»),
SelectOption(label=»Рейтинг», value=»Рейтинг»),
SelectOption(label=»Активности», value=»Активности»),
SelectOption(label=»Экономика», value=»Экономика»),
SelectOption(label=»Информация», value=»Информация»),
SelectOption(label=»Развлечения», value=»Развлечения»),
SelectOption(label=»Прочее», value=»Прочее»)
]
)
]
)
interaction = await bot.wait_for(«select_option»)
selected = interaction.values[0]
if selected == «Модерация»:
moderation = discord.Embed(
title=» Модерация»,
description=f»«{p}ban [участник] [причина]« — Заблокировать участникаn «{p}kick [участник]« — Выгнать участникаn»
f»«{p}mute [участник]« — Заблокировать чат участникуn«{p}unmute [участник]« — Разблокировать чат участникуn»
f»«{p}warn [участник]« — Выдать предупреждение участникуn«{p}unwarn [участник]« — Убрать предупреждение у участникаn»
f»«{p}resetwarns [участник]« — Убрать все предупреждения участникаn«{p}clear [кол-во]« — Очистить чатn»
f»«{p}warns [участник]« — Посмотреть свои предупреждение/предупреждения участникаn»
f»«{p}antilink on/off« — Включить/выключить антилинк системуn«{p}lvlsystem on/off« — Включить/выключить систему уровней»
f»«n{p}addrole [роль] [цена]« — Добавить роль в магазинn«{p}removerole [роль]« — Удалить роль из магазинаn»
f»«{p}set« — Настройка»,
colour=discord.Color.purple()
)
moderation.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=moderation)
elif selected == «Рейтинг»:
rating = discord.Embed(
title=» Рейтинг»,
description=f»«{p}leaderboards balance/level« — Топ по балансу/уровню»,
colour=discord.Color.purple()
)
rating.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=rating)
elif selected == «Активности»:
activities = discord.Embed(
title=» Активности»,
description=f»«{p}youtube« — YouTube Togethern«{p}poker« — Покерn«{p}betroyal« — BetRoyal.ion»
f»«{p}fishington« — Fishington.ion«{p}chess« — Шахматы»,
colour=discord.Color.purple()
)
activities.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=activities)
elif selected == «Экономика»:
economy = discord.Embed(
title=» Экономика»,
description=f»«{p}balance [участник]« — Показывает баланс участникаn«{p}tobank [сумма]« — Положить деньги в банкn»
f»«{p}withdraw [сумма]« — Обналичить деньги с банкаn«{p}beg« — Попрошайничать монетыn»
f»«{p}hunt« — Сходить на охотуn«{p}fish« — Сходить на рыбалкуn«{p}work« — Работатьn»
f»«{p}daily« — Ежедневная наградаn«{p}weekly« — Еженедельная наградаn«{p}reward« — Наградаn»
f»«{p}slots [сумма]« — Казиноn«{p}roulette [цвет] [сумма]« — Рулеткаn«{p}shop« — Магазинn«{p}buy [категория] [предмет]« — Купить что-то из магазинаn»
f»«{p}sell [категория] [предмет]« — Продать имуществоn«{p}buyrole [роль]« — Купить рольn«{p}roleshop« — Магазин ролейn»
f»«{p}addmoney [участник] [cумма]« — Начислить деньги участникуn«{p}takemoney [участник] [cумма]« — Отнять деньги у участникаn»
f»«{p}bonus« — Бонус для **Premium** пользователей»,
colour=discord.Color.purple()
)
economy.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=economy)
elif selected == «Информация»:
info = discord.Embed(
title=» Информация»,
description=f»«{p}help« — Получить список команд ботаn«{p}profile« — Получить свой профильn»
f»«{p}avatar [участник]« — Получить аватарку участника/своюn«{p}ping« — Получить задержку ботаn»
f»«{p}version« — Получить версию ботаn«{p}server« — Получить информацию о сервереn»
f»«{p}bot« — Получить информацию о боте»,
colour=discord.Color.purple()
)
info.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=info)
elif selected == «Развлечения»:
fun = discord.Embed(
title=» Развлечения»,
description=f»«{p}8ball [вопрос]« — Задать вопрос шаруn«{p}coin« — Подкинуть монеткуn»
f»«{p}knb [предмет]« — Поиграть с ботом в камень-ножницы-бумагаn»
f»«{p}iq [участник]« — Узнать IQ участникаn«{p}try [действие]« — Попытаться что то сделатьn»
f»«{p}kill [участник]« — Убить участникаn«{p}kiss [участник]« — Поцеловать участникаn»
f»«{p}pat [участник]« — Погладить участникаn«{p}poke [участник]« — Ткнуть участникаn»
f»«{p}hug [участник]« — Обнять участникаn«{p}eat [участник]« — Покушать»,
colour=discord.Color.purple()
)
fun.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=fun)
elif selected == «Прочее»:
other = discord.Embed(
title=» Прочее»,
description=f»«{p}afk« — Отойтиn«{p}say« — Сказать от лица ботаn«{p}tinyurl [ссылка]« — Укоротить ссылкуn»
f»«{p}rand [число] [число]« — Рандомное число»,
colour=discord.Color.purple()
)
other.set_footer(icon_url=ctx.author.avatar_url, text=f»Запрошенно от {ctx.author}»)
await interaction.edit_origin(embed=other)
Код делает то, что должен делать, но после каждого нажатия кнопки он говорит: «Это взаимодействие не удалось». Нажатие кнопки редактирует вставку, чтобы заменить ее на другую. Как мне избавиться от сообщения об ошибке взаимодействия после нажатия кнопки?
Проблема: https://i.stack.imgur.com/i4dTd.png
Код, полученный от: https://github.com/elixss/YouTube/ blob / main / source / buttons.py
Вот код:
@bot.group(invoke_without_command=True)
async def help(ctx):
# buttons
one = Button(style=1, label="Commands", id="em1")
two = Button(style=1, label="Depression", id="em2")
three = Button(style=1, label="Moderator", id="em3")
four = Button(style=1, label="Language", id="em4")
# embeds
em1 = Embed(title="Commands Plugin",color=0x5865F2)
em2 = Embed(title="Depression Plugin", description="placeholder", color=0x5865F2)
em3 = Embed(title="Moderator Plugin", description="placeholder", color=0x5865F2)
em4 = Embed(title="Language Plugin", description="placeholder", color=0x5865F2)
# main help embed
help_embed = Embed(description="> **Help Module**nPress on any button to view the commands for that selected plugin.",
color=discord.Color.random())
# buttons to embeds
buttons = {
"em1": em1,
"em2": em2,
"em3": em3,
"em4": em4
}
msg = await ctx.send(embed=help_embed,
components=[[one, two, three, four]])
while True:
event = await bot.wait_for("button_click", timeout=60.0)
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
await msg.edit(embed=response)
if response is None:
await event.channel.send("error, try again.")
2 ответа
Лучший ответ
Как сказал Элиас, вы должны реагировать на взаимодействия, иначе будет отображаться сообщение «Это взаимодействие не удалось», но не с обычным ctx.send()
, а с (в вашем случае)
await event.respond(type=4, message="Responded!")
Если вы не хотите отправлять сообщение в ответ на нажатие кнопки или выбор в выборе, вы можете просто использовать type=6
без сообщения:
await event.respond(type=6)
Дополнительные типы см. В документация.
1
Chuaat
6 Сен 2021 в 18:48
Лучший способ сделать это — либо удалить все кнопки после нажатия, либо добавить время восстановления, которое автоматически удалит кнопки через определенное время.
В вашей ситуации это будет выглядеть примерно так:
msg = await ctx.send(embed=help_embed, components=[[one, two, three, four]])
try:
res = await client.wait_for("button_click", timeout = 60)
except asyncio.TimeoutError:
await msg.edit(components = []) #removes buttons from message
else:
if res.author == message.author:
#when button is clicked
await msg.edit(components = [])
Это также предотвращает ограничение скорости, поэтому у вас нет кнопок, постоянно ожидающих ответа.
0
Larg Ank
7 Сен 2021 в 00:22
Before asking a question, look at these
Before, check you are using the correct library (discord-components
not discord-buttons
) and if your library is in
the newest version
.
How to make buttons inline?
How to make buttons inline?
Your code must be something like
await <discord.abc.Messageable>.send(
You should use a two-dimensional array like below to make buttons inline.
await <discord.abc.Messageable>.send(
How do I remove components?
How do I remove components?
Simple. Edit the message with parameter components
set to []
.
msg = await <discord.abc.Messageable>.send(
interaction = await <discord.ext.commands.Bot or discord.Client>.wait_for(«event»)
await msg.edit(components = [])
await interaction.edit_origin(
How do I ignore the interaction?
How do I ignore the interaction?
Just respond with the type 6
with no other parameters or defer with edit_origin enabled.
There is an event on_button_click
and on_select_option
. You can use this as normal events.
@<discord.ext.commands.Bot or discord.Client>.event
async def on_button_click(interaction):
if interaction.responded:
await interaction.send(content = «Yay!»)
@<discord.ext.commands.Bot or discord.Client>.event
async def on_select_option(interaction):
if interaction.responded:
await interaction.send(content = «Yay!»)
TypeError: send() got an unexpected keyword argument ‘components’
TypeError: send() got an unexpected keyword argument ‘components’
Have you put DiscordComponents(<discord.Client or discord.ext.commands.Bot>)
inside the on_ready
event or initialized the bot with ComponentsBot
?
Handle multiple interacts
Handle multiple interacts
You should put a while on discord.Client.wait_for
to handle multiple clicks
interaction = await <discord.ext.commands.Bot or discord.Client>.wait_for(«event»)
await interaction.send(content = «Wow»)
Disabling the components for specific users
Disabling the components for specific users
This is impossible but you can ignore the interaction by putting a check.
interaction = await <discord.ext.commands.Bot or discord.Client>.wait_for(
check = lambda i: i.user.id == «something»
I get »404 Not Found (error code: 10062): Unknown interaction»
I get »404 Not Found (error code: 10062): Unknown interaction»
Check if you already responded to the interaction.
You send a discord.Emoji
object to the parameter. You can get the custom emoji by doing
<discord.ext.commands.Bot or discord.Client>.get_emoji(849325102746042439)
Can I set my own colors for buttons?
Can I set my own colors for buttons?
Кнопка не реагирует, если никто не нажал на нее в течение 3 минут.
Я видел, что это было что-то с тайм-аутом, но я не знаю, где это разместить.
Мой код:
#Tickets
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label = "📥 Ticket", style=discord.ButtonStyle.grey)
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
with open("open_channels_user_id.json", "r") as f:
data = json.load(f)
user_id = data["user_id"]
if user_id != interaction.user.id:
admin_role = discord.utils.get(interaction.guild.roles, name = "hulpje")
category = discord.utils.get(interaction.guild.categories, name='Ticket')
overwrites = {interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
interaction.guild.me: discord.PermissionOverwrite(read_messages=True),
interaction.user: discord.PermissionOverwrite(read_messages=True),
admin_role: discord.PermissionOverwrite(read_messages=True)}
new_ticket = await interaction.guild.create_text_channel(f'Ticket- {interaction.user.name}', category=category, overwrites=overwrites)
channel = client.get_channel(new_ticket.id)
embed = discord.Embed(title=f'Ticket- {interaction.user.name}', description = "Goed dat je een ticket opent. n Stuur alvast wat informatie zodat het makkelijker is voor het staff team.", color=0x004BFF)
await channel.send(embed=embed)
await interaction.response.send_message(f"Ticket is geopen met de naam: Ticket- {interaction.user.name}")
data['user_id'] = interaction.user.id
with open("open_channels_user_id.json", "w") as f:
json.dump(data, f)
time.sleep(3)
await interaction.channel.purge(limit=1)
else:
await interaction.channel.send("Je hebt al een ticket openstaan.")
time.sleep(5)
await interaction.channel.purge(limit=1)
async def menu(ctx):
view = Menu()
embed = discord.Embed(title = "Ticket", description = "Vragen, klachten of iets anders maak hier je Ticket aan en wordt zo snel mogelijk geholpen!", color=0x004BFF)
await ctx.send(embed=embed, view=view)
Я не знаю, что делать. Пожалуйста, помогите!