如何让我的 Python Discord 机器人检查消息是否由机器人本身发送?

How can I make my Python Discord bot check if a message was sent by the bot itself?

我正在使用 Python (v. 3.6.1) 编写一个 Discord 机器人,它检测一个频道中发送的所有消息并在同一频道中回复它们。但是,机器人自己回复消息,导致死循环。

@bot.event
async def on_message(message)
    await bot.send_message(message.channel, message.content)```

我该如何解决这个问题?

message class contains information on the message's author, which you can utilize to determine whether or not to respond to the message. author is a Member object (or its superclass User 如果频道是私有的),它具有 id 属性 但也支持用户之间的直接逻辑比较。

例如:

@bot.event
async def on_message(message):
    if message.author != bot.user:
        await bot.send_message(message.channel, message.content)

应按预期运行

我知道这个问题是几年前的问题了,但万一其他人像我一样在谷歌上搜索这个问题,传递给 on_message 的消息对象内部有一个作者对象,它有一个名为“ bot" 是真还是假(如果是机器人则为真)。因此,您可以通过在开头包含此 if 语句来配置您的函数以安全地忽略其他机器人的任何消息:

def on_message(self, message):
    if (message.author.bot):
        return #if this is true: then it is by a bot.