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

使用Pycord开发Discord Bot时,Modal无法获取用户属性的问题

Pycord Modal获取用户信息异常的解决方法

问题描述

使用Pycord开发Discord Bot时,Modal能正常发送且回调可执行,但获取填写Modal的用户信息出现异常:

  • 调用discord.Interaction.user时,返回<member 'user' of 'Interaction' objects>而非预期的用户属性
  • 尝试访问discord.Interaction.user.name时,报错'member_descriptor' object has no attribute 'name'

调试时能看到discord.interactions.Interaction实例中存在user本地变量,但不清楚如何正确获取User类的属性。

原代码

class MyModal(discord.ui.Modal):
  def __init__(self, *args, **kwargs) -> None:
    super().__init__(*args, **kwargs)

    self.add_item(discord.ui.InputText(label="Enter your prompt here and click submit.", style = discord.InputTextStyle.long))
  
  async def callback(self, interaction: discord.Interaction): # DO NOT alter the callback name
    embed = discord.Embed(title="Modal Results", color=5763719)
    embed.add_field(name="Suggested prompt:", value = self.children[0].value)
    print(discord.Interaction.user) 
    # returns "<member 'user' of 'Interaction' objects>" instead of the user attribute that I expected.
    # embed.set_author(name = discord.Interaction.user.name) <- error: 'member_descriptor' object has no attribute 'name'
    await interaction.response.send_message(embeds=[embed])

@bot.command(description = "Call forth a test Modal.")
async def trymodal(ctx):
  modal = MyModal(title = "Modal via Slash Command")
  await ctx.send_modal(modal)

解决方法

问题核心是你错误调用了类的属性描述符,而非传入的interaction实例的属性。

修正步骤

  1. 替换discord.Interaction.user为回调函数参数中的interaction.user
  2. 通过interaction.user直接访问用户属性(如name、id、avatar等)

修改后的回调代码

async def callback(self, interaction: discord.Interaction):
    embed = discord.Embed(title="Modal Results", color=5763719)
    embed.add_field(name="Suggested prompt:", value=self.children[0].value)
    
    # 正确获取用户实例
    user = interaction.user
    print(user)  # 输出用户对象,例如<Member id=123456789 name="Jeroen" ...>
    embed.set_author(name=user.name, icon_url=user.avatar.url)
    
    await interaction.response.send_message(embeds=[embed])

补充说明

API文档中Interaction.user的类型为Union[User, Member],意思是这个属性可能返回两种对象:

  • User:当用户不在当前服务器时返回
  • Member:当用户在当前服务器时返回
    两者拥有大量通用属性(如name、id),直接访问这些属性即可,无需额外区分类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:55:39