You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 02:36:29