刚接触不和谐机器人时遇到加载齿轮问题寻求一些指导
bot.py
import discord
import os
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('TOKEN')
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print("Bot is ready to be used!")
@bot.command()
async def load_extension(ctx, extension_name):
try:
bot.load_extension(f'cogs.{extension_name}')
await ctx.send(f'Extension {extension_name} loaded.')
except Exception as e:
await ctx.send(f'Error loading extension: {e}')
if __name__ == "__main__":
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
bot.run(token)
cogs/newgame.py
from discord.ext import commands
import requests
from random import randrange
class NewGameCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def newgame(self, ctx):
# Game logic
def setup(bot):
bot.add_cog(NewGameCog(bot))
我收到运行时警告,但我似乎无法修复
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2023-10-18 01:54:39 INFO discord.client logging in using static token
2023-10-18 01:54:40 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: hidden).
Bot is ready to be used!
我可以让 bot.py 文件中的所有内容在没有 cogs 的情况下正常工作
一旦我更改代码以添加像上面的代码那样的齿轮,就会遇到问题
bot.load_extension
是一个异步函数,必须等待。简单来说,
await bot.load_extension(f'cogs.{extension_name}')