I’m having trouble with my Discord bot’s status update. Here’s my code:
String[] statuses = {"Bot v2.0", "Join us!", "Made with love", "Try me!", "Help: /info", "Users: %count"};
int countdown = 120;
public void everySecond() {
if (countdown % 5 == 0) {
if (!initialized) {
initialized = true;
ChannelStatsTracker.initialize();
}
int pick = new Random().nextInt(statuses.length);
shardManager.getShards().forEach(shard -> {
String display = statuses[pick].replace("%count", String.valueOf(shard.getUserCount()));
shard.getPresence().setActivity(Activity.playing(display));
});
ChannelStatsTracker.update();
if (countdown == 0) {
countdown = 120;
}
} else {
countdown--;
}
}
The status should change every 5 seconds but it’s updating every second. I used 120 sec % 5. What’s wrong here? How can I fix this to make it update every 5 seconds as intended?
I encountered a similar issue when developing my Discord bot. The problem lies in how you’re handling the countdown timer. Instead of using modulo operations, I found it more reliable to use a simple counter that resets.
Here’s what worked for me:
private int counter = 0;
public void everySecond() {
counter++;
if (counter >= 5) {
int pick = new Random().nextInt(statuses.length);
shardManager.getShards().forEach(shard -> {
String display = statuses[pick].replace("%count", String.valueOf(shard.getUserCount()));
shard.getPresence().setActivity(Activity.playing(display));
});
ChannelStatsTracker.update();
counter = 0; // Reset the counter
}
}
This approach ensures the status updates precisely every 5 seconds. It’s simpler and less prone to timing errors. Remember to initialize the counter as a class variable. Hope this helps!
private long lastUpdate = 0;
public void everySecond() {
long now = System.currentTimeMillis();
if (now - lastUpdate >= 5000) {
// update code here
lastUpdate = now;
}
}
The issue in your code is that you’re decrementing the countdown every second, but only checking if it’s divisible by 5. This causes the status to update every second when countdown is a multiple of 5.
To fix this, you should only decrement the countdown when it’s not time to update. Here’s a modified version:
if (countdown <= 0) {
int pick = new Random().nextInt(statuses.length);
shardManager.getShards().forEach(shard -> {
String display = statuses[pick].replace("%count", String.valueOf(shard.getUserCount()));
shard.getPresence().setActivity(Activity.playing(display));
});
ChannelStatsTracker.update();
countdown = 5; // Reset to 5 seconds
} else {
countdown--;
}
This will ensure the status updates every 5 seconds as intended. The countdown resets to 5 after each update, creating the desired interval.