discord.py中实现带内嵌按钮的消息(非Embed)技术求助
解决Discord消息内嵌按钮的问题
你提到的components是Discord API层面的字段,但不同开发库对它的封装方式不一样,不是直接在.send或.respond里传components参数,下面分常用库说明具体实现:
1. Python(discord.py)
discord.py用View类来承载按钮组件,通过view参数传入发送方法:
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 自定义View类,包含按钮 class ButtonView(discord.ui.View): @discord.ui.button(label="点我试试", style=discord.ButtonStyle.blue) async def button_click(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message("按钮触发成功!") # 测试命令 @bot.command() async def send_btn(ctx): await ctx.send("这是带内嵌按钮的消息", view=ButtonView()) bot.run("你的Bot令牌")
2. JavaScript(discord.js)
discord.js v13+版本支持直接在发送选项里传components参数,需要用MessageActionRow包裹按钮:
const { Client, MessageActionRow, MessageButton } = require('discord.js'); const client = new Client({ intents: ['GUILDS', 'GUILD_MESSAGES'] }); client.on('messageCreate', async (msg) => { if (msg.content === '!sendbtn') { // 构建按钮行 const buttonRow = new MessageActionRow() .addComponents( new MessageButton() .setLabel("点我试试") .setStyle("PRIMARY") .setCustomId("test_btn") ); // 发送带按钮的消息 await msg.channel.send({ content: "这是带内嵌按钮的消息", components: [buttonRow] }); } }); // 监听按钮交互 client.on('interactionCreate', async (interaction) => { if (!interaction.isButton()) return; if (interaction.customId === "test_btn") { await interaction.reply("按钮触发成功!"); } }); client.login("你的Bot令牌");
注意事项
- 如果你用的库版本过低,可能没有对应的组件支持,先升级到最新稳定版;
- 不同库的参数命名不同,比如discord.py用
view,discord.js用components,不要直接照搬API的字段名。
内容的提问来源于stack exchange,提问作者Hamd




