aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/de/hysky/skyblocker/utils/scheduler/MessageScheduler.java
blob: 43194938c731658f02089b2a0eb48070c90044da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package de.hysky.skyblocker.utils.scheduler;

import net.minecraft.client.MinecraftClient;
import net.minecraft.util.StringHelper;
import org.apache.commons.lang3.StringUtils;

/**
 * A scheduler for sending chat messages or commands. Use the instance in {@link #INSTANCE}. Do not instantiate this class.
 */
public class MessageScheduler extends Scheduler {
    /**
     * The minimum delay that the server will accept between chat messages.
     */
    private static final int MIN_DELAY = 200;
    public static final MessageScheduler INSTANCE = new MessageScheduler();
    /**
     * The timestamp of the last message send,
     */
    private long lastMessage = 0;

    protected MessageScheduler() {
    }

    /**
     * Sends a chat message or command after the minimum cooldown. Prefer this method to send messages or commands to the server.
     *
     * @param message the message to send
     */
    public void sendMessageAfterCooldown(String message) {
        if (lastMessage + MIN_DELAY < System.currentTimeMillis()) {
            sendMessage(message);
            lastMessage = System.currentTimeMillis();
        } else {
            queueMessage(message, 0);
        }
    }

    private void sendMessage(String message) {
        MinecraftClient client = MinecraftClient.getInstance();
        if (client.player == null) {
            Scheduler.LOGGER.error("[Skyblocker Message Scheduler] Tried to send a message while player is null: {}", message);
            return;
        }
        message = StringHelper.truncateChat(StringUtils.normalizeSpace(message.trim()));
        if (message.startsWith("/")) {
            client.player.networkHandler.sendCommand(message.substring(1));
        } else {
            client.inGameHud.getChatHud().addToMessageHistory(message);
            client.player.networkHandler.sendChatMessage(message);
        }
    }

    /**
     * Queues a chat message or command to send in {@code delay} ticks. Use this method to send messages or commands a set time in the future. The minimum cooldown is still respected.
     *
     * @param message the message to send
     * @param delay   the delay before sending the message in ticks
     */
    public void queueMessage(String message, int delay) {
        schedule(() -> sendMessage(message), delay);
    }

    @Override
    protected boolean runTask(Runnable task, boolean multithreaded) {
        if (lastMessage + MIN_DELAY < System.currentTimeMillis()) {
            task.run();
            lastMessage = System.currentTimeMillis();
            return true;
        }
        return false;
    }
}