gpt4 book ai didi

discord.py - 如何在 discord.py 中使用高级命令处理

转载 作者:行者123 更新时间:2023-12-05 09:35:23 26 4
gpt4 key购买 nike

所以我的机器人开始有很多命令,并且在 main.py 上变得有点困惑。我知道有一种方法可以将命令存储在其他文件中,然后在 discord.js 上触发它们时将它们应用于 main.py。在 discord.py 上也可以吗?

最佳答案

这些东西称为“齿轮”,您可以为事件设置齿轮,也可以为其他类别设置齿轮。这是一个例子:

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")

async def setup(bot):
await bot.add_cog(ExampleCog(bot))

每当您使用 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.

拥有 cogs 的一个好处是您不需要每次都重新启动机器人,您只需执行 !reload <cogname> , !unload <cogname> , 或 !load <cogname>为了使这些命令起作用,您需要下面的代码。

重新加载下面的齿轮

@bot.command()
@commands.is_owner()
async def reload(ctx, *, name: str):
try:
await bot.reload_extension(f"cogs.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f'"**{name}**" Cog reloaded')

在下方卸载 Cog

@bot.command()
@commands.is_owner()
async def unload(ctx, *, name: str):
try:
await bot.unload_extension(f"cogs.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f'"**{name}**" Cog unloaded')

在下面加载齿轮

@bot.command()
@commands.is_owner()
async def load(ctx, *, name: str):
try:
await bot.load_extension(f"cogs.{name}")
except Exception as e:
return await ctx.send(e)
await ctx.send(f'"**{name}**" Cog loaded')

注意:该代码可能不适用于斜杠命令以确保它可以,请使用 @bot.tree.app_command()而不是 @bot.command()@app_command()而不是 @commands.command() discord.py 2.0 可以正常使用斜杠命令。

我希望你能理解所有这些。我花了大约一个小时来写这篇文章。

您可以从 Senarc 获得有关此 Discord Server 的更多帮助

最后,祝你有美好的一天,祝你的机器人好运。

关于discord.py - 如何在 discord.py 中使用高级命令处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65902252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com