使用 Discord4J 在消息中添加按钮:交互式消息指南
Discord4J 可以使用 Interactions API 来添加按钮,从而让你的 Discord 应用程序更加动态和用户友好。以下是一个示例,演示如何在 Discord4J 中创建一个按钮,并在用户单击时触发事件:
import discord4j.core.DiscordClient;
import discord4j.core.GatewayDiscordClient;
import discord4j.core.event.domain.interaction.ButtonInteractEvent;
import discord4j.core.event.domain.interaction.InteractionCreateEvent;
import discord4j.core.object.component.ActionRow;
import discord4j.core.object.component.Button;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.channel.MessageChannel;
import discord4j.discordjson.json.ApplicationCommandOptionData;
import discord4j.rest.util.ApplicationCommandOptionType;
import reactor.core.publisher.Mono;
public class ButtonExample {
public static void main(String[] args) {
DiscordClient client = DiscordClient.create('YOUR_BOT_TOKEN');
GatewayDiscordClient gateway = client.login().block();
gateway.on(InteractionCreateEvent.class)
.flatMap(event -> {
if (event.getInteraction().getCommandName().equals('button')) {
// 创建一个带有自定义 ID 的按钮
Button button = Button.primary('my_button', 'Click me!');
// 使用按钮创建操作行
ActionRow actionRow = ActionRow.of(button);
// 使用操作行创建消息
return event.reply(spec -> spec.setContent('Here's a button:').addComponent(actionRow));
} else {
return Mono.empty();
}
})
.flatMap(event -> {
// 获取刚刚发送的消息
Message message = event.getMessage().block();
if (message != null) {
// 获取消息频道
MessageChannel channel = message.getChannel().block();
if (channel != null) {
// 监听消息频道中的按钮交互事件
return gateway.on(ButtonInteractEvent.class)
.filter(interaction -> interaction.getMessage().getId().equals(message.getId()))
.next()
.flatMap(interaction -> {
// 响应按钮点击事件
return interaction.reply('You clicked the button!').then();
});
} else {
return Mono.empty();
}
} else {
return Mono.empty();
}
})
.subscribe();
gateway.onDisconnect().block();
}
}
在上面的示例中,我们创建了一个按钮并将其添加到消息中。然后,我们使用 on(ButtonInteractEvent.class) 方法来监听按钮交互事件。在监听到按钮点击事件后,我们可以在 ButtonInteractEvent 对象中获取按钮的 ID 和消息 ID,并回复用户。
注意,按钮的 ID 必须是唯一的。如果你的应用程序需要使用多个按钮,请分配不同的 ID。
此外,要使用 Interactions API,你需要在 Discord 开发者门户中注册你的应用程序,并启用 Interactions 功能。你还需要在代码中设置应用程序的公共密钥,以便 Discord 可以验证你的交互请求。
原文地址: https://www.cveoy.top/t/topic/mLpC 著作权归作者所有。请勿转载和采集!