使用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实例的属性。
修正步骤
- 替换
discord.Interaction.user为回调函数参数中的interaction.user - 通过
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
相关产品推荐
相关产品推荐

