Pycord动态处理多按钮:获取选中按钮ID并延续命令
动态生成Pycord按钮并获取选中custom_id的问题与解决方法
问题背景
从Novus迁移至Pycord,需实现基于列表动态生成1到n个按钮的交互功能,核心需求是获取选中按钮的custom_id,并将该ID用于后续命令逻辑。
遇到的问题
- DefaultView的callback完全不触发,交互界面显示“This interaction failed”
- 给DefaultButton添加callback后,交互不再报错,但无法回到主命令继续执行,仅超时功能可正常在默认180秒后禁用所有按钮
初始代码
@bot.slash_command(name='bombs', description='Returns bombs to destroy base and airfield.') async def bomb(ctx): await ctx.interaction.response.defer() countries = ["America", "Britain", "China", "France", "Germany", "Italy", "Japan", "Russia", "Sweden"] view = DefaultView() for number in list(range(1, len(countries) + 1)): view.add_item(DefaultButton(label=str(number), custom_id=str(number))) country_choice_message = await ctx.interaction.followup.send("Select a country to view bombs from:", view=view) timed_out_ = await view.wait() if timed_out_: view.disable_all_items() view.stop() await country_choice_message.edit(view=view) await ctx.interaction.followup.send("Timed out.", ephemeral=True) return # country_number = button_custom_id # do other stuff with country_number... class DefaultButton(discord.ui.Button): def __init__(self, custom_id, *args, **kwargs): super().__init__(*args, **kwargs) self.custom_id = custom_id class DefaultView(discord.ui.View): def __init__(self): super().__init__() async def callback(self, button: discord.ui.Button, interaction: discord.Interaction): self.disable_all_items() self.stop() await interaction.response.defer() await interaction.edit_original_message(view=self)
添加按钮回调后的代码
class DefaultButton(discord.ui.Button): def __init__(self, custom_id, *args, **kwargs): super().__init__(*args, **kwargs) self.custom_id = custom_id async def callback(self, interaction: discord.Interaction): self.custom_id = interaction.custom_id await interaction.response.defer() return
解决情况
查阅Stack Overflow相关帖子后,未解决动态按钮数量的适配问题,最终通过@Ice Wolfy的方案解决。
内容的提问来源于stack exchange,提问作者MrMetacom
相关产品推荐
相关产品推荐

