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

如何在Nextcord中获取消息作者的最高角色名称并赋值变量

在Nextcord中获取消息作者的最高角色名称

直接利用Nextcord内置的Member.top_role属性就能轻松获取用户的最高角色,无需手动排序角色列表。以下是具体实现代码:

1. 在命令中使用

import nextcord
from nextcord.ext import commands

# 启用必要的意图,必须包含members和messages意图
intents = nextcord.Intents.default()
intents.members = True
intents.messages = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.command()
async def check_top_role(ctx):
    # 获取命令调用者的Member对象
    member = ctx.author
    # 获取最高角色并提取名称赋值给变量
    top_role_name = member.top_role.name
    
    # 示例:输出结果
    await ctx.send(f"你的最高角色是:{top_role_name}")

bot.run("你的机器人令牌")

2. 在消息事件中使用

@bot.event
async def on_message(message):
    # 忽略机器人自身发送的消息
    if message.author.bot:
        return
    
    # 获取消息发送者的最高角色名称并赋值
    top_role_name = message.author.top_role.name
    
    # 示例:输出结果
    await message.channel.send(f"你的最高角色是:{top_role_name}")
    
    # 保留命令功能必须添加此行
    await bot.process_commands(message)

注意事项

  • 必须启用members意图,否则无法正确获取用户的角色信息,创建Bot实例时需配置好对应意图。
  • 如果用户只有默认的@everyone角色,top_role会返回该角色,名称为@everyone。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 22:43:12