add logger & revert back to executor because yes

not sure if executor will break again i set it to 100 instead of 69 now
This commit is contained in:
ChomeNS 2023-03-28 14:46:47 +07:00
parent b24a4c6951
commit cd2fa73976
10 changed files with 292 additions and 159 deletions

View file

@ -13,8 +13,9 @@ import org.apache.commons.lang3.RandomStringUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Timer; import java.util.concurrent.Executors;
import java.util.TimerTask; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Bot { public class Bot {
private final ArrayList<SessionListener> listeners = new ArrayList<>(); private final ArrayList<SessionListener> listeners = new ArrayList<>();
@ -31,6 +32,8 @@ public class Bot {
@Getter private Session session; @Getter private Session session;
@Getter private ScheduledExecutorService executor = Executors.newScheduledThreadPool(100);
@Getter @Setter private ConsolePlugin console; @Getter @Setter private ConsolePlugin console;
@Getter @Setter private LoggerPlugin logger; // in ConsolePlugin @Getter @Setter private LoggerPlugin logger; // in ConsolePlugin
@Getter private final ChatPlugin chat; @Getter private final ChatPlugin chat;
@ -140,13 +143,7 @@ public class Bot {
if (reconnectDelay < 0) return; // to disable reconnecting if (reconnectDelay < 0) return; // to disable reconnecting
final Timer timer = new Timer(); executor.schedule(() -> reconnect(), reconnectDelay, TimeUnit.MILLISECONDS);
timer.schedule(new TimerTask() {
@Override
public void run() {
reconnect();
}
}, reconnectDelay);
} }
}); });

View file

