
discord.py 中 modal 的提交处理必须通过 `on_submit()` 方法实现,而非自定义 `callback()`;若方法名错误,discord 将无法触发回调,导致“something went wrong”静默失败且控制台无报错。
在使用 discord.py(v2.0+)构建交互式模态窗口(Modal)时,一个常见却极易被忽略的陷阱是:Modal 类中用于响应用户提交的钩子方法名称必须严格为 on_submit。与 View 组件中的 callback 不同,Modal 并不识别或调用名为 callback 的异步方法——它只会在用户点击“Submit”后自动调用 on_submit(interaction: Interaction)。若该方法缺失或命名错误(如误写为 callback),Discord 端将因无法完成预期的交互响应流程而抛出模糊的 “Something went wrong” 错误,且后端不会记录任何异常(因为根本未进入你的逻辑),造成极强的排查迷惑性。
✅ 正确做法:将原 callback 方法重命名为 on_submit,并确保其为 async 且接收单个 Interaction 参数:
from discord import Interaction, TextStyle
from discord.ui import TextInput, Modal
class HostGameModal(Modal):
def __init__(self, era: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.era = era
self.add_item(TextInput(
label="Game Name",
custom_id="game_name",
placeholder="Enter your game's name"
))
self.add_item(TextInput(
label="Max Players",
custom_id="max_players",
placeholder="Enter max number of players",
style=TextStyle.short
))
self.add_item(TextInput(
label="Password",
custom_id="password",
placeholder="Enter a game password",
style=TextStyle.short
))
# ✅ 关键修正:必须命名为 on_submit,不可改为 callback 或其他名称
async def on_submit(self, interaction: Interaction):
printlog("HostGameModal on_submit called.") # 现在这行会正常执行
try:
await interaction.response.defer(ephemeral=True)
# 安全获取输入值(推荐按 custom_id 查找,而非依赖 children 索引)
game_name = next(item for item in self.children if item.custom_id == "game_name").value
max_players = int(next(item for item in self.children if item.custom_id == "max_players").value)
password = next(item for item in self.children if item.custom_id == "password").value
await interaction.followup.send(
f"Hosting a '{self.era}' game named '{game_name}' with max {max_players} players and password '{password}'.",
ephemeral=True
)
except ValueError as e:
await interaction.followup.send("❌ Invalid input: 'Max Players' must be a number.", ephemeral=True)
except Exception as e:
printlog(f"Unexpected error in HostGameModal on_submit: {e}")
await interaction.followup.send("⚠️ An unexpected error occurred. Please try again.", ephemeral=True)? 重要注意事项:
- 方法签名不可省略或修改:必须是 async def on_submit(self, interaction: Interaction),参数类型与数量需严格匹配;
- 避免使用 children[n].value 硬编码索引:推荐通过 custom_id 动态查找(如示例所示),防止因字段顺序调整导致逻辑错乱;
- 务必响应交互:on_submit 内必须调用 interaction.response.*(如 defer() 或 send()),否则会触发超时错误;
- 异常需显式捕获并响应:未处理的异常会导致交互挂起,最终触发 Discord 端“Something went wrong”;
- 调试建议:在 on_submit 开头添加日志或 await interaction.followup.send("DEBUG: entered on_submit", ephemeral=True) 快速验证是否被调用。
遵循以上规范后,Modal 提交将稳定触发、逻辑可追踪、错误可捕获,彻底告别无提示的静默失败。










