如何在机器人启动时发送消息

时间:2021-08-02 00:36:41

标签: java discord-jda

目前我正在制作一个机器人,它会在每周四下午 1:00 提醒我。计时器部分已经完成,但我需要它在机器人启动时进行初始化。我正在使用 GuildMessageReceivedEvent 并通过执行命令激活它。我已经尝试过 ReadyEvent,但我无法使用该事件发送消息。任何帮助表示赞赏。

代码:

public class Reminder extends ListenerAdapter {
    @Override
    public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
        String[] args = e.getMessage().getContentRaw().split("\\s+");
        if (args[0].equalsIgnoreCase("!start")) {
            if (e.getGuild().getId().equalsIgnoreCase("679875946597056683")) {
                TextChannel defaultChannel = e.getGuild().getDefaultChannel();
                if (defaultChannel != null) {
                    e.getChannel().sendTyping().queue();
                    e.getChannel().sendMessage("Reminder has been activated.").queue();
                    LocalDateTime now = LocalDateTime.now(ZoneId.of("America/Los_Angeles"));
                    LocalDateTime then = LocalDateTime.now(ZoneId.of("America/Los_Angeles"));
                    then = then.with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY)).withHour(13).withMinute(0).withSecond(0);
                    Duration duration = Duration.between(now, then);
                    long initialDelay = duration.getSeconds();

                    if (initialDelay < 0) {
                        initialDelay = Duration.between(now, then.with(TemporalAdjusters.next(DayOfWeek.THURSDAY)).withHour(13).withMinute(0)).getSeconds();
                    }

                    ScheduledExecutorService scheduledActivity = Executors.newScheduledThreadPool(1);
                    scheduledActivity.scheduleAtFixedRate(() -> {
                                List<Message> messages = e.getChannel().getHistory().retrievePast(1).complete();
                                for (Message msg : messages) {
                                    if (!msg.getContentRaw().equalsIgnoreCase("Reminder")) {
                                        defaultChannel.sendTyping().queue();
                                        defaultChannel.sendMessage("Reminder").queue();
                                    }
                                }
                            },
                            initialDelay,
                            TimeUnit.DAYS.toSeconds(7),
                            TimeUnit.SECONDS);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用 ReadyEvent 向服务器中的特定频道发送消息。 例如,在您的 ReadyEvent:

event.getJDA().getGuildById("Your Server ID").getTextChannelById("Your Discord Channel ID").sendMessage("Bot is ready!").queue();

或者您可以通过以下方式将其发送到您服务器的系统频道:

event.getJDA().getGuildById("Your Server ID").getSystemChannel().sendMessage("Bot is ready!").queue();