You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过requests或discord.py读取Discord Modal内的问题内容?

读取Discord Modal内容的实现方案

使用discord.py处理

discord.py v2.0+已原生支持Modal交互,无需手动抓包解析,直接通过事件监听即可获取提交内容:

  • 定义Modal组件时,给每个输入框设置唯一custom_id
  • 监听on_modal_submit事件,在回调中通过interaction.data["components"]遍历获取每个输入框的value值

示例代码:

import discord
from discord import ui

class MyModal(ui.Modal, title="示例Modal"):
    # 定义输入框并设置custom_id
    question1 = ui.TextInput(label="问题1", custom_id="q1", style=discord.TextStyle.short)
    question2 = ui.TextInput(label="问题2", custom_id="q2", style=discord.TextStyle.paragraph)

    async def on_submit(self, interaction: discord.Interaction):
        # 直接获取输入内容
        q1_content = self.question1.value
        q2_content = self.question2.value
        await interaction.response.send_message(f"你提交的内容:\n问题1:{q1_content}\n问题2:{q2_content}")

# 触发Modal的命令
@bot.tree.command(name="open_modal")
async def open_modal(interaction: discord.Interaction):
    await interaction.response.send_modal(MyModal())

# 全局监听所有Modal提交事件
@bot.event
async def on_modal_submit(interaction: discord.Interaction):
    if interaction.data["custom_id"] == "your_modal_custom_id":
        # 遍历组件提取内容
        for component_group in interaction.data["components"]:
            for item in component_group["components"]:
                print(f"{item['custom_id']}: {item['value']}")

使用requests手动处理

若必须用requests,需模拟Discord的交互流程:

  1. 获取用户Discord令牌(注意:令牌为敏感信息,滥用会导致账号封禁)
  2. Modal提交时,Discord会向https://discord.com/api/v10/interactions发送POST请求,请求体JSON中data.components数组包含所有输入框信息,每个元素的value字段即为用户输入内容
  3. 你之前用Chrome DevTools未找到内容,大概率是未展开JSON深层结构,需查看data -> components -> [组件组] -> components -> value路径

简化版请求体结构:

{
  "type": 3,
  "data": {
    "custom_id": "your_modal_custom_id",
    "components": [
      {
        "type": 1,
        "components": [
          {
            "type": 4,
            "custom_id": "q1",
            "value": "用户输入的问题1内容"
          }
        ]
      },
      {
        "type": 1,
        "components": [
          {
            "type": 4,
            "custom_id": "q2",
            "value": "用户输入的问题2内容"
          }
        ]
      }
    ]
  },
  "guild_id": "xxx",
  "channel_id": "xxx"
}

可通过requests发送POST请求模拟提交,或监听该请求获取内容,但Discord API有严格的签名和令牌校验机制,手动实现难度较高。

内容的提问来源于stack exchange,提问作者KeparDEV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 21:37:18