【问题标题】:How can I use a Python Discord bot cog to read all messages that are sent? on_message does not seem to be working如何使用 Python Discord bot cog 读取所有发送的消息? on_message 似乎不起作用
【发布时间】:2019-09-14 09:16:15
【问题描述】:

我已经正确设置了 cog(我知道,因为我有一个单独的 cog 来处理所有命令,所以 on_message 不会把它们弄乱),但是 on_message 什么也没做。

我已经尝试将它包含到另一个 cog 中,但我仍然没有收到任何错误,它只是不起作用。我也尝试过使用不同形式的@bot.event,但这些都只会导致错误。最后,我知道 cog 正在工作,因为主 .py 中的 on_ready 提醒我它已成功加载。

这是 cog 中应该读取所​​有消息的代码(减去所有导入内容):

class autoresponse(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    async def on_message(self, message):
        print(message.content)

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

这是加载它的代码


@bot.event
async def on_ready():
    print('bot is up')
    await bot.change_presence(status=discord.Status.online, activity=discord.Game("bl help"))
    for cog in [f.replace('.py', "") for f in listdir("cogs") if isfile(join("cogs", f))]:
        try:
            if not "__init__" in cog:
                bot.load_extension("cogs." + cog)
                print("Loaded cog")
        except Exception as e:
            print("Cog {} not loaded!".format(cog))
            traceback.print_exc()

希望机器人应该将所有消息打印到控制台,因为这样我就会知道它的工作原理,并且可以继续我希望它做的其他事情。

【问题讨论】:

    标签: python bots discord discord.py


    【解决方案1】:

    cog 中的事件侦听器需要用commands.Cog.listener 装饰

    @commands.Cog.listener()
    async def on_message(self, message):
        print(message.content)
    

    新式 cogs 的文档can be found here

    【讨论】:

      【解决方案2】:

      请使用齿轮

      class MyClass(commands.Cog):
      
          def __init__(self, bot):
              """ Init function for AutoCommands."""
              self.bot = bot
      
          @commands.Cog.listener()
              async def on_message(self, message: discord.Message):
                  print(message)
      
      def setup(bot: commands.Cog):
          bot.add_cog(MyClass(bot))
      
      

      【讨论】:

        猜你喜欢
        • 2020-08-16
        • 1970-01-01
        • 2021-03-11
        • 2020-08-31
        • 2019-08-23
        • 2020-12-01
        • 2021-03-02
        • 2021-01-12
        • 2021-06-05
        相关资源
        最近更新 更多