使用discord.py发送TextInput时触发HTTPException错误求助
问题原因及解决方案
你的代码确实存在错误,并非discord.py库的问题。
Discord的API规则明确规定:TextInput(文本输入框)是**模态框(Modal)**的专属组件,不能直接添加到普通View中发送。你遇到的错误提示,就是因为Discord服务器拒绝了这种不符合组件类型规则的请求。
正确实现方式
要使用TextInput,必须遵循以下逻辑:
- 创建
Modal对象,将TextInput添加到这个模态框内 - 通过交互事件(比如按钮点击)触发模态框弹出
示例代码(群内触发)
async def on_message(self, message): if message.content.startswith('!'): # 定义点击后触发模态框的按钮 class InputTriggerButton(discord.ui.Button): async def callback(self, interaction: discord.Interaction): # 构建模态框 input_modal = discord.ui.Modal(title="测试输入") # 向模态框添加文本输入组件 input_modal.add_item(discord.ui.TextInput(label="test")) # 弹出模态框 await interaction.response.send_modal(input_modal) # 创建视图并添加按钮 view = discord.ui.View() view.add_item(InputTriggerButton(label="打开输入框")) # 发送带按钮的消息引导用户交互 await message.channel.send("点击下方按钮输入内容:", view=view)
示例代码(私信触发)
如果需要直接向用户发起输入请求,可通过私信触发模态框:
async def on_message(self, message): if message.content.startswith('!'): try: input_modal = discord.ui.Modal(title="测试输入") input_modal.add_item(discord.ui.TextInput(label="test")) # 向消息发送者发送模态框 await message.author.send_modal(input_modal) except discord.Forbidden: await message.channel.send("无法向你发送私信,请检查隐私设置")
关键规则提醒
- 普通
View仅支持添加按钮、选择菜单、链接按钮这类可交互组件(对应错误提示里的类型2、3、5等) TextInput必须嵌套在Modal中使用,且模态框只能通过交互响应(如interaction.response.send_modal)触发,不能直接用channel.send发送
内容的提问来源于stack exchange,提问作者AyameBLR
相关产品推荐
相关产品推荐

