【问题标题】:How do I invoke another command withen a listener/event with Discord.py?如何使用 Discord.py 在侦听器/事件中调用另一个命令?
【发布时间】:2021-04-23 02:37:40
【问题描述】:

所以我想在机器人加入公会时调用命令。在其他 StackOverflows 的帮助下,我尝试了以下方法:

@commands.Cog.listener()
    async def on_guild_join(self, guild):
        setup_cmd = self.bot.get_command('setup')
        await self.bot.invoke(setup_cmd)

我怀疑的一个问题是 invoke() 方法需要一个 ctx,而 on_guild_join 不提供 Context 对象。无论如何,当我尝试这样做时,我得到了这个错误:

Traceback (most recent call last):
  File "C:\Users\brian\.virtualenvs\ComBot-l9j8wB-A\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\c0de_box\projects\Bots\ComBot\cogs\setup_tasks.py", line 14, in on_ready
    await self.bot.invoke(setup_cmd)
  File "C:\Users\brian\.virtualenvs\ComBot-l9j8wB-A\lib\site-packages\discord\ext\commands\bot.py", line 935, in invoke
    if ctx.command is not None:
AttributeError: 'Command' object has no attribute 'command'

那么在这种情况下我将如何调用另一个命令?

【问题讨论】:

    标签: python discord discord.py bots


    【解决方案1】:

    Bot.invokeContext 作为参数,而不是Command 实例,尽管在on_guild_join 事件中无法获取Context,但您应该创建一个函数并在命令中调用它事件

    async def setup_func(self, *args, **kwargs):
        ...
    
    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        await self.setup_func(...)
    
    @commands.command()
    async def setup(self, ctx, ...):
        await self.setup_func(...)
    

    【讨论】:

    • 好吧,最后我无法得到我想要的,所以我只是将它作为命令删除并将其附加到 on_guild_join 侦听器。
    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多