如何让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
相关产品推荐
相关产品推荐

