求助:TypeError: object NoneType can't be used in 'await' expression报错问题
问题解决:Discord机器人中TypeError: object NoneType can't be used in 'await' expression
错误原因
time.sleep()是同步函数,执行时会直接阻塞整个事件循环,而且它没有返回可等待对象,所以用await修饰会抛出NoneType相关错误。如果直接去掉await,同步睡眠会导致机器人在这2秒内完全无法响应其他事件,表现为“无法正常运行”。
解决方案
替换同步的time.sleep()为异步的asyncio.sleep(),步骤如下:
- 导入
asyncio模块 - 将
await time.sleep(2)替换为await asyncio.sleep(2)
修改后的完整代码:
import asyncio import discord from discord.ext import commands # 初始化机器人(根据你的实际配置调整) bot = commands.Bot(command_prefix='!', intents=discord.Intents.all()) snipe_message_author = {} snipe_message_content = {} @bot.event async def on_message_delete(message): snipe_message_author[message.channel.id] = message.author snipe_message_content[message.channel.id] = message.content await asyncio.sleep(2) # 替换为异步睡眠函数 del snipe_message_author[message.channel.id] del snipe_message_content[message.channel.id] # 运行机器人 bot.run('你的机器人令牌')
说明
asyncio.sleep()是专为异步环境设计的睡眠函数,它会在睡眠期间释放事件循环,让机器人可以正常处理其他消息、事件,不会造成阻塞,同时它返回可等待对象,能安全用await修饰。
内容的提问来源于stack exchange,提问作者Matine Elmsafi
相关产品推荐
相关产品推荐

