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

如何让discord.py机器人识别对话用户并正确回复用户名?

解决discord.py机器人回复发送指令用户名称的问题

问题说明

你当前的代码会让机器人回复自身名称,而非发送!hi指令的用户名称:

当前代码:

bot = commands.Bot(command_prefix="!", intents=discord.Intents().all())
@bot.command()
async def hi(ctx):
    await ctx.send("hi" +  bot.user.name)

当前实际效果:
Bob: !hi
Bot: hi Bot
Alice: !hi
Bot: hi Bot

预期效果:
Bob: !hi
Bot: hi Bob
Alice: !hi
Bot: hi Alice

错误原因

你使用的bot.user.name获取的是机器人自身的用户名,并非发起指令的用户信息。要获取发送指令的用户,需调用ctx.author对象,它包含了发起指令用户的所有相关信息。

修复后的代码

将bot.user.name替换为ctx.author.name(获取用户注册用户名)或ctx.author.display_name(优先显示用户服务器昵称,无昵称则显示用户名):

bot = commands.Bot(command_prefix="!", intents=discord.Intents().all())
@bot.command()
async def hi(ctx):
    # 使用用户注册用户名回复
    await ctx.send(f"hi {ctx.author.name}")
    # 或者使用用户服务器昵称回复(优先显示昵称)
    # await ctx.send(f"hi {ctx.author.display_name}")

验证效果

修复后执行指令的效果与预期一致:

Bob: !hi
Bot: hi Bob
Alice: !hi
Bot: hi Alice

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:45:28