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

Pycord斜杠命令中获取提及角色ID报错的问题咨询

解决Pycord斜杠命令获取提及角色ID的问题

错误原因

你当前代码中mention参数默认是字符串类型,而字符串没有mentions属性,因此触发报错。Pycord的斜杠命令参数若不指定类型,会默认按字符串处理,无法直接解析角色提及。

解决方案

方案1:获取单个角色的ID

直接将参数类型指定为discord.Role,Pycord会自动识别用户的角色提及或选择,直接返回Role对象,可直接提取ID:

@bot.slash_command(name="test", description="testing command")
async def test(ctx, role: discord.Option(discord.Role, name="role", description="Mention or select a role.", required=True)):
    # 打印角色ID
    print(f"Role ID: {role.id}")
    # 回复用户
    await ctx.respond(f"目标角色ID:{role.id}")

方案2:获取多个角色的ID

如果需要支持多选角色,将参数类型设为list[discord.Role],即可拿到角色列表,遍历提取每个角色的ID:

@bot.slash_command(name="test", description="testing command")
async def test(ctx, roles: discord.Option(list[discord.Role], name="roles", description="Mention or select multiple roles.", required=True)):
    # 提取所有角色ID
    role_ids = [role.id for role in roles]
    print(f"Role IDs: {role_ids}")
    await ctx.respond(f"选中的角色ID:{', '.join(map(str, role_ids))}")

方案3:从字符串输入中解析角色提及(不推荐)

如果必须通过纯文本输入解析角色提及(比如用户输入带@角色名的文本),可以用正则表达式提取角色ID(角色提及的格式为<@&角色ID>):

import re

@bot.slash_command(name="test", description="testing command")
async def test(ctx, mention_text: discord.Option(str, name="mention_text", description="输入包含角色提及的文本.", required=True)):
    # 匹配角色提及格式,提取ID
    role_id_pattern = r"<@&(\d+)>"
    role_ids = re.findall(role_id_pattern, mention_text)
    
    print(f"提取到的角色ID:{role_ids}")
    # 可选:将ID转换为Role对象(需在服务器上下文)
    roles = [ctx.guild.get_role(int(rid)) for rid in role_ids if ctx.guild.get_role(int(rid))]
    await ctx.respond(f"解析到的角色ID:{', '.join(role_ids)}")

注意事项

优先使用方案1或方案2,因为Pycord内置的discord.Role参数类型会自动处理角色的验证和匹配,无需手动解析,更稳定可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:27