Python开发Discord机器人时如何在kill命令中获取被@用户的用户名
问题原因
你当前代码中person参数默认接收的是字符串类型,当用户@其他成员时,传入的是Discord提及的原始编码字符串(格式为<@!用户ID>),直接输出就会显示为异常格式,无法自动转为用户名。
解决方法
- 给
person参数添加discord.Member类型注解,discord.py会自动将消息中的@提及解析为对应的成员对象 - 通过成员对象的
.display_name属性获取用户在服务器内的昵称(没有昵称则自动返回全局用户名),输出格式更符合预期 - 可选添加无参数/参数无效的异常处理,避免命令报错
修改后的完整代码如下:
import random import discord from discord.ext import commands # 原有动图列表无需修改 killgifs = ['https://c.tenor.com/1dtHuFICZF4AAAAC/kill-smack.gif' , 'https://c.tenor.com/gQAWuiZnbZ4AAAAC/pokemon-anime.gif' , 'https://c.tenor.com/PJbU0yjG3BUAAAAd/anime-girl.gif' , 'https://c.tenor.com/Re9dglY0sCwAAAAC/anime-wasted.gif'] @bot.command(name='kill') # 指定person参数为discord.Member类型,添加默认值处理无参数场景 async def kill(ctx, person: discord.Member = None): if not person: await ctx.send("你需要@一个用户才能使用该命令") return author = ctx.author embed = discord.Embed(color=discord.Color.red()) # 调用display_name属性获取正确显示名称 embed.set_author(name=f'{author.display_name} kills {person.display_name}') embed.set_image(url=random.choice(killgifs)) await ctx.send(embed=embed)
注意事项
如果你使用的是discord.py 2.0及以上版本,需要额外开启成员意图才能正常解析成员对象:
- 前往Discord开发者平台的Bot管理页,开启
Server Members Intent开关 - 初始化bot时添加意图配置:
intents = discord.Intents.default() intents.members = True bot = commands.Bot(command_prefix=']', intents=intents)
内容的提问来源于stack exchange,提问作者Rovindu Thamuditha
相关产品推荐
相关产品推荐

