Discord机器人Cog加载报错:coroutine未await问题求助
Discord Bot Cog加载/卸载功能修复
试过Stack Overflow上所有相关帖子都无效,现描述问题及需求:
机器人能正常上线,但.ping命令无响应(Cog未加载),启动程序和执行.load example时均出现报错:RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited client.load_extension(f'cogs.{filename[:-3]}')
需要实现Cog的加载/卸载功能,用来启用/禁用机器人特性。
现有代码
main.py
import discord import os from discord.ext import commands import asyncio intents = discord.Intents.all() intents.members = True client = commands.Bot(command_prefix=".", intents=intents, help_command=None) @client.command() async def load(ctx, extension): client.load_extension(f'cogs.{extension}') @client.command() async def unload(ctx, extension): client.unload_extension(f'cogs.{extension}') for filename in os.listdir('./cogs'): if filename.endswith('.py'): client.load_extension(f'cogs.{filename[:-3]}') client.run('TOKEN')
example.py(Cog文件)
import discord from discord.ext import commands class Example(commands.Cog): def __init__(self, client): self.client = client # Events @commands.Cog.listener() async def on_ready(self): print('Bot is online.') #Commands @commands.command() async def ping(self, ctx): await ctx.send('Pong!') def setup(client): client.add_cog(Example(client))
已尝试的无效操作
- 给
setup函数添加await - 改成
async main()结构启动机器人 - 将加载Cog的循环放入异步函数并添加
await
解决方案
核心问题是discord.py 2.0+版本中,load_extension和unload_extension已改为异步方法,必须用await调用,以下是修正后的完整代码:
修正后的main.py
import discord import os from discord.ext import commands import asyncio intents = discord.Intents.all() intents.members = True client = commands.Bot(command_prefix=".", intents=intents, help_command=None) @client.command() async def load(ctx, extension): await client.load_extension(f'cogs.{extension}') await ctx.send(f"已加载 {extension} 模块") @client.command() async def unload(ctx, extension): await client.unload_extension(f'cogs.{extension}') await ctx.send(f"已卸载 {extension} 模块") async def load_initial_cogs(): # 异步加载初始Cog for filename in os.listdir('./cogs'): if filename.endswith('.py'): await client.load_extension(f'cogs.{filename[:-3]}') async def main(): async with client: await load_initial_cogs() await client.start('你的TOKEN') asyncio.run(main())
关键修改点说明
- 异步方法加await:所有调用
load_extension和unload_extension的地方都添加await,解决协程未等待的警告 - 异步启动流程:使用
async with client和client.start()替代原有的client.run(),确保异步加载Cog的操作能在机器人启动前完成 - 保留原Cog结构:example.py中的
setup函数无需修改,保持同步写法即可
验证:启动机器人后,.ping命令可正常响应,.load example和.unload example能成功执行且无警告。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

