【问题标题】:Discord bot changing status activity every 30 seconds jdaDiscord bot 每 30 秒更改一次状态活动 jda
【发布时间】:2020-12-21 22:16:18
【问题描述】:

我想让机器人每 30 秒刷新/更改两条不同消息的状态(活动)

jda.getPresence().setActivity(Activity.playing("message1"));
jda.getPresence().setActivity(Activity.playing("message2"));

【问题讨论】:

  • 问题出在哪里?
  • 我希望机器人每 30 秒刷新一次状态(活动),每次刷新都会更改为不同的消息。 (message1, message2)
  • 只使用定时器?
  • 你能帮我怎么做吗?

标签: java discord-jda


【解决方案1】:

基本上,您需要创建一个包含消息的数组和一个在 0 和最后一条消息之间交替的索引:

String[] messages={"message 1","message 2"};
int currentIndex=0;

每 30 秒,您可以执行以下操作:

jda.getPresence().setActivity(Activity.playing(messages[currentIndex]));
currentIndex=(currentIndex+1)%messages.length;

首先是这个sets the Activity to the current messagecurrentIndex数组中的元素)。

在此之后,它将1 添加到currentIndex

如果currentIndex 超出数组长度,它会再次将其设置为0。这是使用Modulo operation 完成的。

为了每 30 秒执行一次,您可以使用以下方法之一:

java.util.Timer

执行此操作的旧方法是创建Timer

//Outside of any method
private String[] messages={"message 1","message 2"};
private int currentIndex=0;
//Run this once
new Timer().schedule(new TimerTask(){
  public void run(){
    jda.getPresence().setActivity(Activity.playing(messages[currentIndex]));
    currentIndex=(currentIndex+1)%messages.length;
  }},0,30_000);

Timer#schedule 可以在特定延迟后执行TimerTask(0 表示您想立即开始)并让它在指定时间段后重复(延迟时间和时间段均以毫秒为单位)。

java.util.concurrent.ScheduledExecutorService

也可以使用ScheduledExecutorService,它允许更多的定制(这种方法被认为比Timer“更好”,如Java Concurrency in Practice,第6.2.5章所述):

//outside of any method
private String[] messages = { "message 1", "message 2" };
private int currentIndex = 0;
private ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
//run this once
threadPool.scheduleWithFixedDelay(() -> {
    jda.getPresence().setActivity(Activity.playing(messages[currentIndex]));
    currentIndex = (currentIndex + 1) % messages.length;
}, 0, 30, TimeUnit.SECONDS);
//when you want to stop it (e.g. when the bot is stopped)
threadPool.shutdown();

首先,创建一个允许调度任务的线程池。

这个线程池也可以用于其他任务。

在此示例中,这是使用单个线程完成的。如果要使用多线程,可以使用Executors.newScheduledThreadPool(numberOfThreads);

在此之后,您调用 ScheduledExecutorService#scheduleWithFixedDelay,它会每 30 秒运行一次提供的 Runnable

如果您希望它在应用程序停止时自动停止而不调用shutdown(),您可以通过指定ThreadFactory 来告诉它使用守护线程:

ScheduledExecutorService threadPool = Executors.newSingleThreadScheduledExecutor(r->{
    Thread t=new Thread(r);
    t.setDaemon(true);
    return t;
});

【讨论】:

  • 我应该在哪里提供消息 2?
  • linkerror我该怎么办?
  • 你导入java.util.Timer了吗?
  • 是导入import java.util.Timer;
  • 我忘了TimerTask is not a SAM。我的编辑工作了吗?
猜你喜欢
  • 2018-12-13
  • 2021-06-29
  • 2020-07-28
  • 2023-01-05
  • 1970-01-01
  • 2021-10-15
  • 2020-11-15
  • 2014-05-03
  • 1970-01-01
相关资源
最近更新 更多