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

Python开发Discord机器人时如何在kill命令中获取被@用户的用户名

问题原因

你当前代码中person参数默认接收的是字符串类型,当用户@其他成员时,传入的是Discord提及的原始编码字符串(格式为<@!用户ID>),直接输出就会显示为异常格式,无法自动转为用户名。

解决方法

  1. 给person参数添加discord.Member类型注解,discord.py会自动将消息中的@提及解析为对应的成员对象
  2. 通过成员对象的.display_name属性获取用户在服务器内的昵称(没有昵称则自动返回全局用户名),输出格式更符合预期
  3. 可选添加无参数/参数无效的异常处理,避免命令报错

修改后的完整代码如下:

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及以上版本,需要额外开启成员意图才能正常解析成员对象:

  1. 前往Discord开发者平台的Bot管理页,开启Server Members Intent开关
  2. 初始化bot时添加意图配置:
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=']', intents=intents)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:27:04