【问题标题】:How to load multiple cogs in Python 3如何在 Python 3 中加载多个 cog
【发布时间】:2021-03-20 00:52:39
【问题描述】:

我正在制作一个 Discord 机器人,并且必须加载 2 个 cogs cogs/foo.pycogs/fooo.py。我想加载它们,所以我在我的代码中这样做了:

@bot.event
async def on_ready():
    print('UwU')
    bot.load_extension("cogs.foo")
    bot.load_extension("cogs.fooo")

这是我的齿轮:

import discord
from discord.ext import commands

class Cog(commands.Cog):
    def __init__(self,bot):
        self.bot = bot
    @commands.command()
    def Foo(self,ctx):
        await ctx.send("Foo")

def setup(bot):
    bot.add_cog(Cog(bot))

而且,这是我运行代码后得到的错误:

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fooo' raised an error: CommandRegistrationError: The alias n is already an existing command or alias.

因此,它成功加载了第一个 cog,但在第二个上引发了错误。

【问题讨论】:

    标签: python python-3.x discord discord.py discord.py-rewrite


    【解决方案1】:

    Maybe this can help? 它是关于如何加载 cogs 以及它们如何工作的示例。 要加载多个 cog,请执行以下操作:

        for cog in initial_extensions:
            client.load_extension(cog)
    

    如果您单击链接并阅读代码,您就会知道initial_extensions 是什么。

    【讨论】:

      【解决方案2】:

      使用简单的 for 循环和os.listdir

      import os
      
      for f in os.lisdir('./cogs'):
          if f.endswith('.py'):
              bot.load_extension(f'cogs.{f[:-3]}')
      

      另外这个错误意味着已经有一个名为n的命令,所以检查你的cod并检查每个命令是否都有一个唯一的名称

      【讨论】:

      • 是的,虽然我没有名为n 的命令或别名,这就是我感到困惑的原因。而且,即使我确实检查了我的代码并且没有名为 e 的命令或别名,它仍然给出相同的错误;-;.
      【解决方案3】:

      你可以使用

      for filename in os.listdir("./cogs"):
          if filename.endswith(".py"):
              client.load_extension(f"cogs.{filename[:-3]}")
              print("Cog Loaded!")
      

      要导入超过 1 个齿轮。 编码愉快!

      【讨论】:

        猜你喜欢
        • 2018-08-24
        • 2020-10-24
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 2021-10-26
        • 2021-05-12
        • 2021-06-30
        相关资源
        最近更新 更多