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

Discord.py使用Cogs时wait_for()失效问题求助

问题分析与解决方案

原代码的问题

  1. 缩进错误:@commands.hybrid_command 装饰器的缩进不正确,会直接导致语法报错。
  2. 消息发送逻辑错误:await ctx.send(msg) 里的msg是Message对象,直接发送会触发类型错误,应该用msg.content提取文本内容。
  3. 缺少限制与超时处理:wait_for未限定消息必须在同一频道发送,也没设置超时时间,容易导致机器人卡住或被其他频道的消息误触发。
  4. 未实现文本输入框交互:原代码靠监听后续消息实现,不符合你想要的「触发命令后弹出文本输入框」的需求。

方案1:修复原监听消息的版本

修正缩进、消息发送逻辑,增加超时和频道限制:

import asyncio
from discord import commands

class Test(commands.Cog, name="test"):
    def __init__(self, bot):
        self.bot = bot

    @commands.hybrid_command(name='create_response', with_app_command=True)
    async def create_response(self, ctx):
        await ctx.send("请输入需要处理的内容:")
        # 限定消息必须来自同一作者、同一频道
        def check(msg):
            return msg.author == ctx.author and msg.channel == ctx.channel
        
        try:
            # 设置60秒超时,避免机器人无限等待
            msg = await self.bot.wait_for('message', check=check, timeout=60)
            await ctx.send(f"你输入的内容是:{msg.content}")
        except asyncio.TimeoutError:
            await ctx.send("超时未输入,命令已取消。")

方案2:实现带文本输入框的斜杠命令(推荐)

利用Discord应用命令的参数特性,直接在触发命令时弹出文本输入框,无需额外等待消息,完全匹配你的预期交互:

from discord import commands

class Test(commands.Cog, name="test"):
    def __init__(self, bot):
        self.bot = bot

    @commands.hybrid_command(name='create_response', with_app_command=True)
    async def create_response(self, ctx, content: str):
        # 直接处理用户通过输入框提交的content参数
        await ctx.send(f"你输入的内容是:{content}")

这个版本中,用户输入/create_response后,Discord会自动弹出文本输入框让用户填写内容,提交后机器人直接返回结果,交互流程更顺畅。

额外注意事项

  • 确保机器人启动时调用了await bot.tree.sync(),完成应用命令的同步。
  • 两种方案都需要给机器人配置「发送消息」「读取消息」的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:23:10