You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord-py-slash-commands库cog中wait_for_component功能无法正常运行

问题原因
  • 核心错误为变量名拼写不匹配:你创建动作行时定义的变量名为action_row,但调用wait_for_component方法时传入的参数是actionrow,缺失了中间的下划线。这就导致方法监听的组件和实际发送到频道的组件不匹配,框架无法对应到点击事件,因此点击按钮会提示Interaction Failed!,且控制台没有明确报错。
修正后代码
import discord
from discord.ext import commands
from discord_slash.context import ComponentContext
from discord_slash.model import ButtonStyle
from discord_slash.utils.manage_components import create_actionrow, create_button, wait_for_component

class buttons(commands.Cog):
    def __init__(self, client):
        self.client = client
    
    @commands.command()
    async def button(self, ctx):
        btns = [create_button(
                    style=ButtonStyle.green,
                    label="Button!"
                )]
        action_row = create_actionrow(*btns)
        await ctx.send("My Message", components=[action_row])
        # 修正此处的变量名,改为action_row
        button_ctx: ComponentContext = await wait_for_component(self.client,components=action_row)
        await button_ctx.edit_origin(content="You pressed a button!")
        
def setup(client):
    client.add_cog(buttons(client))
额外优化建议
  • 可添加用户校验规则,避免其他用户点击按钮触发你的交互逻辑:在wait_for_component中新增check参数即可,示例如下:
button_ctx: ComponentContext = await wait_for_component(self.client, components=action_row, check=lambda x: x.author.id == ctx.author.id)
  • 可添加timeout参数设置监听超时时间,单位为秒,超时后会抛出异步超时异常,你可以根据需求自行捕获处理对应的场景。

内容的提问来源于stack exchange,提问作者Ritheesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 05:39:01