Python开发Discord Bot:重复调用长耗时命令报错排查
Discord机器人长耗时命令重复调用无响应及404错误的解决
问题根源
你的代码里用了time.sleep(10)这个同步阻塞函数,它会彻底卡住Discord机器人的事件循环:
- 事件循环被阻塞时,机器人无法处理新的命令请求,导致重复调用时后续请求无响应
- Discord的交互有严格的超时限制(必须在15秒内完成初始响应或defer),事件循环阻塞会让后续的交互处理超时,Discord服务器会认为该交互已失效,返回
Unknown interaction(404错误)
解决方法
把同步的time.sleep替换成异步的asyncio.sleep,后者会主动让出事件循环,让机器人可以同时处理其他任务,不会阻塞整个服务。
修改后的代码:
import asyncio from discord import app_commands # 假设tree是已初始化的app_commands.CommandTree实例 @tree.command( name = "long-pong", description = "long pong" ) @app_commands.describe( nothing = "Nothing", toseehere = "to see here" ) async def requestCalendar(ctx, nothing:str, toseehere:str): await ctx.response.defer(ephemeral=True) # 用asyncio.sleep替代time.sleep await asyncio.sleep(10) await ctx.followup.send("Pong")
额外注意
如果你的长耗时功能是CPU密集型任务(比如大量计算),仅用asyncio.sleep还不够,需要把这类任务放到线程池或进程池执行,避免占用事件循环:
import asyncio from concurrent.futures import ThreadPoolExecutor from discord import app_commands def cpu_intensive_task(): # 这里是你的CPU密集型代码 import time time.sleep(10) return "Pong" @tree.command( name = "long-pong", description = "long pong" ) @app_commands.describe( nothing = "Nothing", toseehere = "to see here" ) async def requestCalendar(ctx, nothing:str, toseehere:str): await ctx.response.defer(ephemeral=True) # 在线程池中执行同步任务 result = await asyncio.get_event_loop().run_in_executor(ThreadPoolExecutor(), cpu_intensive_task) await ctx.followup.send(result)
内容的提问来源于stack exchange,提问作者thekingoflorda
相关产品推荐
相关产品推荐

