如何用Discord.py机器人实现!nickname命令显示服务器昵称?
实现Discord.py的!nickname命令获取服务器昵称
直接调用message.author无法获取服务器昵称是因为它返回的是User对象,仅包含用户的全局账号信息,不包含服务器专属的自定义昵称。要获取服务器内的昵称,需要操作GuildMember对象,以下是两种可靠实现方式:
方式一:使用命令装饰器(官方推荐)
通过commands.Bot的命令装饰器实现时,ctx.author在服务器内触发命令时会自动返回GuildMember对象,无需额外获取:
import discord from discord.ext import commands # 开启必要意图,需先在Discord开发者门户开启Server Members Intent intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.command(name='nickname') async def get_server_nickname(ctx): # 判断是否在服务器环境中 if not ctx.guild: await ctx.send(f"私聊无服务器昵称,你的用户名:{ctx.author.name}") return # 无服务器昵称时返回全局用户名 display_name = ctx.author.nick or ctx.author.name await ctx.send(f"你的服务器昵称:{display_name}") bot.run('你的机器人令牌')
方式二:使用on_message事件手动处理
如果需要通过消息事件直接处理命令,需从对应服务器中获取成员对象:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.event async def on_message(message): # 忽略机器人自身发送的消息 if message.author.bot: return if message.content.strip() == '!nickname': if not message.guild: await message.channel.send(f"私聊无服务器昵称,你的用户名:{message.author.name}") return # 从服务器中获取成员对象 member = message.guild.get_member(message.author.id) if member: display_name = member.nick or member.name await message.channel.send(f"你的服务器昵称:{display_name}") # 必须调用此方法,否则装饰器定义的命令会失效 await bot.process_commands(message) bot.run('你的机器人令牌')
关键注意事项
- 必须在Discord开发者门户的机器人设置中开启
Server Members Intent,否则无法获取成员的昵称信息。 nick属性会在用户未设置服务器昵称时返回None,使用or运算符可以快速兜底到全局用户名。
内容的提问来源于stack exchange,提问作者Rafik Semouma
相关产品推荐
相关产品推荐

