You need to enable JavaScript to run this app. Discord.py如何从用户字符串列表生成可@提及以通知选中用户
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py如何从用户字符串列表生成可@提及以通知选中用户

Discord.py 实现嵌入消息中@提及用户并触发通知的方案

第一步:开启必要的权限与意图

你之前遍历服务器成员仅返回机器人自身,是因为没有开启成员权限意图:

  • 前往Discord开发者后台的机器人管理页,开启「Server Members Intent(服务器成员意图)」开关
  • 初始化Bot时显式声明启用成员意图,示例代码:
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True # 启用成员访问权限
bot = commands.Bot(command_prefix="!", intents=intents)

第二步:编写用户名转提及格式的工具方法

Discord中可触发通知的提及格式为<@用户ID>,你可以通过服务器成员对象的mention属性直接获取该格式:

def get_user_mention(guild: discord.Guild, raw_tag: str) -> str:
    # 移除原始文本中的@符号,得到 用户名#标签 格式
    tag = raw_tag.lstrip("@")
    # 按用户名#标签搜索对应服务器成员
    member = guild.get_member_named(tag)
    # 找到成员返回提及格式,找不到返回原文本避免报错
    return member.mention if member else raw_tag

第三步:修改现有代码,替换文本为提及格式

处理你现有列表中的所有用户文本,再嵌入到Embed中,发送时允许提及通知即可:

async def on_message(self, message):
(...)
            # 先批量处理所有列表中的用户文本为提及格式
            processed_list1 = [get_user_mention(message.guild, item) for item in list1]
            processed_list2 = [get_user_mention(message.guild, item) for item in list2]
            processed_list3 = [get_user_mention(message.guild, item) for item in list3]
            processed_dps = [get_user_mention(message.guild, item) for item in dps]

            embed = discord.Embed(title=c.LFG_OVER, description="Party:", color=c.COLOUR_BANANA)
            embed.set_author(name=f"{message.author.display_name}", url="", icon_url=f"{message.author.avatar_url}")
            embed.set_thumbnail(url=c.LFG_TY)

            embed.add_field(name="_", value=f"This is text: {processed_list1[0]}\nThis is text: {processed_list1[1]}\nThis is text: {processed_list2[0]}\nThis is text: {processed_list2[1]}", inline=True)
            embed.add_field(name="_", value=f"This is text: {processed_list3[0]}\nThis is text: {processed_dps[1]}\nThis is text: {processed_list3[2]}\nThis is text: {processed_list3[3]}", inline=True)

            # 发送时添加allowed_mentions参数,允许触发用户提及通知
            await message.channel.send(embed=embed, allowed_mentions=discord.AllowedMentions(users=True))

注意事项

  • 机器人必须与被@的用户处于同一服务器,否则无法获取成员对象生成有效提及
  • 若使用discord.py 2.0及以上版本,成员意图为强制要求开启的权限,未开启时无法获取服务器完整成员列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:30:05