我有这个代码:
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("TEST")
@app_commands.command(name="setup", description="setup")
async def setup(self, interaction):
await interaction.response.send_message("test")
async def setup(bot):
await bot.add_cog(Test(bot))
问题是,当加载 cog 时,它不会打印“TEST”,并且 on_ready 中的代码似乎没有触发。
我在输出中没有收到任何错误,并且我不认为 on_ready 被触发,但是
async def on_message(self, message)
工作得很好。可能是什么问题?
这就是 main.py 的样子:
import os
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
async def load():
print("Loading cogs:")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
print(filename)
await bot.load_extension(f'cogs.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
await load()
@bot.command()
async def sync(ctx):
if ctx.author.id == MY_USER_ID:
b = await bot.tree.sync()
await ctx.send("Currently synced " + str(len(b)) + " commands!")
print("Sync command was issued, synced " + str(len(b)) + " commands!")
else:
await ctx.send('You must be me to use this command!')
@bot.command()
async def reload(ctx):
if ctx.author.id == MY_USER_ID:
print("RELOADING SELECTED COGS:")
await ctx.send("Succesfully reloaded these cogs:")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await ctx.send(filename)
await bot.reload_extension(f'cogs.{filename[:-3]}')
else:
await ctx.send('You must be me to use this command!')
with open('token.txt', 'r') as file:
bot_token = file.read().strip()
bot.run(bot_token)
请注意,您的齿轮是在
on_ready
事件触发后加载的。我建议您在启动机器人之前加载您的齿轮:
import asyncio
async def main():
async with bot:
print("Loading cogs:")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
print(filename)
await bot.load_extension(f'cogs.{filename[:-3]}')
await bot.start(bot_token)
asyncio.run(main())
通过这种方式启动您的机器人,您可以删除
load()
函数,也可以将其从 on_ready
事件中删除。