discord.py开发中替代time.sleep()的更优方案是什么?
问题原因
你当前使用的time.sleep()是同步阻塞函数,会直接卡住discord.py依赖的异步事件循环,导致10秒等待期间机器人所有其他功能都无法响应,这就是全局停滞的根本原因。
修改核心逻辑
- 把同步的
time.sleep()替换为异步非阻塞的asyncio.sleep(),调用时必须加await关键字,等待期间不会影响机器人其他功能运行 - 发送回复时直接保存返回的回复消息实例,无需单独在
on_message事件中额外做判断处理,减少冗余代码 - 也可以直接使用discord.py内置的
delete(delay=秒数)参数,底层自动实现延时删除逻辑,代码更简洁
修改后可用代码
最优精简版(无需单独写on_message删除逻辑)
# Delete the referred to message @client.event async def on_reaction_add(reaction, user): # <A bunch of other irrelevant code> if successCounter == 1: # 保存刚发送的回复消息对象 reply_msg = await reaction.message.reply("Image successfully added!") # 内置delay参数实现延时删除,无需手动写sleep逻辑 await reaction.message.delete(delay=10) await reply_msg.delete(delay=10)
如果你需要保留原有on_message逻辑的修改版
import asyncio # 只需要导入一次,放在代码顶部即可 # Delete the referred to message @client.event async def on_reaction_add(reaction, user): # <A bunch of other irrelevant code> if successCounter == 1: await reaction.message.reply("Image successfully added!") await asyncio.sleep(10) await reaction.message.delete() # Delete the "Image successfully added!" message @client.event async def on_message(message): # 必须加这行,否则你后续写的所有指令监听都会失效 await client.process_commands(message) if message.author.id == botID: if message.reference is not None: await asyncio.sleep(10) await message.delete()
注意事项
- 所有异步方法调用必须加
await关键字,否则会出现协程未等待的报错,功能无法正常执行 - 不要在discord.py的异步事件回调函数中使用任何同步阻塞工具(比如
time.sleep、requests等),一律使用对应的异步替代方案(asyncio.sleep、aiohttp等),否则都会导致机器人全局卡住
内容的提问来源于stack exchange,提问作者throwawayaccount23135
相关产品推荐
相关产品推荐

