Discord.py 2.1.0加载扩展报错RuntimeWarning:协程未被等待
解决:coroutine 'BotBase.load_extension' was never awaited 错误
错误原因
discord.py 2.0及以上版本中,Bot.load_extension已改为异步协程方法,直接调用会因未等待协程执行触发警告。
修复步骤
方法1:使用异步入口函数加载扩展
修改main.py的代码结构,将加载扩展的逻辑放在异步函数中,通过asyncio.run()启动:
import os import asyncio import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True # 根据需求开启所需权限 client = commands.Bot(command_prefix='!', intents=intents) async def load_extensions(): # 遍历commands目录加载所有扩展 for filename in os.listdir("./commands"): if filename.endswith(".py"): await client.load_extension(f"commands.{filename[:-3]}") async def main(): await load_extensions() await client.start('你的机器人TOKEN') if __name__ == "__main__": asyncio.run(main())
方法2:使用setup_hook方法(官方推荐)
自定义Bot类并实现setup_hook异步方法,在机器人启动前自动加载扩展:
import os import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True class MyBot(commands.Bot): async def setup_hook(self): # 加载commands目录下的所有扩展 for filename in os.listdir("./commands"): if filename.endswith(".py"): await self.load_extension(f"commands.{filename[:-3]}") client = MyBot(command_prefix='!', intents=intents) client.run('你的机器人TOKEN')
注意事项
- 所有调用
load_extension的代码必须处于异步上下文中,不能在同步函数里直接调用异步方法。 - Replit环境无需额外配置,只要代码结构符合异步规范即可正常运行。
内容的提问来源于stack exchange,提问作者Technical Support and vids
相关产品推荐
相关产品推荐

