所以我的机器人开始有很多命令,它在 main.py 上变得有点乱。我知道有一种方法可以将命令存储在其他文件中,然后在 discord.js 上触发它们时将它们应用到 main.py。在 discord.py 上也有可能吗?
小智 5
有些东西叫做“cogs”,你可以有一个用于事件的cog,还有一些用于其他类别。下面是一个例子:
import discord
from discord.ext import commands, tasks
class ExampleCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command() # You use commands.command() instead of bot.command()
async def test(self, ctx): # you must always have self, if not it will not work.
await ctx.send("**Test**")
@commands.Cog.listener() # You use commands.Cog.listener() instead of bot.event
async def on_ready(self):
print("Test")
def setup(bot):
bot.add_cog(ExampleCog(bot))
Run Code Online (Sandbox Code Playgroud)
每当您使用时,请在使用齿轮时bot将其替换为self.bot。当您使用 cogs 时,您需要将 cog 文件放在一个单独的文件夹中。您应该创建一个名为“ ./cogs/examplecog.py”的文件夹
在您的主 bot 文件中,您应该具有下面编写的代码,以便 bot 读取 cog 文件。
for file in os.listdir("./cogs"): # lists all the cog files inside the cog folder.
if file.endswith(".py"): # It gets all the cogs that ends with a ".py".
name = file[:-3] # It gets the name of the file removing the ".py"
bot.load_extension(f"cogs.{name}") # This loads the cog.
Run Code Online (Sandbox Code Playgroud)
使用 cogs 的一个好处是,您不需要每次希望新代码工作时都重新启动机器人,只需执行!reload <cogname>、!unload <cogname>、 或!load <cogname>并且要使这些命令工作,您需要下面的代码。
重新加载下面的齿轮
@bot.command()
@commands.is_owner()
async def reload(ctx, *, name: str):
try:
bot.reload_extension(f"cogs.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f'"**{name}**" Cog reloaded')
Run Code Online (Sandbox Code Playgroud)
卸载下面的齿轮
@bot.command()
@commands.is_owner()
async def unload(ctx, *, name: str):
try:
bot.unload_extension(f"cogs.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f'"**{name}**" Cog unloaded')
Run Code Online (Sandbox Code Playgroud)
在下方加载齿轮
@bot.command()
@commands.is_owner()
async def load(ctx, *, name: str):
try:
bot.load_extension(f"cogs.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f'"**{name}**" Cog loaded')
Run Code Online (Sandbox Code Playgroud)
我希望你明白这一切。 我花了大约一个小时来写这篇文章。
您可以在此Discord 服务器上获得有关 Discord.py 的更多帮助
最后,祝您有愉快的一天,祝您的机器人好运。
| 归档时间: |
|
| 查看次数: |
1518 次 |
| 最近记录: |