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

discord.py中如何检测Embed内嵌内容中是否存在成员提及?

解答

discord.py没有内置和interaction.message.mentions等效的接口可以直接读取Embed内容中的提及信息,你可以通过以下两种更合理的方案实现需求,避免在消息正文中插入冗余的提及内容:

方案一:通过按钮custom_id传递用户ID(最推荐)

custom_id最大支持100字符长度,完全足够存储操作类型+目标用户ID的组合,这种方式无需额外解析内容,性能和稳定性最高。

修改后的命令代码:

@client.command()
async def modlogs(ctx, member: discord.Member): 
    main=discord.Embed(title=" ", description=f"{ctx.author.mention} please use the buttons below to navigate {member.mention}'s modlogs.", color=0x76dba8)
    main.set_author(name=f"{member}", icon_url = member.avatar_url)
    # 把用户ID拼到custom_id里,用分隔符拆分
    user_id = str(member.id)
    await ctx.send(
        embed = main, # 现在可以删掉正文里的冗余提及了
        components=[[
            Button(style=ButtonStyle.blue, label="Warnings", custom_id= f"warnings_{user_id}"),
            Button(style=ButtonStyle.blue, label="Kicks", custom_id= f"kicks_{user_id}"),
            Button(style=ButtonStyle.blue, label="Bans", custom_id= f"bans_{user_id}")
        ]],
    )

修改后的按钮点击事件代码:

@client.event
async def on_button_click(interaction):
    # 拆分custom_id获取操作类型和用户ID
    action, user_id = interaction.custom_id.split("_")
    user_id = int(user_id)
    # 获取成员对象,在线程多的服务器可以用interaction.guild.get_member(user_id)提升速度
    member = await interaction.guild.fetch_member(user_id)
    
    if collection2.count_documents({"_id": member.id}) == 0:
        embed1=discord.Embed(description=f"{member.mention} has no warnings!", color=0xff0000)
        embed1.set_author(name="Error")
        # 后续你的编辑消息逻辑
    else:    
        # 对应操作的逻辑

方案二:正则解析Embed中的提及

如果你确实需要从Embed内容中提取提及,可以通过正则匹配Embed的description、fields等字段中的提及格式(格式为<@用户ID>或<@!用户ID>):

import re
MENTION_REGEX = r'<@!?(\d+)>'

@client.event
async def on_button_click(interaction):
    embed = interaction.message.embeds[0]
    # 搜索description里的提及
    mention_ids = []
    if embed.description:
        mention_ids.extend(re.findall(MENTION_REGEX, embed.description))
    # 搜索所有field里的提及
    for field in embed.fields:
        if field.value:
            mention_ids.extend(re.findall(MENTION_REGEX, field.value))
    # 去重转成int
    mention_ids = list(set(int(i) for i in mention_ids))
    if not mention_ids:
        # 没有找到提及的处理逻辑
        return
    member = await interaction.guild.fetch_member(mention_ids[0])
    # 后续你的业务逻辑

另外注意你原代码里定义的ram_member = member是全局变量,多用户同时调用命令时会被覆盖,不要用这种方式存临时数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:27:03