如何在discord.py中不回复首次交互而发送两次交互?
解决discord.py中Modal提交后发送两次交互消息的问题
核心逻辑是:Discord要求所有交互必须在3秒内完成响应,不能直接跳过首次交互的处理。你需要先延迟响应(defer),再通过followup发送两次目标消息,这样就不会显示首次的回复内容,达到你想要的效果。
具体实现代码
import discord import asyncio from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.tree.command(name="send_embed", description="发送两个Embed消息") async def send_embed(interaction: discord.Interaction): # 定义Modal及输入组件 modal = discord.ui.Modal(title="创建Embed") modal.add_item(discord.ui.TextInput(label="Embed标题", style=discord.TextStyle.short)) modal.add_item(discord.ui.TextInput(label="Embed内容", style=discord.TextStyle.paragraph)) # 弹出Modal等待用户填写 await interaction.response.send_modal(modal) # 捕获用户提交Modal的交互事件 try: submit_interaction = await bot.wait_for( "interaction", check=lambda i: i.user == interaction.user and i.type == discord.InteractionType.modal_submit, timeout=300 ) except asyncio.TimeoutError: return # 关键步骤:延迟响应,不生成可见回复 await submit_interaction.response.defer(ephemeral=False) # 构造并发送第一个Embed消息 embed1 = discord.Embed( title=submit_interaction.data["components"][0]["components"][0]["value"], description="第一条交互消息" ) await submit_interaction.followup.send(embed=embed1) # 构造并发送第二个Embed消息 embed2 = discord.Embed( title=submit_interaction.data["components"][0]["components"][0]["value"], description="第二条交互消息" ) await submit_interaction.followup.send(embed=embed2) bot.run("你的Bot令牌")
关键说明
- 必须先执行defer:如果不先调用
defer响应首次交互,Discord会判定该交互未处理,后续的followup.send会被系统拒绝,这就是你之前尝试无效的核心原因。 - ephemeral参数控制消息可见性:如果需要消息仅对提交用户可见,将
defer和followup.send中的ephemeral设为True;要发送公开频道消息则设为False。 - Modal交互的捕获:通过
wait_for监听用户提交Modal的事件,确保后续操作针对的是正确的交互实例。
内容的提问来源于stack exchange,提问作者vanquish
相关产品推荐
相关产品推荐

