我想制作一个带有命令类/组的机器人在它们自己的文件中,例如: 全面的 天赋 对 ...
但我无法将命令同步回 main.py 首先尝试用一个独立的 Cog 文件来做,但是因为那没有用,我切换到下面的代码,因为除了同步之外,它工作得很好
main.py
import discord
from discord.ext import commands
import os
import asyncio
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix="!", intents=intents)
async def load_extensions():
for filename in os.listdir("./Modules"):
if filename.endswith(".py"):
try:
await bot.load_extension(f"Modules.{filename[:-3]}")
print(f"Loaded extension: Modules.{filename[:-3]}")
except Exception as e:
print(f"Failed to load extension {filename[:-3]}: {e}")
async def main():
await load_extensions()
@bot.event
async def on_ready():
print(f'{bot.user} is now running!')
try:
synced = await bot.tree.sync()
print(f"synced {len(synced)} command(s)")
except Exception as e:
print(f"An error occurred: {e}")
bot.run("token")
asyncio.run(main())
Modules.Overall.py
import discord
from discord.ext import commands
class Overall(commands.Cog, name="Overall"):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.slash_command(name="ping")
async def ping(self, ctx: commands.Context):
await ctx.send(f"Pong! Latency: {round(self.bot.latency * 1000)}ms")
@commands.slash_command(name="credits")
async def credits(self, ctx: commands.Context):
embed = discord.Embed(title="Credits", description="Created by [Your Name]")
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(Overall(bot))```
I think it might be becuase something is in the wrong order or is read wrong yet i cant find anything like that.
i was already asking some friend that knows more than me, he said it might be because of the directory. yet from what we found it looks fine:[Folder of the program](https://i.stack.imgur.com/J22tb.png)
commands.Bot.run
阻塞。根据文档:
这个函数必须是最后调用的函数,因为它是阻塞的。这意味着在此函数调用之后事件或任何被调用的事件的注册将不会执行,直到它返回。
所以你应该在其他地方调用
await main()
,例如在你的 on_ready
函数中。