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

discord.py rewrite 等待用户回复时如何实现20秒超时后执行对应操作

解决方案

你可以直接用discord.py内置的wait_for超时参数实现需求,同时我修正了你原有代码里的几个语法错误,修改后完整逻辑如下:

import asyncio # 确保你已经导入了asyncio
from discord.ext import commands

TOKEN = "你的机器人TOKEN"

class MyBot(commands.Bot):
    
    def __init__(self, command_prefix, self_bot):
        super().__init__(command_prefix=command_prefix, self_bot=self_bot) # 用super写法更规范
        self.add_commands()
        self.playinput = ""
        self.inputvalid = True
        self.playing = False
        self.replace = False

    
    def add_commands(self):
      @self.command(name="play",help="Plays the first Youtube result from the input you give. Usage:   -play [search here]   Example:   -play Never Gonna Give You Up")
      async def play(ctx,*args): # 官方约定上下文参数拼写为ctx,你也可以保留原有cxt写法
        self.playinput = ""
        self.inputvalid = True
        if len(args) != 0:
          self.playinput = " ".join(args) # 直接用join拼接搜索词,不需要循环累加
        else:
          message = await ctx.send("Invalid input.")
          await asyncio.sleep(5)
          await message.delete() # rewrite版本删除消息的标准写法
          self.inputvalid = False
          return # 输入无效直接返回,不需要走后续逻辑
    
        if self.inputvalid == True:
          if self.playing == True:
            # 保存询问消息对象,后续用于删除
            confirm_msg = await ctx.send("Video already playing. Replace? y/n")
            
            def check(msg):
              return msg.author == ctx.author and msg.channel == ctx.channel and \
              msg.content.lower() in ["y", "n"]
            
            try:
              # 加timeout参数设置20秒超时
              replacemessage = await self.wait_for("message", check=check, timeout=20)
            except asyncio.TimeoutError:
              # 超时未收到回复,删除询问消息
              await confirm_msg.delete()
              await ctx.send("操作已超时取消", delete_after=5) # 可选配置,超时提示5秒后自动删除
              return
            else:
              # 收到合法回复,同时删除询问消息和用户的回复消息
              await confirm_msg.delete()
              await replacemessage.delete()
              # 后续你自己的处理逻辑,比如判断用户选了y还是n
              self.replace = (replacemessage.content.lower() == "y")
          
          # 下面补充你自己的播放逻辑
          # ...

bot = MyBot(command_prefix="-", self_bot=False)
bot.run(TOKEN)

核心改动说明

  • wait_for方法传入timeout=20参数,超过20秒没有符合条件的消息就会抛出asyncio.TimeoutError
  • 异常分支处理超时场景,直接删除之前发送的询问消息
  • 正常收到回复的分支,同时删除询问消息和用户发送的y/n回复
  • 修正了原代码中未加await、变量未定义、旧版本删除消息写法等问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:24:03