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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:15:45