You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py 1.7.3:如何让机器人被@时回复但被回复时不触发?

解决Discord.py 1.7.3中机器人被@的触发逻辑问题

问题描述

想要实现:机器人仅在被主动@时发送消息For a list of commands, type .help,但当前代码在机器人被回复时也会触发该消息。原代码如下:

@client.event
async def on_message(message):
    if client.user.mentioned_in(message) and message.mention_everyone is False:
        await message.channel.send("For a list of commands, type `.help`")

    await client.process_commands(message)

问题原因

mentioned_in()方法会将回复消息中的附带提及也判定为“被提及”——当用户回复机器人的消息时,Discord会自动将机器人加入message.mentions列表,导致原条件误触发。

解决方案

修改判断逻辑,区分主动@机器人和回复消息时的附带提及:

@client.event
async def on_message(message):
    # 检查机器人是否被直接提及
    if client.user in message.mentions and not message.mention_everyone:
        # 处理回复场景
        if message.reference:
            try:
                # 获取被回复的消息
                referenced_msg = await message.channel.fetch_message(message.reference.message_id)
                # 若仅提及了被回复的机器人,说明是单纯回复,不触发
                if referenced_msg.author == client.user and len(message.mentions) == 1:
                    pass
                else:
                    await message.channel.send("For a list of commands, type `.help`")
            except:
                # 若无法获取被回复消息(如已删除),默认触发提示
                await message.channel.send("For a list of commands, type `.help`")
        else:
            # 非回复场景直接触发
            await message.channel.send("For a list of commands, type `.help`")

    await client.process_commands(message)

逻辑说明

  • 用client.user in message.mentions替代mentioned_in(),明确检查直接提及
  • 针对回复场景:若被回复的是机器人且仅这一个提及,判定为单纯回复,不触发提示;否则(如回复时额外@了机器人)正常触发
  • 增加异常处理,避免因被回复消息已删除导致报错

内容的提问来源于stack exchange,提问作者1HC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:57:20