如何用Discord Bot模拟点击其他Bot消息中的按钮?
Discord Bot模拟点击按钮解决方案
核心实现方式
Discord官方API未提供直接模拟点击按钮的方法,但可以通过构造组件交互请求来触发按钮逻辑,无需依赖用户的interaction token——Bot可用自身token签名请求完成操作。
步骤与代码示例
- 定位目标按钮:遍历消息组件,匹配目标按钮的
custom_id(比如你场景中的"ticket") - 构造交互请求体:按照Discord交互API格式组装数据
- 发送POST请求:通过Bot token向Discord交互端点发起请求
import aiohttp import discord from discord.ext import commands client = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @client.event async def on_message(message): if message.author == client.user: return # 检查消息是否包含嵌入内容和按钮组件 if message.embeds and message.components: # 遍历第一行组件下的所有按钮 for button in message.components[0].children: # 匹配目标按钮的custom_id和显示文本 if (isinstance(button, discord.Button) and button.custom_id == "ticket" and button.label == "Open a ticket!"): print(f"找到目标按钮:{button.label}") # 组装交互请求数据 interaction_payload = { "type": 3, # 3代表消息组件交互类型 "guild_id": str(message.guild.id) if message.guild else None, "channel_id": str(message.channel.id), "message_id": str(message.id), "application_id": str(message.author.id), # 原工单Bot的应用ID(即作者ID) "data": { "component_type": 2, # 2代表按钮组件类型 "custom_id": button.custom_id } } # 发送请求触发按钮 async with aiohttp.ClientSession() as session: headers = { "Authorization": f"Bot {client.http.token}", "Content-Type": "application/json" } api_url = "https://discord.com/api/v9/interactions" async with session.post(api_url, json=interaction_payload, headers=headers) as resp: if resp.status == 204: print("按钮触发成功,工单已创建") else: print(f"触发失败,状态码:{resp.status},响应:{await resp.text()}") break await client.process_commands(message) client.run("你的Bot Token")
关键注意点
- 确保Bot拥有对应频道的查看消息和发送消息权限,否则请求会被Discord拒绝
application_id必须填写生成按钮的Bot的ID(即消息作者ID),不能使用自身Bot的ID- 此方法依赖Discord API的当前格式,若API端点或参数规则变更,需同步调整代码
内容的提问来源于stack exchange,提问作者morigan
相关产品推荐
相关产品推荐

