discord.py 2.4.0:关闭Modal后如何保留已输入数据?
实现Discord Modal关闭后重开保留输入数据(discord.py 2.4.0)
要实现这个需求,核心是缓存用户的历史输入,并在每次打开Modal时将缓存数据填充到对应输入框中,具体实现方案如下:
1. 初始化输入缓存
首先需要一个全局字典来存储用户的输入数据,用用户ID+Modal唯一标识作为键,避免不同用户或不同Modal的数据冲突:
# 全局缓存,格式:{ (user_id, modal_id): { "输入框标识": "输入内容" } } user_input_cache = {}
2. 动态生成带缓存数据的Modal
创建Modal时,先检查当前用户是否有对应Modal的历史输入,若有则将TextInput的default参数设置为缓存值:
import discord from discord import ui class PersistentModal(ui.Modal, title="持久化输入模态框"): # 定义两个示例输入框 username = ui.TextInput(label="用户名", style=discord.TextStyle.short, placeholder="请输入用户名") description = ui.TextInput(label="个人描述", style=discord.TextStyle.long, placeholder="请输入个人描述") def __init__(self, user_id: int): super().__init__() # 检查当前用户的缓存数据 cache_key = (user_id, "persistent_modal") if cache_key in user_input_cache: cached_data = user_input_cache[cache_key] # 将缓存数据填充到对应输入框 self.username.default = cached_data.get("username", "") self.description.default = cached_data.get("description", "") async def on_submit(self, interaction: discord.Interaction): # 提交时更新缓存数据 cache_key = (interaction.user.id, "persistent_modal") user_input_cache[cache_key] = { "username": self.username.value, "description": self.description.value } await interaction.response.send_message("输入已保存!", ephemeral=True)
3. 触发Modal的交互逻辑
在按钮或命令触发Modal时,传入用户ID以加载对应缓存:
class OpenModalButton(ui.View): @ui.button(label="打开模态框", style=discord.ButtonStyle.primary) async def open_modal(self, interaction: discord.Interaction, button: ui.Button): # 传入用户ID,让Modal加载对应缓存 modal = PersistentModal(user_id=interaction.user.id) await interaction.response.send_modal(modal) # 注册slash命令触发按钮 @bot.tree.command(name="open_persistent_modal", description="打开带输入缓存的模态框") async def open_modal_command(interaction: discord.Interaction): await interaction.response.send_message("点击按钮打开模态框:", view=OpenModalButton(), ephemeral=True)
关键细节说明
- TextInput的
default参数:discord.py 2.4.0中,TextInput组件原生支持default参数设置初始显示内容,这是实现数据保留的核心。 - 缓存持久化(可选):如果需要机器人重启后仍保留数据,可以将缓存写入本地JSON文件或数据库,启动时读取、提交时更新即可。
- 多Modal区分:通过
modal_id区分不同类型的Modal,避免不同功能的Modal数据互相覆盖。
内容的提问来源于stack exchange,提问作者user27634008
相关产品推荐
相关产品推荐

