Replit运行Discord测试机器人遇RuntimeWarning问题求助
解决Discord机器人加载Cog时的RuntimeWarning错误
问题原因
discord.py 2.0及以上版本中,Bot.load_extension() 已从同步方法改为异步协程,你直接在同步代码中调用该方法,未用await等待协程执行完成,因此触发了未等待协程的警告。
修复方案
将加载Cog的逻辑移至异步的on_ready事件中(更贴合Discord机器人的生命周期逻辑),用await关键字等待协程执行:
修改后的代码:
import os import discord from discord.ext import commands bot = commands.Bot(command_prefix="!c", intents=discord.Intents.all(), case_insensitive=True) @bot.event async def on_ready(): print(f"{bot.user} is online!") # 在异步事件中加载Cog for filename in os.listdir("./cogs"): if filename.endswith(".py"): try: await bot.load_extension(f"cogs.{filename[:-3]}") print(f"成功加载Cog: {filename[:-3]}") except Exception as e: print(f"加载Cog {filename[:-3]}失败: {str(e)}") bot.run("your_bot_token_here")
额外说明
- 添加
try-except块可以捕获加载Cog时的异常(比如代码语法错误、依赖缺失),便于排查问题。 - 确保cogs目录下的Python文件是合法的Discord Cog格式(需继承
commands.Cog)。
内容的提问来源于stack exchange,提问作者Adam Albustami
相关产品推荐
相关产品推荐

