Discord.py bot.load_extension 不起作用

问题描述 投票:0回答:1


import os

import random

import math

import discord





from discord.ext import commands









intents = discord.Intents.default()



intents.message_content = True

intents.members = True



client = discord.Client(intents=intents)





bot = commands.Bot(command_prefix="$", intents=intents)



  if file_.endswith(".py"):

    print(file_[:-3])

    bot.load_extension(f"cogs.{file_[:-3]}")

我正在尝试从其他名为levels.py的文件加载扩展名 但是当我使用 bot.load_extension 时。它给了我一个错误:

BotBase.load_extension 从未被等待过。

我怎样才能解决这个问题,我从 YouTube 教程中得到这个,我的代码与他类似,所以出了什么问题

python discord
1个回答
0
投票

错误消息“BotBase.load_extension was never waiting”表示您尝试在不使用await关键字的情况下调用异步函数。在Discord.py中,load_extension方法是异步的,这意味着它必须等待才能正常运行。 要解决此问题,请确保在异步上下文中使用 bot.load_extension 并使用 wait 关键字。以下是如何在异步事件处理程序中加载扩展的示例:

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

bot = commands.Bot(command_prefix="$", intents=intents)

# This event triggers when the bot is ready
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')
    try:
        # Use `await` to load the extension
        await bot.load_extension("cogs.levels")
        print("Extension 'cogs.levels' loaded successfully")
    except Exception as e:
        print(f"Failed to load extension 'cogs.levels': {e}")

# Run the bot with your token
bot.run('YOUR_BOT_TOKEN')

确保levels.py文件位于名为cogs的子目录中,并且具有如下设置方法:

# levels.py
from discord.ext import commands

class Levels(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

# Other cog-related code...

# The setup function is necessary for loading the extension
def setup(bot):
    bot.add_cog(Levels(bot))

请记住将“YOUR_BOT_TOKEN”替换为真实的机器人令牌。另外,请勿公开透露您的机器人令牌,因为它可能会被用来控制您的机器人。 最后,确保您的脚本在正确安装 Discord.py 库且最新版本的环境中执行。

© www.soinside.com 2019 - 2024. All rights reserved.