如何解决discord.py中的RuntimeWarning问题?
解决Discord机器人加载Cogs时的RuntimeWarning问题
问题原因
你碰到的RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited错误,核心原因是discord.py 2.0及以上版本中,load_extension已改为异步协程方法,必须用await关键字调用,否则会触发未等待协程的警告。
解决方案
需要把加载Cogs的逻辑放到异步函数中,用await调用load_extension,以下是两种常用实现方式:
方式1:在on_ready事件中加载(推荐)
将加载逻辑移到异步的on_ready事件里:
import os import discord from discord.ext import commands client = commands.Bot(command_prefix='!', intents=discord.Intents.all()) @client.event async def on_ready(): # 遍历cogs目录加载所有.py文件 for filename in os.listdir('./cogs'): if filename.endswith('.py'): await client.load_extension(f"cogs.{filename[:-3]}") print(f'已登录为 {client.user}') client.run('你的机器人令牌')
方式2:使用异步主函数
如果不想在on_ready中处理,可单独写异步加载函数和入口:
import os import discord from discord.ext import commands import asyncio client = commands.Bot(command_prefix='!', intents=discord.Intents.all()) async def load_cogs(): for filename in os.listdir('./cogs'): if filename.endswith('.py'): await client.load_extension(f"cogs.{filename[:-3]}") async def main(): await load_cogs() await client.start('你的机器人令牌') if __name__ == "__main__": asyncio.run(main())
额外注意点
- 确保你的Cog文件符合规范,每个Cog需继承
commands.Cog,并包含异步的setup函数:
# cogs/example.py示例代码 from discord.ext import commands class Example(commands.Cog): def __init__(self, client): self.client = client async def setup(client): await client.add_cog(Example(client))
- 若你仍在使用discord.py v1.x版本,
load_extension是同步方法,但v1.x已停止维护,建议升级到v2.x版本并采用异步调用方式。
内容的提问来源于stack exchange,提问作者Ivan Parvanov
相关产品推荐
相关产品推荐