@ -0,0 +1,173 @@
package land.chipmunk.chayapak.chomens_bot;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
// totallynotskidded from HBot
public class Logger {
public static File logDir = new File("logs");
public static File logFile = new File(logDir, "log.txt");
public static OutputStreamWriter logWriter;
public static LocalDate currentLogDate;
public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("'['dd/MM/yyyy HH:mm:ss']' ");
public static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("'dd/MM/yyyy'");
public static String prevEntry = "";
public static int duplicateCounter = 1;
public static ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
public static int spamLevel = 0;
public static long freezeTime = 0;
static {
init();
executor.scheduleAtFixedRate(() -> {
try {
tick();
} catch (Exception e) {
e.printStackTrace();
}
}, 0, 50, TimeUnit.MILLISECONDS);
}
public static void init() {
if (!logDir.exists()) logDir.mkdir();
try {
if (!logFile.exists()) {
makeNewLogFile();
} else if (!logIsCurrent(logFile)) {
compressLogFile();
makeNewLogFile();
} else {
openLogFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void tick() {
if (freezeTime <= System.currentTimeMillis() && spamLevel > 0) {
spamLevel--;
}
if (!currentLogDate.equals(LocalDate.now())) {
try {
compressLogFile();
makeNewLogFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static synchronized void makeNewLogFile() throws IOException {
currentLogDate = LocalDate.parse(LocalDate.now().format(dateFormatter));
logWriter = new OutputStreamWriter(new FileOutputStream(logFile, false), StandardCharsets.UTF_8);
logWriter.write(currentLogDate.toString() + '\n');
logWriter.flush();
}
public static synchronized void openLogFile() throws IOException {
currentLogDate = LocalDate.parse(getLogDate(logFile));
logWriter = new OutputStreamWriter(new FileOutputStream(logFile, true), StandardCharsets.UTF_8);
}
public static synchronized void compressLogFile() throws IOException {
if (Files.size(logFile.toPath()) > 100*1024*1024) { // Will not save because log file is too big
return;
}
File gzipFile = new File(logDir, getLogDate(logFile) + ".txt.gz");
FileInputStream in = new FileInputStream(logFile);
GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzipFile));
byte[] buffer = new byte[1024];
int size;
while ((size = in.read(buffer)) > 0) {
out.write(buffer, 0, size);
}
in.close();
out.finish();
out.close();
}
public static synchronized BufferedReader getLogReader(File file) throws IOException {
GZIPInputStream in = new GZIPInputStream(new FileInputStream(file));
return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
}
public static synchronized String getLogDate(File file) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr);
String date = reader.readLine();
reader.close();
return date;
}
public static synchronized boolean logIsCurrent(File file) throws IOException {
LocalDate date = LocalDate.now();
return getLogDate(file).equals(date.toString());
}
public static synchronized void log(String str) {
if (freezeTime > System.currentTimeMillis()) {
return;
}
try {
if (spamLevel >= 100) {
spamLevel = 80;
freezeTime = System.currentTimeMillis() + 20000;
if (duplicateCounter > 1) {
logWriter.write(String.format(" [%sx]\n", duplicateCounter));
} else {
logWriter.write("\n");
}
logWriter.write("Spam detected, logs temporarily frozen");
logWriter.flush();
duplicateCounter = 1;
prevEntry = "";
return;
}
if (str.equalsIgnoreCase(prevEntry)) {
duplicateCounter++;
} else {
if (duplicateCounter > 1) {
logWriter.write(String.format(" [%sx]\n", duplicateCounter));
} else {
logWriter.write("\n");
}
logWriter.write(getTimePrefix() + str.replaceAll("\\[(\\d+?)x](?=$|[\r\n])", "[/$1x]")); // the replaceAll will prevent conflicts with the duplicate counter
logWriter.flush();
duplicateCounter = 1;
prevEntry = str;
spamLevel += 2;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getTimePrefix() {
LocalDateTime dateTime = LocalDateTime.now();
return dateTime.format(dateTimeFormatter);
}
}

View file

@ -8,8 +8,7 @@ import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.Timer; import java.util.concurrent.TimeUnit;
import java.util.TimerTask;
public class BruhifyPlugin { public class BruhifyPlugin {
@Getter @Setter private String bruhifyText = ""; @Getter @Setter private String bruhifyText = "";
@ -17,29 +16,24 @@ public class BruhifyPlugin {
private int startHue = 0; private int startHue = 0;
public BruhifyPlugin (Bot bot) { public BruhifyPlugin (Bot bot) {
final Timer timer = new Timer(); bot.executor().scheduleAtFixedRate(() -> {
if (bruhifyText.equals("")) return;
timer.schedule(new TimerTask() { int hue = startHue;
@Override String displayName = bruhifyText;
public void run() { int increment = (int)(360.0 / Math.max(displayName.length(), 20));
if (bruhifyText.equals("")) return;
int hue = startHue; Component component = Component.empty();
String displayName = bruhifyText;
int increment = (int)(360.0 / Math.max(displayName.length(), 20));
Component component = Component.empty(); for (char character : displayName.toCharArray()) {
String color = String.format("#%06x", ColorUtilities.hsvToRgb(hue, 100, 100));
for (char character : displayName.toCharArray()) { component = component.append(Component.text(character).color(TextColor.fromHexString(color)));
String color = String.format("#%06x", ColorUtilities.hsvToRgb(hue, 100, 100)); hue = (hue + increment) % 360;
component = component.append(Component.text(character).color(TextColor.fromHexString(color)));
hue = (hue + increment) % 360;
}
bot.core().run("minecraft:title @a actionbar " + GsonComponentSerializer.gson().serialize(component));
startHue = (startHue + increment) % 360;
} }
}, 50, 100);
bot.core().run("minecraft:title @a actionbar " + GsonComponentSerializer.gson().serialize(component));
startHue = (startHue + increment) % 360;
}, 50, 100, TimeUnit.MILLISECONDS);
} }
} }

View file

@ -21,6 +21,7 @@ import lombok.Getter;
import land.chipmunk.chayapak.chomens_bot.Bot; import land.chipmunk.chayapak.chomens_bot.Bot;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit;
public class CorePlugin extends PositionPlugin.PositionListener { public class CorePlugin extends PositionPlugin.PositionListener {
private final Bot bot; private final Bot bot;
@ -118,13 +119,7 @@ public class CorePlugin extends PositionPlugin.PositionListener {
if (!ready) { if (!ready) {
ready = true; ready = true;
final Timer timer = new Timer(); bot.executor().scheduleAtFixedRate(this::refill, 0, bot.config().core().refillInterval(), TimeUnit.MILLISECONDS);
timer.schedule(new TimerTask() {
@Override
public void run() {
refill();
}
}, 1, bot.config().core().refillInterval());
for (Listener listener : listeners) listener.ready(); for (Listener listener : listeners) listener.ready();
} }
} }

View file

@ -26,9 +26,8 @@ import org.jetbrains.annotations.NotNull;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class DiscordPlugin { public class DiscordPlugin {
@Getter private JDA jda; @Getter private JDA jda;
@ -171,15 +170,7 @@ public class DiscordPlugin {
} }
}); });
final TimerTask task = new TimerTask() { bot.executor().scheduleAtFixedRate(() -> onDiscordTick(channelId), 0, 50, TimeUnit.MILLISECONDS);
@Override
public void run() {
onDiscordTick(channelId);
}
};
final Timer timer = new Timer();
timer.schedule(task, 50, 50);
} }
@Override @Override

View file

@ -5,8 +5,7 @@ import land.chipmunk.chayapak.chomens_bot.Bot;
import lombok.Getter; import lombok.Getter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Timer; import java.util.concurrent.TimeUnit;
import java.util.TimerTask;
public class HashingPlugin { public class HashingPlugin {
private final Bot bot; private final Bot bot;
@ -17,13 +16,7 @@ public class HashingPlugin {
public HashingPlugin (Bot bot) { public HashingPlugin (Bot bot) {
this.bot = bot; this.bot = bot;
final Timer timer = new Timer(); bot.executor().scheduleAtFixedRate(this::update, 0, 1, TimeUnit.SECONDS);
timer.schedule(new TimerTask() {
@Override
public void run() {
update();
}
}, 1, 1000);
} }
public void update () { public void update () {

View file

@ -4,6 +4,7 @@ import com.github.steveice10.packetlib.event.session.ConnectedEvent;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent; import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter; import com.github.steveice10.packetlib.event.session.SessionAdapter;
import land.chipmunk.chayapak.chomens_bot.Bot; import land.chipmunk.chayapak.chomens_bot.Bot;
import land.chipmunk.chayapak.chomens_bot.Logger;
import land.chipmunk.chayapak.chomens_bot.util.ComponentUtilities; import land.chipmunk.chayapak.chomens_bot.util.ComponentUtilities;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@ -29,11 +30,16 @@ public class LoggerPlugin extends ChatPlugin.ChatListener {
} }
public void log (String message) { public void log (String message) {
bot.console().reader().printAbove( final String formattedMessage = String.format(
String.format( "[%s] %s",
"[%s] %s", bot.host() + ":" + bot.port(),
bot.host() + ":" + bot.port(), message
message );
bot.console().reader().printAbove(formattedMessage);
Logger.log(
formattedMessage.replaceAll( // use replaceAll for regexes, use replace for normal string
"\u001B\\[[;\\d]*[ -/]*[@-~]",
""
) )
); );
} }

View file

@ -6,7 +6,6 @@ import land.chipmunk.chayapak.chomens_bot.song.*;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import land.chipmunk.chayapak.chomens_bot.Bot; import land.chipmunk.chayapak.chomens_bot.Bot;
import land.chipmunk.chayapak.chomens_bot.song.*;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
@ -16,13 +15,13 @@ import java.net.URL;
import java.nio.file.Path; import java.nio.file.Path;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Timer; import java.util.concurrent.ScheduledFuture;
import java.util.TimerTask; import java.util.concurrent.TimeUnit;
public class MusicPlayerPlugin extends SessionAdapter { public class MusicPlayerPlugin extends SessionAdapter {
private final Bot bot; private final Bot bot;
private TimerTask playTask; private ScheduledFuture<?> playTask;
public static final String SELECTOR = "@a[tag=!nomusic,tag=!chomens_bot_nomusic]"; public static final String SELECTOR = "@a[tag=!nomusic,tag=!chomens_bot_nomusic]";
public static File SONG_DIR = new File("songs"); public static File SONG_DIR = new File("songs");
@ -86,74 +85,70 @@ public class MusicPlayerPlugin extends SessionAdapter {
} }
public void coreReady () { public void coreReady () {
playTask = new TimerTask() { final Runnable task = () -> {
@Override if (loaderThread != null && !loaderThread.isAlive()) {
public void run() { if (loaderThread.exception != null) {
if (loaderThread != null && !loaderThread.isAlive()) { bot.chat().tellraw(Component.translatable("Failed to load song: %s", loaderThread.exception.message()).color(NamedTextColor.RED));
if (loaderThread.exception != null) { } else {
bot.chat().tellraw(Component.translatable("Failed to load song: %s", loaderThread.exception.message()).color(NamedTextColor.RED)); songQueue.add(loaderThread.song);
} else { bot.chat().tellraw(Component.translatable("Added %s to the song queue", Component.empty().append(loaderThread.song.name).color(NamedTextColor.GOLD)));
songQueue.add(loaderThread.song); }
bot.chat().tellraw(Component.translatable("Added %s to the song queue", Component.empty().append(loaderThread.song.name).color(NamedTextColor.GOLD))); loaderThread = null;
} }
loaderThread = null;
if (currentSong == null) {
if (songQueue.size() == 0) return;
currentSong = songQueue.get(0); // songQueue.poll();
bot.chat().tellraw(Component.translatable("Now playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.GOLD)));
currentSong.play();
}
if (currentSong.paused && ticksUntilPausedBossbar-- < 0) return;
else ticksUntilPausedBossbar = 20;
bot.core().run("minecraft:bossbar add " + bossbarName + " \"\"");
bot.core().run("minecraft:bossbar set " + bossbarName + " players " + SELECTOR);
bot.core().run("minecraft:bossbar set " + bossbarName + " name " + GsonComponentSerializer.gson().serialize(generateBossbar()));
bot.core().run("minecraft:bossbar set " + bossbarName + " color " + (nightcore ? "purple" : "yellow"));
bot.core().run("minecraft:bossbar set " + bossbarName + " visible true");
bot.core().run("minecraft:bossbar set " + bossbarName + " style progress");
bot.core().run("minecraft:bossbar set " + bossbarName + " value " + (int) Math.floor(currentSong.time));
bot.core().run("minecraft:bossbar set " + bossbarName + " max " + currentSong.length);
if (currentSong.paused) return;
handlePlaying();
if (currentSong.finished()) {
removeBossbar();
bot.chat().tellraw(Component.translatable("Finished playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.GOLD)));
if (loop == Loop.CURRENT) {
currentSong.setTime(0);
return;
}
if (loop == Loop.ALL) {
skip();
return;
} }
if (currentSong == null) { songQueue.remove();
if (songQueue.size() == 0) return;
currentSong = songQueue.get(0); // songQueue.poll(); if (songQueue.size() == 0) {
bot.chat().tellraw(Component.translatable("Now playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.GOLD))); stopPlaying();
bot.chat().tellraw(Component.text("Finished playing every song in the queue"));
return;
}
if (currentSong.size() > 0) {
currentSong = songQueue.get(0);
currentSong.setTime(0);
currentSong.play(); currentSong.play();
} }
if (currentSong.paused && ticksUntilPausedBossbar-- < 0) return;
else ticksUntilPausedBossbar = 20;
bot.core().run("minecraft:bossbar add " + bossbarName + " \"\"");
bot.core().run("minecraft:bossbar set " + bossbarName + " players " + SELECTOR);
bot.core().run("minecraft:bossbar set " + bossbarName + " name " + GsonComponentSerializer.gson().serialize(generateBossbar()));
bot.core().run("minecraft:bossbar set " + bossbarName + " color " + (nightcore ? "purple" : "yellow"));
bot.core().run("minecraft:bossbar set " + bossbarName + " visible true");
bot.core().run("minecraft:bossbar set " + bossbarName + " style progress");
bot.core().run("minecraft:bossbar set " + bossbarName + " value " + (int) Math.floor(currentSong.time));
bot.core().run("minecraft:bossbar set " + bossbarName + " max " + currentSong.length);
if (currentSong.paused) return;
handlePlaying();
if (currentSong.finished()) {
removeBossbar();
bot.chat().tellraw(Component.translatable("Finished playing %s", Component.empty().append(currentSong.name).color(NamedTextColor.GOLD)));
if (loop == Loop.CURRENT) {
currentSong.setTime(0);
return;
}
if (loop == Loop.ALL) {
skip();
return;
}
songQueue.remove();
if (songQueue.size() == 0) {
stopPlaying();
bot.chat().tellraw(Component.text("Finished playing every song in the queue"));
return;
}
if (currentSong.size() > 0) {
currentSong = songQueue.get(0);
currentSong.setTime(0);
currentSong.play();
}
}
} }
}; };
final Timer timer = new Timer(); playTask = bot.executor().schedule(task, 50, TimeUnit.MILLISECONDS);
timer.schedule(playTask, 1, 50);
if (currentSong != null) currentSong.play(); if (currentSong != null) currentSong.play();
} }
@ -226,7 +221,7 @@ public class MusicPlayerPlugin extends SessionAdapter {
@Override @Override
public void disconnected (DisconnectedEvent event) { public void disconnected (DisconnectedEvent event) {
playTask.cancel(); playTask.cancel(true);
if (currentSong != null) currentSong.pause(); // nice. if (currentSong != null) currentSong.pause(); // nice.
} }

View file

@ -16,19 +16,19 @@ import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter; import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.packet.Packet; import com.github.steveice10.packetlib.packet.Packet;
import com.github.steveice10.packetlib.packet.PacketProtocol; import com.github.steveice10.packetlib.packet.PacketProtocol;
import lombok.Getter;
import lombok.Setter;
import land.chipmunk.chayapak.chomens_bot.Bot; import land.chipmunk.chayapak.chomens_bot.Bot;
import land.chipmunk.chayapak.chomens_bot.Configuration; import land.chipmunk.chayapak.chomens_bot.Configuration;
import lombok.Getter;
import lombok.Setter;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import java.util.Timer; import java.util.concurrent.ScheduledFuture;
import java.util.TimerTask; import java.util.concurrent.TimeUnit;
public class SelfCarePlugin extends SessionAdapter { public class SelfCarePlugin extends SessionAdapter {
private final Bot bot; private final Bot bot;
private TimerTask checkTask; private ScheduledFuture<?> checkTask;
@Getter @Setter boolean visibility = false; @Getter @Setter boolean visibility = false;
@ -108,25 +108,21 @@ public class SelfCarePlugin extends SessionAdapter {
muted = false; muted = false;
prefix = false; prefix = false;
checkTask = new TimerTask() { final Runnable task = () -> {
@Override final Session session = bot.session();
public void run() { final PacketProtocol protocol = session.getPacketProtocol();
final Session session = bot.session(); if (
final PacketProtocol protocol = session.getPacketProtocol(); !session.isConnected() ||
if ( (
!session.isConnected() || protocol instanceof MinecraftProtocol &&
( ((MinecraftProtocol) protocol).getState() != ProtocolState.GAME
protocol instanceof MinecraftProtocol && )
((MinecraftProtocol) protocol).getState() != ProtocolState.GAME ) return;
)
) return;
check(); check();
}
}; };
final Timer timer = new Timer(); checkTask = bot.executor().scheduleAtFixedRate(task, 0, bot.config().selfCare().checkInterval(), TimeUnit.MILLISECONDS);
timer.schedule(checkTask, 1, bot.config().selfCare().checkInterval());
} }
public void packetReceived (ClientboundGameEventPacket packet) { public void packetReceived (ClientboundGameEventPacket packet) {
@ -156,6 +152,6 @@ public class SelfCarePlugin extends SessionAdapter {
@Override @Override
public void disconnected (DisconnectedEvent event) { public void disconnected (DisconnectedEvent event) {
checkTask.cancel(); checkTask.cancel(true);
} }
} }

View file

@ -12,8 +12,7 @@ import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.Arrays; import java.util.Arrays;
import java.util.Timer; import java.util.concurrent.TimeUnit;
import java.util.TimerTask;
public class TPSPlugin extends SessionAdapter { public class TPSPlugin extends SessionAdapter {
private final Bot bot; private final Bot bot;
@ -32,13 +31,7 @@ public class TPSPlugin extends SessionAdapter {
bot.addListener(this); bot.addListener(this);
final Timer timer = new Timer(); bot.executor().scheduleAtFixedRate(this::updateTPSBar, 0, 50, TimeUnit.MILLISECONDS);
timer.schedule(new TimerTask() {
@Override
public void run() {
updateTPSBar();
}
}, 1, 50);
} }
public void on () { public void on () {