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

如何解决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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:31:02