是否可以将 Discord.py bot 拆分为多个文件?

时间:2021-03-16 20:15:49

标签: python discord discord.py

所以我的 Discord bot 保存在一个文件 (bot.py) 中,并且由于它有很多命令,我的帮助命令必须解释每一个命令,因为 bot 的目标是功能强大且非常用户友好。可以想象,这会占用很多的空间。我想做的是将主要命令放在 bot.py 中,并将所有帮助命令放在一个单独的文件 (help.py) 中,这可能吗?如果是这样,如何?

1 个答案:

答案 0 :(得分:2)

扩展示例

  • 名为 foo.py 的文件
import discord
from discord.ext import commands

@commands.command()
async def baz(ctx):
    await ctx.send("Whatever")


def setup(bot):
    # Every extension should have this function
    bot.add_command(baz)
  • 主文件
bot.load_extension("path.foo") # Path to the file, instead of using a slash use a period
  • 齿轮(可以在主文件中)
class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    def baz(self, ctx):
        await ctx.send("something")

bot.add_cog(MyCog(bot))

结合齿轮和扩展

  • foo.py
import discord
from discord.ext import commands

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    def baz(self, ctx):
        await ctx.send("something")

def setup(bot):
    bot.add_cog(MyCog(bot))
  • 主文件
bot.load_extension("path.foo")

有关详细信息,请查看 cogsextensions 介绍。

另外,我假设您使用的是 commands.Bot 并且您将机器人实例命名为 bot