on_message Cog 触发 2 条机器人回复

时间:2021-07-02 10:55:17

标签: python discord discord.py

我正在开发一个随机使用的 discord.py 机器人,我第一次尝试在 Cog 中创建我的 on_message 事件,我查看了不同的示例并尝试了这个:

import discord

from discord.ext import commands


class AntiSpam(commands.Cog):

    def __init__(self, client):
        self.client = client

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

        if len(message.content) > 350: # Anti-Spam for message lenght
            await message.delete()
            await message.channel.send(f'{message.author.mention}, <a:cat_no:843799913958866955> You are **not** allowed to send unnecessarily long and annoying messages in this server!', delete_after=5)

        await self.client.process_commands(message)

def setup(client):
    client.add_cog(AntiSpam(client))

现在,一切都很完美,直到我在添加该事件后尝试使用命令,它回复了 2 个答案,例如,我使用了一个简单的“hello”命令,它会回复 "{ctx.author.mention} World" 但是,现在它会用该消息回复 2 次而不是一次,我见过有人问某人是否有 on_message 事件,但从未继续。 我还尝试关闭我运行的每个 python 文件,通过 client.logout() 重新启动我的电脑来杀死机器人,但仍然出现同样的错误,有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

您不在侦听器中处理命令,只在事件中处理,只需删除最后一行

    @commands.Cog.listener()
    async def on_message(self, message):
        if len(message.content) > 350: # Anti-Spam for message lenght
            await message.delete()
            await message.channel.send(f'{message.author.mention}, <a:cat_no:843799913958866955> You are **not** allowed to send unnecessarily long and annoying messages in this server!', delete_after=5)

你可以有多个监听器(用 commands.Cog.listener()bot.listen() 修饰)但只能有一个事件(用 bot.event 修饰)