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

如何让discord.py代码仅对指定bot发送的含指定关键词的embed消息作出反应

实现逻辑说明

discord.py 中Embed内容不会存储在message.content字段中,需通过message.embeds属性读取:

  • message.embeds是列表类型,存储当前消息携带的所有Embed对象
  • 单个Embed对象可读取title(标题)、description(描述)、fields(自定义字段列表)属性获取文本内容
  • 每个field包含name(字段名)和value(字段值)两个文本属性
修改后的代码
import discord

# discord.py v2.x以上必须配置intent,需同时在Discord开发者后台开启对应账号的消息读取权限
client = discord.Client(intents=discord.Intents.all())
token = "<discord token>"
# 自定义你要匹配的关键词列表
TARGET_KEYWORDS = {"test", "你要找的关键词"}
# 目标频道ID
TARGET_CHANNEL_ID = 825437474871312387
# 目标bot的ID
TARGET_BOT_ID = 342644185800769537

@client.event
async def on_message(message):
    # 先过滤非目标频道、非目标bot的消息
    if message.channel.id != TARGET_CHANNEL_ID or message.author.id != TARGET_BOT_ID:
        return
    # 过滤没有Embed的消息,避免报错
    if not message.embeds:
        return
    # 取第一个Embed(常规场景下bot只会发送单个Embed)
    target_embed = message.embeds[0]
    # 拼接Embed所有可检索的文本内容
    all_content = ""
    # 拼接标题
    if target_embed.title:
        all_content += target_embed.title + " "
    # 拼接描述
    if target_embed.description:
        all_content += target_embed.description + " "
    # 拼接所有自定义字段的内容
    for field in target_embed.fields:
        if field.name:
            all_content += field.name + " "
        if field.value:
            all_content += field.value + " "
    # 关键词匹配判断,如需忽略大小写可替换为:if any(keyword.lower() in all_content.lower() for keyword in TARGET_KEYWORDS)
    if any(keyword in all_content for keyword in TARGET_KEYWORDS):
        await message.add_reaction("❤️")
        print("done")

if __name__ == '__main__':
    client.run(token, bot=False)
    print("can you see me?")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:06:00