【问题标题】:How do I setup and load a cog into discord.py?如何设置 cog 并将其加载到 discord.py 中?
【发布时间】:2021-02-20 07:24:48
【问题描述】:

我正在尝试使用 discord.py 命令扩展中的内置帮助命令,但我似乎无法加载 cog,因此我可以对命令进行排序。这是我当前的代码:

bot = commands.Bot(command_prefix='fd!', description=description, intents=intents)

class Testing(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
    self._last_member = None
  
  @commands.command(description = "Sends a test message")
  async def test(ctx):
    await message.channel.send("Test")

#extra code for other un-grouped commands here

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

#bot.run stuff here

我错过了什么吗?当我运行命令 (fd!test) 时,它说该命令不存在,而当我运行 fd!help 时,它没有列出,cog 也没有。

帮助表示赞赏!

【问题讨论】:

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


    【解决方案1】:

    首先,您需要在 cog 文件的顶部添加 import discord 和 from discord.ext import commands。确保您的 cog 文件位于名为 cogs 的文件夹中,该文件夹应与项目的其余部分位于同一文件夹中。在你的主代码中,添加这个来实际加载 cog:

    # loading all cogs
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            bot.load_extension(f'cogs.{filename[:-3]}')
    

    另外,你需要在ctx之前传入self,并且你需要将message.channel.send改为ctx.send:

    @commands.command(description = "Sends a test message")
      async def test(self, ctx):
        await ctx.send("Test")
    

    【讨论】:

    • 这几乎完美无缺,当我尝试运行测试命令时,它说'callback for test command is missing 'ctx' parameter',当我尝试 fd!help test 它说'ValueError :缺少上下文参数'。有什么想法吗?
    • @finalerock44 在您的test 命令中,尝试使用await ctx.send("Test") 而不是await message.channel.send("Test")
    • 似乎没有用,打印的错误和以前一样
    • @finalerock44 哦等等,在你的test 命令中,尝试在ctx 之前传入self,就像这样:async def test(self, ctx):
    猜你喜欢
    • 2019-11-11
    • 2021-04-10
    • 2021-01-23
    • 2021-05-18
    • 2021-06-22
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多