Discord.py v2.1.0:如何获取与消息交互的用户?
在Discord.py v2.1.0中获取交互触发用户的正确方式
你遇到的问题大概率是混淆了「交互触发用户」和「消息作者」的获取路径,以下是不同场景下的正确实现:
1. 按钮/选择菜单等组件交互
对于消息内的按钮、选择菜单这类交互,interaction.user本身就是触发交互的用户,而interaction.message.author才是这条带组件消息的作者(比如机器人或发消息的用户)。
示例代码:
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.event async def on_ready(): await bot.tree.sync() print(f"已登录为 {bot.user}") # 发送带按钮的消息 @bot.tree.command(name="send_button", description="发送一个测试按钮") async def send_button(interaction: discord.Interaction): button = discord.ui.Button(label="点我触发交互") view = discord.ui.View() view.add_item(button) # 绑定按钮回调 async def button_callback(btn_interaction: discord.Interaction): # 这里的btn_interaction.user就是点击按钮的用户 await btn_interaction.response.send_message(f"触发交互的用户:{btn_interaction.user.display_name}", ephemeral=True) button.callback = button_callback await interaction.response.send_message("点击下方按钮测试", view=view) bot.run("你的机器人令牌")
2. 消息上下文菜单交互
如果是通过右键消息调用的上下文菜单命令,interaction.user是使用菜单的用户,目标消息的作者需要通过interaction.target.author获取。
示例代码:
@bot.tree.context_menu(name="查看交互用户") async def check_interactor(interaction: discord.Interaction, message: discord.Message): # interaction.user = 触发菜单的用户 # message.author = 被右键的消息的作者 await interaction.response.send_message( f"触发交互的用户:{interaction.user.name}\n目标消息作者:{message.author.name}", ephemeral=True )
排查要点
如果你仍然拿到的是消息作者,检查代码中是否误写了interaction.message.author或message.author,而非interaction.user。Discord.py v2.1.0中interaction.user的行为是完全符合预期的,返回的就是触发当前交互的用户。
内容的提问来源于stack exchange,提问作者Heisenberg
相关产品推荐
相关产品推荐

