RuntimeWarning: coroutine 'BotBase.add_cog'未被等待问题求助
解决Discord Bot的RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited警告
问题原因
discord.py 2.0及以上版本中,Bot.add_cog方法已从同步方法改为异步协程,必须使用await关键字调用。你的代码中直接同步调用了该方法,导致协程从未被等待,触发警告。
解决方案
修改main.py代码,将add_cog调用放在异步上下文环境中,有两种常用方式:
方式一:使用异步main函数包裹
import asyncio import discord from event import Event from discord.ext import commands import sqlite3 import os TOKEN = 'token lol' bot = commands.Bot(command_prefix='+', intents=discord.Intents.all()) async def main(): async with bot: await bot.add_cog(Event(bot)) await bot.start(TOKEN) asyncio.run(main())
方式二:利用bot的setup_hook事件
import discord from event import Event from discord.ext import commands import sqlite3 import os TOKEN = 'token lol' bot = commands.Bot(command_prefix='+', intents=discord.Intents.all()) @bot.event async def setup_hook(): await bot.add_cog(Event(bot)) bot.run(TOKEN)
额外提示
你的代码中使用的sqlite3是同步库,在Discord Bot的异步事件循环中调用可能会阻塞Bot响应,建议改用异步数据库库(如aiosqlite)来优化性能。
内容的提问来源于stack exchange,提问作者Ztuber45
相关产品推荐
相关产品推荐

