【问题标题】:Discord.py commands run twiceDiscord.py 命令运行两次
【发布时间】:2020-06-29 23:58:35
【问题描述】:

我最近在使用 discord.py 和 discord.ext 命令扩展来制作机器人时遇到了一个问题

当我调用一个命令时,它会运行两次,导致许多错误和错误。添加此命令后才开始发生

@commands.command()
    async def afk(self, ctx, userMessage):

        #if user is already afk, remove them from the afk dict, if not add them to it
        if ctx.message.author in self.afkUsers:
            self.afkUsers.pop(ctx.message.author)
        else:
            self.afkUsers[ctx.message.author] = userMessage

但是删除此命令并不能解决问题。我在 heroku 上托管,但停止了它并在我自己的电脑上运行它进行测试,但问题仍然存在。我在命令中使用了打印函数来测试它们是否运行了两次并且其中的字符串输出了两次

我还有一个 on_message 事件

@commands.Cog.listener()
    async def on_message(self, message):
        
        #if a member is mentioned but the member is afk, a message is sent
        textChannel = message.channel
        afkChannel = self.client.get_channel(690550327975346176)
        
        for member in message.mentions:
            if member in self.afkUsers:
                await textChannel.send(f"user is afk- {self.afkUsers[member]}")
            elif member in afkChannel.members:
                await textChannel.send("user is afk")
            

        #allows commands to work with on_message event
        await self.client.process_commands(message)

编辑:这也发生在我的主文件中的一些命令上,但奇怪的是只有其中一些受到影响

【问题讨论】:

  • 您有任何on_message 活动吗?如果有,你能提供吗?
  • 是的,我编辑了帖子以包含它
  • 我用我的机器人尝试了你的代码,我没有遇到任何问题,所以你的问题可能来自其他地方。你确定你停止了你的 heroku 工人吗?
  • 是的,如果我没有,你能告诉我确切的方法吗?不应该是这样,因为我添加了打印两次的打印语句到我的终端,如果它在 heroku 上,它将被发送到 heroku 日志
  • 另外,这与您的问题无关,但如果您希望您的用户能够在 !afk 之后写一个句子,您应该将 async def afk(self, ctx, userMessage): 替换为 async def afk(self, ctx, *, userMessage):

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


【解决方案1】:

您为同一条消息拨打了两次process_commands。这是因为默认的on_message 监听器已经调用了process_commands。因此,您的 cog 中的 on_message 侦听器再次调用它。您应该从 cog on_message 中删除 process_commands 调用。

【讨论】:

  • 我的机器人依赖 on_message 监听器来格式化消息内容并在处理之前检查是谁发送的。有没有办法让 discord.py 默认停止处理命令?
  • 是的,如果您在 bot 本身而不是在 cog 中注册自己的 on_message 侦听器,那么它将替换默认的侦听器。你可以只拥有它pass 而不做任何事情
猜你喜欢
  • 2021-04-16
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2020-10-10
  • 2020-12-31
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多