Compare commits

3 Commits

Author SHA1 Message Date
f2af6316dc Code Optimierung 2025-08-31 19:38:28 +02:00
4075203e6f Code Optimierung 2025-08-31 19:34:53 +02:00
c3764aab26 fix NewsChannel erkennung 2025-07-23 12:01:02 +02:00
12 changed files with 76 additions and 52 deletions

View File

@ -1,21 +1,17 @@
plugins { plugins {
id 'application' id 'application'
id("com.github.johnrengelman.shadow") version "7.1.2" id("com.gradleup.shadow") version "8.3.0"
} }
application.mainClass = "de.ocame.ffdiscordbot.Main" application.mainClass = "de.ocame.ffdiscordbot.Main"
group 'de.ocame' group 'de.ocame'
version '1.3-SNAPSHOT' version '1.4-SNAPSHOT'
repositories { repositories {
mavenCentral() mavenCentral()
} }
sourceCompatibility = '17'
targetCompatibility = '17'
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
} }
@ -34,11 +30,11 @@ dependencies {
implementation 'org.xerial:sqlite-jdbc:3.41.2.2' implementation 'org.xerial:sqlite-jdbc:3.41.2.2'
implementation 'org.json:json:20231013' implementation 'org.json:json:20231013'
implementation 'com.mysql:mysql-connector-j:9.2.0' implementation 'com.mysql:mysql-connector-j:9.2.0'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.0.1' implementation 'com.fasterxml.jackson.core:jackson-databind:2.19.2'
implementation "ch.qos.logback:logback-classic:1.5.6" implementation "ch.qos.logback:logback-classic:1.5.18"
// compile "org.json:json:20141113" // compile "org.json:json:20141113"
} }

View File

