Java Discord4J 发送包含倒计时的消息
Java Discord4J 发送包含倒计时的消息
本文将演示如何使用 Java Discord4J 库发送一条包含倒计时的消息。
示例代码
import discord4j.core.DiscordClient;
import discord4j.core.DiscordClientBuilder;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.channel.TextChannel;
import discord4j.rest.util.Color;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class DiscordBot {
public static void main(String[] args) {
// 创建Discord客户端
DiscordClient client = new DiscordClientBuilder('<your-bot-token>').build();
// 监听消息创建事件
client.getEventDispatcher().on(MessageCreateEvent.class)
.subscribe(event -> {
// 获取消息内容
String content = event.getMessage().getContent();
// 判断是否包含倒计时
if (content.startsWith('!countdown')) {
// 分离倒计时时间
String[] parts = content.split(' ');
if (parts.length != 2) {
return;
}
String timeStr = parts[1];
// 解析时间
LocalDateTime time = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss'));
Instant instant = time.toInstant(ZoneOffset.ofHours(8));
long duration = Duration.between(Instant.now(), instant).getSeconds();
// 创建消息发送对象
TextChannel channel = event.getMessage().getChannel().ofType(TextChannel.class).block();
Message message = channel.createMessage(spec -> {
spec.setContent('倒计时:' + timeStr);
spec.setEmbed(embed -> {
embed.setTitle('倒计时');
embed.setColor(Color.RED);
embed.setDescription('距离 ' + timeStr + ' 还有:' + formatDuration(duration));
});
}).block();
}
});
// 登录Discord服务器
client.login().block();
}
private static String formatDuration(long seconds) {
long days = seconds / (24 * 60 * 60);
seconds -= days * (24 * 60 * 60);
long hours = seconds / (60 * 60);
seconds -= hours * (60 * 60);
long minutes = seconds / 60;
seconds -= minutes * 60;
StringBuilder sb = new StringBuilder();
if (days > 0) {
sb.append(days).append(' 天 ');
}
if (hours > 0) {
sb.append(hours).append(' 小时 ');
}
if (minutes > 0) {
sb.append(minutes).append(' 分钟 ');
}
sb.append(seconds).append(' 秒');
return sb.toString();
}
}
代码解析
- 创建Discord客户端:使用
DiscordClientBuilder类创建Discord客户端,并传入你的机器人Token。 - 监听消息创建事件:使用
getEventDispatcher()方法获取事件调度器,并使用on()方法监听MessageCreateEvent事件。当收到一条消息时,会触发该事件的回调函数。 - 解析消息内容:在回调函数中,获取消息内容,判断是否以“!countdown”开头。如果是,则解析出倒计时时间,并计算出距离该时间还有多少秒。
- 创建嵌入式消息:使用
TextChannel#createMessage()方法创建消息对象,并使用Message#setEmbed()方法设置嵌入式消息的属性。 - 格式化倒计时时间:使用
formatDuration()方法将秒数转换为天、小时、分钟和秒的格式。 - 发送消息:通过
Message#block()方法等待消息发送完成。
总结
本示例演示了如何使用Java Discord4J库发送一条包含倒计时的消息,并使用嵌入式消息(Embed Message)美化显示。你可以根据自己的需要修改代码,例如更改倒计时时间的格式、添加其他信息等。
希望本文对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/mTWP 著作权归作者所有。请勿转载和采集!