按钮基本上是使用反应的一种替代方法。对于类似页面的系统,它的工作方式几乎相同。您发送带有反应/按钮的消息,等待反应,然后编辑消息。
有几点不同:
- 按钮会立即应用于消息,之后不需要添加。
- 按钮需要在按下后 3 秒内做出响应,以避免用户在屏幕上显示“此交互失败”。
- 交互时,同一用户无法再次交互消息上的按钮,直到机器人确认或交互超时。
- 用户不能删除按钮
这意味着按钮对于诸如编辑其所在消息之类的操作非常有用,但对于切换角色之类的操作则不那么有用。
每条消息可以有5s ActionRow,每条消息可以ActionRow有5s Button(共25条)
按钮具有标签、样式和自定义 ID(或 URL,如果它是“URL 样式”按钮)。
由于您使用的是discord-buttons,您可以执行以下操作来发送带有按钮的消息:
const { MessageActionRow, MessageButton } = require("discord-buttons");
// create a row!
const row = new MessageActionRow(),
backButton = new MessageButton()
.setLabel("Back")
// https://discord.com/developers/docs/interactions/message-components#buttons-button-styles
.setStyle("blurple"),
// identifies the button, so you can know which button was pressed
.setID("back"),
nextButton = new MessageButton()
.setLabel("Next")
.setStyle("blurple")
.setID("next");
row.addComponent(backButton).addComponent(nextButton);
const pages = [
"Hello",
"World",
"Foo",
"Bar"
];
let index = 0;
const message = await channel.send(pages[index], {
component: row
});
然后,您可以使用提供的方法或事件等待交互:discord-buttons
discord-buttons扩展了常规discord.js类的功能,因此可以使用类似的选项。
function handleInteractions() {
// originalMessage is the message sent by the user to activate this 'command'
const filter = (button) => button.clicker.user.id === originalMessage.author.id;
const clickedButton = (await message.awaitButtons(filter, {
max: 1, // how many to collect
time: 60000 // how long to wait in milliseconds
})).first();
// check if a button was actually clicked
if (clickedButton) {
// IMPORTANT: Respond to the interaction to prevent false errors on the user's side.
// https://discord-buttons.js.org/events/clickbutton#functions
// Acknowledges the interaction, doesn't send or edit anything
// You may find it easier to use a different method to acknowledge and edit/send a new message, but in this example, the message will be edited normally.
await clickedButton.defer();
if (clickedButton.id === "back") {
index--;
} else {
index++;
}
// constrain the pages
if (index < 0) index = pages.length - 1;
if (index >= pages.length) index = 0;
// edit your message!
message.edit(pages[index]);
// re-listen to button clicks
handleInteractions();
} else {
// It may be useful to delete the message or remove the buttons from the
// message once you are no longer listening to the events.
message.edit({components: []});
}
}
handleInteractions();