如何创建支持并发处理的Discord命令函数 避免全局执行阻塞
修复方案
问题原因
discord.py 基于异步事件循环运行,你代码中使用的time.sleep(10)是同步阻塞方法,调用后会直接卡住整个事件循环线程,期间所有其他命令的处理都会被暂停,直到阻塞结束。
修改步骤
- 导入异步IO库
asyncio - 将
sleep_now方法中的同步睡眠替换为异步非阻塞的asyncio.sleep
修改后完整代码
import asyncio from discord.ext import commands class Hello(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print(f'{self.__class__.__name__} Cog is ready') @commands.command() async def hello(self, ctx): await ctx.send('Hello partner!') @commands.command() async def sleeper(self, ctx): await self.sleep_now() await ctx.send('I have been sleeping for 10 seconds') async def sleep_now(self): # 替换为异步睡眠,不会阻塞事件循环 await asyncio.sleep(10) def setup(client): client.add_cog(Hello(client))
效果验证
修改后运行流程和你的预期完全一致:
- 输入
!sleeper后立即输入!hello,机器人会先响应Hello partner! - 等待10秒后,机器人再发送
I have been sleeping for 10 seconds
内容的提问来源于stack exchange,提问作者Zoey Malkov
相关产品推荐
相关产品推荐