@ -378,7 +378,7 @@ public class FanFiktionReader {
Document sendToFav = fetcher.fetchHtml(URL + "/?a=q&a1=v&t=addstory&lbi=popup-addtofav-body&ar=1&action=i", postData); Document sendToFav = fetcher.fetchHtml(URL + "/?a=q&a1=v&t=addstory&lbi=popup-addtofav-body&ar=1&action=i", postData);
if(sendToFav.getElementsByClass("successbox").isEmpty()) { if(sendToFav.getElementsByClass("successbox").isEmpty()) {
LoggerUtil.log("error", "Reader", "Story konnte nicht hinzugefügt werden"); LoggerUtil.log("error", "Reader", "Story konnte nicht hinzugefügt werden");
new InfoNotifier(jda).setMessagetext("Story " + ffid + "konnte nicht hinzugefügt werden. \n" + sendToFav.toString()).sendOutput(); new InfoNotifier(jda).setMessagetext("Story " + ffid + "konnte nicht hinzugefügt werden. \n" + sendToFav).sendOutput();
} }
} }
catch (IOException | InterruptedException e) { catch (IOException | InterruptedException e) {

View File

@ -26,13 +26,14 @@ public class Main {
.setActivity(Activity.playing("mit der Marine fangen")) .setActivity(Activity.playing("mit der Marine fangen"))
.setStatus(OnlineStatus.ONLINE) .setStatus(OnlineStatus.ONLINE)
.setAutoReconnect(true) .setAutoReconnect(true)
.addEventListeners(new ChatReader()) //.addEventListeners(new ChatReader())
.build();/**/ .build();/**/
try { try {
TimeUnit.SECONDS.sleep(10); TimeUnit.SECONDS.sleep(10);
} }
catch (InterruptedException e) { catch (InterruptedException e) {
LoggerUtil.log("error", "Main", "Sleeptimer erzuegt Fehler" + e.getMessage());
} }
FanFiktionReader ffr = new FanFiktionReader(jda); FanFiktionReader ffr = new FanFiktionReader(jda);
@ -56,7 +57,7 @@ public class Main {
delay[0] = ffr.getTime(); delay[0] = ffr.getTime();
LoggerUtil.log("info", "Main", "neue Zeit: " + (Long.toString(Math.round(delay[0] / 60 * 10)/10) )); LoggerUtil.log("info", "Main", "neue Zeit: " + (Long.toString(Math.round((float) delay[0] / 60 * 10)/10) ));
// Plane die Aufgabe erneut mit dem neuen Intervall // Plane die Aufgabe erneut mit dem neuen Intervall
scheduledFuture.get().cancel(false); scheduledFuture.get().cancel(false);

View File

@ -2,7 +2,6 @@ package de.ocame.ffdiscordbot;
import java.awt.*; import java.awt.*;
import java.sql.*; import java.sql.*;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;

View File

@ -1,6 +1,7 @@
package de.ocame.ffdiscordbot; package de.ocame.ffdiscordbot;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.channel.concrete.NewsChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import org.json.JSONObject; import org.json.JSONObject;
@ -52,7 +53,6 @@ class SocketServerRunnable implements Runnable {
} }
catch (IOException | NullPointerException e) { catch (IOException | NullPointerException e) {
LoggerUtil.log("error", "SocketRunnable", "Fehler bei der Kommunikation mit dem Client: " + e.getMessage()); LoggerUtil.log("error", "SocketRunnable", "Fehler bei der Kommunikation mit dem Client: " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -63,7 +63,7 @@ class SocketServerRunnable implements Runnable {
} }
private Boolean channelCheckAction(JSONObject jsonData, PrintWriter out) { private Boolean channelCheckAction(JSONObject jsonData, PrintWriter out) {
JSONObject jsonResponse= new JSONObject(); JSONObject jsonResponse= new JSONObject();
Long channelId = null; long channelId;
Object channelIdObj = jsonData.get("channelId"); Object channelIdObj = jsonData.get("channelId");
if(channelIdObj.equals("")) { if(channelIdObj.equals("")) {
@ -74,8 +74,7 @@ class SocketServerRunnable implements Runnable {
if (channelIdObj instanceof Number) { if (channelIdObj instanceof Number) {
channelId = ((Number) channelIdObj).longValue(); channelId = ((Number) channelIdObj).longValue();
} }
else if (channelIdObj instanceof String) { else if (channelIdObj instanceof String channelIdStr) {
String channelIdStr = (String) channelIdObj;
channelId = Long.parseLong(channelIdStr); channelId = Long.parseLong(channelIdStr);
} }
else { else {
@ -83,18 +82,31 @@ class SocketServerRunnable implements Runnable {
return true; return true;
} }
String response = "";
try { try {
TextChannel textchannel = jda.getTextChannelById(channelId); if(jda.getNewsChannelById(channelId) != null) {
if (textchannel.canTalk()) { NewsChannel textchannel = jda.getNewsChannelById(channelId);
jsonResponse.put("status", "success") if (textchannel.canTalk()) {
.put("name", textchannel.getName()) jsonResponse.put("status", "success")
.put("serverName", textchannel.getGuild().getName()); .put("name", textchannel.getName())
.put("serverName", textchannel.getGuild().getName());
}
else {
jsonResponse.put("status", "fail");
}
} }
else { else {
jsonResponse.put("status", "fail"); TextChannel textchannel = jda.getTextChannelById(channelId);
if (textchannel.canTalk()) {
jsonResponse.put("status", "success")
.put("name", textchannel.getName())
.put("serverName", textchannel.getGuild().getName());
}
else {
jsonResponse.put("status", "fail");
}
} }
} }
catch (NullPointerException e) { catch (NullPointerException e) {
jsonResponse.put("status", "error"); jsonResponse.put("status", "error");

View File

@ -12,7 +12,6 @@ import java.util.regex.Pattern;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class AchievementManager { public class AchievementManager {

View File

@ -11,7 +11,6 @@ import net.dv8tion.jda.api.requests.RestAction;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -19,7 +18,7 @@ import java.util.concurrent.CompletableFuture;
public class ChatReader extends ListenerAdapter { public class ChatReader extends ListenerAdapter {
RestAction<?> latestUpdate = null; RestAction<?> latestUpdate = null;
private Set<String> ChannelWhitelist; private final Set<String> ChannelWhitelist;
public ChatReader() { public ChatReader() {
ChannelWhitelist = new HashSet<>(); ChannelWhitelist = new HashSet<>();
@ -63,7 +62,7 @@ public class ChatReader extends ListenerAdapter {
if(!ChannelWhitelist.contains(event.getChannel().getId())) { if(!ChannelWhitelist.contains(event.getChannel().getId())) {
return; return;
} }
System.out.println(event.getReaction().toString()); System.out.println(event.getReaction());
} }
// ========================================================================================= // =========================================================================================
@ -90,7 +89,7 @@ public class ChatReader extends ListenerAdapter {
event.getChannel().getIterableHistory() event.getChannel().getIterableHistory()
.forEachAsync(message -> { .forEachAsync(message -> {
messages.add(message); messages.add(message);
System.out.println(message.getType().toString()); System.out.println(message.getType());
handleProgressUpdate(progressMessage, filePath, messages.size()); handleProgressUpdate(progressMessage, filePath, messages.size());
return messages.size() < MAX_DESIRED; return messages.size() < MAX_DESIRED;
}) })
@ -152,7 +151,7 @@ public class ChatReader extends ListenerAdapter {
private void writeMessageToFile(FileWriter fileWriter, Message message) { private void writeMessageToFile(FileWriter fileWriter, Message message) {
try { try {
fileWriter.write("Time: " + message.getTimeCreated().toString() + "\n"); fileWriter.write("Time: " + message.getTimeCreated() + "\n");
fileWriter.write("Author: " + message.getAuthor().getId() + "\n"); fileWriter.write("Author: " + message.getAuthor().getId() + "\n");
fileWriter.write("Message ID: " + message.getId() + "\n"); fileWriter.write("Message ID: " + message.getId() + "\n");
fileWriter.write("Content: " + message.getContentRaw() + "\n"); fileWriter.write("Content: " + message.getContentRaw() + "\n");
@ -168,7 +167,7 @@ public class ChatReader extends ListenerAdapter {
reaction.retrieveUsers().queue(users -> { reaction.retrieveUsers().queue(users -> {
StringBuilder reactionUsers = new StringBuilder(); StringBuilder reactionUsers = new StringBuilder();
for (User user : users) { for (User user : users) {
if (reactionUsers.length() > 0) reactionUsers.append("|"); if (!reactionUsers.isEmpty()) reactionUsers.append("|");
reactionUsers.append(user.getId()); reactionUsers.append(user.getId());
} }
reactionFuture.complete("Reaction: " + emojiName + ": " + reactionUsers + "\n"); reactionFuture.complete("Reaction: " + emojiName + ": " + reactionUsers + "\n");

View File

@ -2,6 +2,7 @@ package de.ocame.ffdiscordbot.achievements;
import de.ocame.ffdiscordbot.ConfigLoader; import de.ocame.ffdiscordbot.ConfigLoader;
import de.ocame.ffdiscordbot.LoggerUtil; import de.ocame.ffdiscordbot.LoggerUtil;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
@ -28,12 +29,12 @@ public class MySQLStorage {
// Verbindung erstellen // Verbindung erstellen
String url = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; String url = "jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
connection = DriverManager.getConnection(url, username, password); connection = DriverManager.getConnection(url, username, password);
System.out.println("Erfolgreich mit der Datenbank verbunden!");
LoggerUtil.log("info", "MySQL", "Erfolgreich mit der Datenbank verbunden!"); LoggerUtil.log("info", "MySQL", "Erfolgreich mit der Datenbank verbunden!");
} catch (SQLException e) { } catch (SQLException e) {
LoggerUtil.log("error", "MySQL", "Fehler beim Herstellen der Verbindung zur MySQL-Datenbank: " + e.getMessage()); LoggerUtil.log("error", "MySQL", "Fehler beim Herstellen der Verbindung zur MySQL-Datenbank: " + e.getMessage());
e.printStackTrace(); //e.printStackTrace();
LoggerFactory.getLogger("MySQL").error("Stack: ", e);
} }
return connection; return connection;
@ -143,7 +144,7 @@ public class MySQLStorage {
String sql = """ String sql = """
INSERT INTO Achievement (userId) INSERT INTO Achievement (userId)
VALUES (?) VALUES (?)
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
username = VALUES(username); username = VALUES(username);
"""; """;
try (Connection connection = getConnection(); PreparedStatement stmt = connection.prepareStatement(sql)) { try (Connection connection = getConnection(); PreparedStatement stmt = connection.prepareStatement(sql)) {

View File

@ -107,14 +107,14 @@ public class DefaultHtmlFetcher implements HtmlFetcher {
} }
private static class SerializableCookie { private static class SerializableCookie {
private String uri; private final String uri;
private String name; private final String name;
private String value; private final String value;
private String path; private final String path;
private String domain; private final String domain;
private long maxAge; private final long maxAge;
private boolean secure; private final boolean secure;
private boolean httpOnly; private final boolean httpOnly;
SerializableCookie(HttpCookie cookie) { SerializableCookie(HttpCookie cookie) {
this.uri = cookie.getDomain(); this.uri = cookie.getDomain();

View File

@ -47,11 +47,20 @@ public abstract class BaseNotifier <T extends BaseNotifier<T>> {
} }
Long[] channelIds = SQLiteStorage.getChannelIds(); Long[] channelIds = SQLiteStorage.getChannelIds();
if(targetChannel != null) { if(targetChannel != null) {
Objects.requireNonNull(jda.getTextChannelById(targetChannel)) if (jda.getNewsChannelById(targetChannel) != null) {
// .sendMessage("Hier ist ein Text vor dem Embed <@&423156046115242005> :") Objects.requireNonNull(jda.getNewsChannelById(targetChannel))
// .setEmbeds(outputBox.build()) // .sendMessage("Hier ist ein Text vor dem Embed <@&423156046115242005> :")
.sendMessageEmbeds(outputBox.build()) // .setEmbeds(outputBox.build())
.queue(); .sendMessageEmbeds(outputBox.build())
.queue();
}
else {
Objects.requireNonNull(jda.getTextChannelById(targetChannel))
// .sendMessage("Hier ist ein Text vor dem Embed <@&423156046115242005> :")
// .setEmbeds(outputBox.build())
.sendMessageEmbeds(outputBox.build())
.queue();
}
} }
else if(Objects.requireNonNull(channelIds).length == 0) { else if(Objects.requireNonNull(channelIds).length == 0) {
Objects.requireNonNull(jda.getTextChannelById(542202034330271759L)).sendMessageEmbeds(outputBox.build()).queue(); Objects.requireNonNull(jda.getTextChannelById(542202034330271759L)).sendMessageEmbeds(outputBox.build()).queue();
@ -59,8 +68,17 @@ public abstract class BaseNotifier <T extends BaseNotifier<T>> {
else { else {
for (Long channelId : channelIds ) { for (Long channelId : channelIds ) {
try { try {
if (Objects.requireNonNull(jda.getTextChannelById(channelId)).canTalk()) if(jda.getTextChannelById(channelId) != null) {
Objects.requireNonNull(jda.getTextChannelById(channelId)).sendMessageEmbeds(outputBox.build()).queue(); if (Objects.requireNonNull(jda.getTextChannelById(channelId)).canTalk())
Objects.requireNonNull(jda.getTextChannelById(channelId)).sendMessageEmbeds(outputBox.build()).queue();
} else if (jda.getNewsChannelById(channelId) != null) {
if (Objects.requireNonNull(jda.getNewsChannelById(channelId)).canTalk())
Objects.requireNonNull(jda.getNewsChannelById(channelId)).sendMessageEmbeds(outputBox.build()).queue();
}
else {
LoggerUtil.log("error", "BaseNotifier", "Kanal nicht Gefunden " + channelId);
}
} }
catch (NullPointerException e) { catch (NullPointerException e) {
LoggerUtil.log("error", "BaseNotifier", "keine Rechte zu senden in " + channelId); LoggerUtil.log("error", "BaseNotifier", "keine Rechte zu senden in " + channelId);

View File

@ -11,8 +11,8 @@ import java.util.Map;
// Handles notifications about new chapters // Handles notifications about new chapters
public class ChapterNotifier extends BaseNotifier<ChapterNotifier> { public class ChapterNotifier extends BaseNotifier<ChapterNotifier> {
private DataChapter chapter; private final DataChapter chapter;
private DataStory story; private final DataStory story;
public ChapterNotifier(JDA jda, DataChapter chapter, DataStory story) { public ChapterNotifier(JDA jda, DataChapter chapter, DataStory story) {
super(jda); super(jda);

View File

@ -6,7 +6,6 @@ import net.dv8tion.jda.api.JDA;
import java.time.Instant; import java.time.Instant;
import java.util.Map; import java.util.Map;
import java.util.Properties;
public class InfoNotifier extends BaseNotifier<InfoNotifier> { public class InfoNotifier extends BaseNotifier<InfoNotifier> {