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

Discord.py 如何在嵌入消息(embedded message)中接收用户输入

Discord.py 实现嵌入消息关联用户输入的方案

Discord 官方的嵌入消息(Embed)本身为静态展示组件,不支持直接内嵌输入框,你需要的交互效果可以通过「嵌入消息 + 交互按钮 + 模态框(Modal)」的组合实现,最终可以做到成员点击嵌入附带的按钮后填写输入,提交后的内容可同步更新到原嵌入消息中,和你需要的示例效果逻辑一致。

前置要求

  • 你的 discord.py 版本需要 >= 2.0,低版本不支持交互组件和模态框,升级命令:pip install --upgrade discord.py
  • 你需要开启机器人的「Message Content Intent」「Server Members Intent」权限,在 Discord 开发者后台的机器人设置页即可开启

完整实现示例代码

import discord
from discord import ui
from discord.ext import commands

# 定义带输入框的模态框
class InputModal(ui.Modal, title="填写输入内容"):
    # 定义单行输入框,也可以替换style参数为discord.TextStyle.paragraph实现多行输入
    user_input = ui.TextInput(label="你的输入", placeholder="在这里填写内容", style=discord.TextStyle.short)

    async def on_submit(self, interaction: discord.Interaction):
        # 读取用户提交的输入内容
        input_content = self.user_input.value
        # 自定义提交后的逻辑,示例为将内容更新到原嵌入消息中
        original_embed = interaction.message.embeds[0]
        original_embed.add_field(name=f"{interaction.user.name}的输入", value=input_content, inline=False)
        await interaction.response.edit_message(embed=original_embed)
        # 给用户发送仅自己可见的提交成功提示
        await interaction.followup.send("提交成功,内容已更新到嵌入消息中", ephemeral=True)

# 定义带触发按钮的视图
class InputButtonView(ui.View):
    def __init__(self):
        # timeout设为None代表按钮不会过期,可自行设置数值指定过期时间
        super().__init__(timeout=None)
    
    @ui.button(label="点击填写内容", style=discord.ButtonStyle.primary, custom_id="input_button")
    async def input_button_callback(self, interaction: discord.Interaction, button: ui.Button):
        # 点击按钮后弹出输入模态框
        await interaction.response.send_modal(InputModal())

# 机器人实例初始化
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    # 注册持久化视图,机器人重启后按钮仍然可用
    bot.add_view(InputButtonView())
    print(f"已登录为 {bot.user}")

# 发送带嵌入和输入按钮的触发命令
@bot.command()
async def send_input_embed(ctx: commands.Context):
    # 构造嵌入消息
    embed = discord.Embed(title="收集用户输入", description="点击下方按钮填写你的信息", color=discord.Color.blue())
    # 发送嵌入+按钮组件
    await ctx.send(embed=embed, view=InputButtonView())

# 运行机器人,替换为你自己的机器人Token
bot.run("你的机器人Token")

使用说明

  • 机器人上线后,发送!send_input_embed命令即可触发带输入按钮的嵌入消息
  • 服务器成员点击按钮后会弹出带输入框的弹窗,填写提交后内容会自动追加到原嵌入的字段中
  • 可根据需求自定义模态框的输入框数量、样式,以及提交后的处理逻辑

内容的提问来源于stack exchange,提问作者yet-it-compiles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:06:08