discord.py添加Cogs遇协程未等待警告及命令未找到问题求助
Discord音乐机器人问题解决:命令未找到+RuntimeWarning处理
问题描述
机器人能正常显示在线,但输入命令时提示“command not found”,每次运行脚本都会弹出RuntimeWarning,提示coroutine 'BotBase.add_cog' was never awaited。尝试直接用await bot.add_cog(help_cog(bot))时会报错。
报错信息
/bin/python3 "/home/r1d0m/Python/Discord Music Bot/main.py" /home/r1d0m/Python/Discord Music Bot/main.py:15: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(help_cog(bot)) RuntimeWarning: Enable tracemalloc to get the object allocation traceback /home/r1d0m/Python/Discord Music Bot/main.py:16: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited bot.add_cog(music_cog(bot))
原main.py代码
import discord from discord.ext import commands from help_cog import help_cog from music_cog import music_cog intents = discord.Intents.all() intents.message_content = True bot = commands.Bot(command_prefix="/", intents = intents) bot.remove_command("help") bot.add_cog(help_cog(bot)) bot.add_cog(music_cog(bot)) with open('/home/r1d0m/Python/Discord Music Bot/token.txt') as redk: contents = redk.read() bot.run(contents)
解决方案
问题根源
discord.py v2.0及以上版本中,Bot.add_cog()改为异步方法,必须在异步上下文内用await调用。全局代码不属于异步环境,直接用await会报错,不用await又会触发RuntimeWarning,导致cog未被正确加载,命令自然无法识别。
修改后的代码
import discord from discord.ext import commands from help_cog import help_cog from music_cog import music_cog intents = discord.Intents.all() intents.message_content = True bot = commands.Bot(command_prefix="/", intents=intents) bot.remove_command("help") # 用setup_hook异步加载cog,这是官方推荐的正确方式 async def setup_hook(): await bot.add_cog(help_cog(bot)) await bot.add_cog(music_cog(bot)) bot.setup_hook = setup_hook with open('/home/r1d0m/Python/Discord Music Bot/token.txt') as redk: contents = redk.read().strip() # 去除token可能带的换行符,避免登录失败 bot.run(contents)
说明
- 使用
setup_hook方法,bot启动时会自动在异步环境中执行这个函数,正确awaitadd_cog,解决RuntimeWarning。 - cog被正确加载后,里面的命令会注册到bot上,“command not found”的问题也会消失。
- 读取token时加
strip(),避免文件末尾的换行符导致token无效,引发登录问题。
内容的提问来源于stack exchange,提问作者Great Gamer
相关产品推荐
相关产品推荐

