discord.py中能否不通过Modal使用discord.ui.TextInput实现用户名注册?
解决Discord.py无需Modal使用TextInput的问题
首先明确:Discord官方UI交互规则里,discord.ui.TextInput组件**必须嵌套在Modal(模态框)**中才能触发用户输入,无法直接添加到普通View里。你之前尝试直接把TextInput加到View里的写法不符合Discord组件逻辑,所以无法正常运行。
要实现你预期的「使用命令→点击继续→输入用户名→完成注册」流程,可以通过按钮触发Modal的方式实现,以下是完整示例代码:
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 定义包含用户名输入框的Modal class UsernameModal(discord.ui.Modal, title="注册用户名"): username = discord.ui.TextInput( label="请输入你的用户名", placeholder="输入3-20位用户名...", min_length=3, max_length=20, required=True ) async def on_submit(self, interaction: discord.Interaction): # 此处编写用户名注册逻辑(比如存入数据库) await interaction.response.send_message(f"用户名 `{self.username.value}` 注册成功!", ephemeral=True) # 定义带「继续」按钮的View class ContinueView(discord.ui.View): def __init__(self): super().__init__(timeout=60) @discord.ui.button(label="继续", style=discord.ButtonStyle.green) async def continue_button(self, interaction: discord.Interaction, button: discord.ui.Button): # 点击按钮后弹出输入用户名的Modal await interaction.response.send_modal(UsernameModal()) # 注册触发命令 @bot.command() async def register(ctx): await ctx.send("点击下方按钮开始注册用户名:", view=ContinueView()) bot.run("你的Bot Token")
流程说明
- 用户发送
!register命令,Bot发送带有「继续」按钮的消息 - 用户点击「继续」按钮,弹出包含用户名输入框的模态框
- 用户输入完成提交后,
on_submit方法处理注册逻辑并反馈结果
这种写法完全匹配你预期的流程,同时严格遵循Discord的UI组件规范。
内容的提问来源于stack exchange,提问作者user19916937
相关产品推荐
相关产品推荐

