Changed to new logging, static implementation for now which is not ideal, but it's not worth spending the time to fix it right now

This commit is contained in:
Teriuihi 2023-05-21 21:54:59 +02:00
parent 0ae96bd6e5
commit 94f1d566ac
39 changed files with 164 additions and 217 deletions

View File

@ -70,4 +70,5 @@ dependencies {
// Other stuff?
compileOnly("org.projectlombok:lombok:1.18.24")
annotationProcessor("org.projectlombok:lombok:1.18.24")
implementation(files("libs/AltitudeLogs.jar"))
}

BIN
libs/AltitudeLogs.jar Normal file

Binary file not shown.

View File

@ -11,6 +11,11 @@ dependencyResolutionManagement {
// MySQL
maven("https://jcenter.bintray.com")
}
repositories {
flatDir {
dirs("lib")
}
}
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
}

View File

@ -29,7 +29,7 @@ public class AltitudeBot {
}
private void start() {
Logger.info("Starting bot...");
Logger.altitudeLogs.info("Starting bot...");
initConfigs();
jda = JDABuilder.createDefault(SettingsConfig.TOKEN,
GatewayIntent.GUILD_MEMBERS,
@ -62,13 +62,14 @@ public class AltitudeBot {
private void initConfigs() {
SettingsConfig.reload();
MessagesConfig.reload();
Logger.setDebugActive(SettingsConfig.DEBUG);
}
public String getDataFolder() {
try {
return new File(AltitudeBot.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getPath();
} catch (URISyntaxException e) {
Logger.severe("Unable to retrieve config directory");
Logger.altitudeLogs.error("Unable to retrieve config directory");
e.printStackTrace();
}
return (null);

View File

@ -2,6 +2,7 @@ package com.alttd.buttonManager.buttons.autoReminder;
import com.alttd.buttonManager.DiscordButton;
import com.alttd.schedulers.ReminderScheduler;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
@ -23,6 +24,7 @@ public class ButtonAccepted extends DiscordButton {
Message message = event.getMessage();
if (!ButtonReminderUtil.shouldExecute(message, event))
return;
Logger.altitudeLogs.debug("Accepting reminder");
MessageEmbed embed = message.getEmbeds().get(0);
EmbedBuilder embedBuilder = new EmbedBuilder(embed).setColor(Color.GREEN);
ReminderScheduler.getInstance(event.getJDA()).removeReminder(message.getIdLong());

View File

@ -1,6 +1,7 @@
package com.alttd.buttonManager.buttons.autoReminder;
import com.alttd.buttonManager.DiscordButton;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
@ -21,6 +22,7 @@ public class ButtonInProgress extends DiscordButton {
Message message = event.getMessage();
if (!ButtonReminderUtil.shouldExecute(message, event))
return;
Logger.altitudeLogs.debug("Marking reminder as in progress");
MessageEmbed embed = message.getEmbeds().get(0);
EmbedBuilder embedBuilder = new EmbedBuilder(embed);
Color color = embed.getColor();

View File

@ -2,6 +2,7 @@ package com.alttd.buttonManager.buttons.autoReminder;
import com.alttd.buttonManager.DiscordButton;
import com.alttd.schedulers.ReminderScheduler;
import com.alttd.util.Logger;
import com.alttd.util.Util;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
@ -23,6 +24,7 @@ public class ButtonRejected extends DiscordButton {
Message message = event.getMessage();
if (!ButtonReminderUtil.shouldExecute(message, event))
return;
Logger.altitudeLogs.debug("Rejecting reminder");
MessageEmbed embed = message.getEmbeds().get(0);
EmbedBuilder embedBuilder = new EmbedBuilder(embed).setColor(Color.RED);
ReminderScheduler.getInstance(event.getJDA()).removeReminder(message.getIdLong());

View File

@ -11,8 +11,6 @@ import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.channel.concrete.ForumChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.forums.ForumPost;
import net.dv8tion.jda.api.entities.channel.forums.ForumTag;
import net.dv8tion.jda.api.entities.channel.forums.ForumTagSnowflake;
import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
@ -25,7 +23,6 @@ import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import java.awt.*;
import java.util.List;
import java.util.Optional;
public class ButtonSuggestionReviewAccept extends DiscordButton {
@ -124,6 +121,11 @@ public class ButtonSuggestionReviewAccept extends DiscordButton {
public void sendSuggestionInForum(ForumChannel forumChannel, TextChannel modLog, MessageEmbed.Field field, MessageEmbed suggestionMessage, String mentionMember, ButtonInteractionEvent event) {
MessageCreateData messageCreateData = new MessageCreateBuilder().addContent("**Suggestion by: " + mentionMember + "**\n\n" + field.getValue() + "\u200B").build();
if (field.getName() == null) {
Logger.altitudeLogs.error("Encountered empty name field when sending suggestion in forum");
return;
}
forumChannel.createForumPost(field.getName(), messageCreateData).queue(success -> {
event.getMessage().delete().queue(RestAction.getDefaultSuccess(), Util::handleFailure);
event.replyEmbeds(Util.genericSuccessEmbed("Success", "The suggestion was accepted and posted in the suggestion channel")).setEphemeral(true).queue();
@ -140,7 +142,7 @@ public class ButtonSuggestionReviewAccept extends DiscordButton {
.findAny()
.ifPresentOrElse(forumTag -> success.getThreadChannel().getManager().setAppliedTags(ForumTagSnowflake.fromId(forumTag.getIdLong()))
.queue(RestAction.getDefaultSuccess(), Util::handleFailure), () -> {
Logger.warning("No [Unanswered] reaction found for suggestion");
Logger.altitudeLogs.warning("No [Unanswered] reaction found for suggestion");
});
}, failure -> event.replyEmbeds(Util.genericErrorEmbed("Error", "Unable to send suggestion to the suggestion channel"))
.setEphemeral(true).queue(RestAction.getDefaultSuccess(), Util::handleFailure));

View File

@ -33,7 +33,7 @@ public class CommandManager extends ListenerAdapter {
public CommandManager(JDA jda, ModalManager modalManager, ContextMenuManager contextMenuManager, LockedChannel lockedChannel, SelectMenuManager selectMenuManager) {
commandList.put("manage", new ArrayList<>(List.of(new ScopeInfo(CommandScope.GLOBAL, 0))));
loadCommands();
Logger.info("Loading commands...");
Logger.altitudeLogs.info("Loading commands...");
CommandSetToggleableRoles commandSetToggleableRoles = new CommandSetToggleableRoles(jda, this);
commands = List.of(
new CommandManage(jda, this, contextMenuManager),
@ -152,13 +152,13 @@ public class CommandManager extends ListenerAdapter {
commandList.put(commandName, scopeInfoList);
}
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
} finally {
try {
if (statement != null)
statement.close();
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
}
}
}

View File

@ -56,7 +56,7 @@ public class CommandManage extends DiscordCommand {
String subcommandName = event.getInteraction().getSubcommandGroup();
subcommandName = subcommandName == null ? event.getInteraction().getSubcommandName() : subcommandName;
if (subcommandName == null) {
Logger.severe("No subcommand found for %", getName());
Logger.altitudeLogs.error("No subcommand found for " + getName());
return;
}

View File

@ -71,7 +71,7 @@ public class SubCommandDisable extends SubCommand {
private boolean disableCommand(DiscordCommand command, long guildId) {
if (!commandManager.disableCommand(command.getName(), new ScopeInfo(CommandScope.GUILD, guildId)))
return false;
String sql = "REMOVE FROM commands WHERE command_name = ? AND scope = ? and location_id = ?";
String sql = "DELETE FROM commands WHERE command_name = ? AND scope = ? and location_id = ?";
PreparedStatement statement = null;
try {
@ -80,18 +80,18 @@ public class SubCommandDisable extends SubCommand {
statement.setString(2, "GUILD");
statement.setLong(3, guildId);
if (!statement.execute()) {
Logger.warning("Unable to disable command: % for guild: %", command.getName(), String.valueOf(guildId));
Logger.altitudeLogs.warning("Unable to disable command: " + command.getName() + " for guild: " + guildId);
return false;
}
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
return false;
} finally {
try {
if (statement != null)
statement.close();
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
}
}
return true;

View File

@ -112,18 +112,18 @@ public class SubCommandEnable extends SubCommand {
statement.setString(2, "GUILD");
statement.setLong(3, guildId);
if (statement.executeUpdate() == 0) {
Logger.warning("Unable to enable command: % for guild: %", command.getName(), String.valueOf(guildId));
Logger.altitudeLogs.warning("Unable to enable command: " + command.getName() + " for guild: "+ guildId);
return false;
}
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
return false;
} finally {
try {
if (statement != null)
statement.close();
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
}
}
return true;
@ -141,18 +141,18 @@ public class SubCommandEnable extends SubCommand {
statement.setString(2, "GUILD");
statement.setLong(3, guildId);
if (statement.executeUpdate() == 0) {
Logger.warning("Unable to enable command: % for guild: %", contextMenu.getContextMenuId(), String.valueOf(guildId));
Logger.altitudeLogs.warning("Unable to enable command: " + contextMenu.getContextMenuId() + " for guild: " + guildId);
return false;
}
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
return false;
} finally {
try {
if (statement != null)
statement.close();
} catch (SQLException exception) {
Logger.sql(exception);
Logger.altitudeLogs.error(exception);
}
}
return true;
@ -180,7 +180,7 @@ public class SubCommandEnable extends SubCommand {
.filter(name -> name.toLowerCase().startsWith(commandName))
.filter(name -> !commandManager.getActiveLocations(name).contains(scopeInfo))
.limit(25)
.collect(Collectors.toList()));
.toList());
event.replyChoiceStrings(collect).queue();
}

View File

@ -103,7 +103,7 @@ public class CommandAuction extends DiscordCommand {
Integer startingPrice = event.getOption("starting-price", OptionMapping::getAsInt);
if (startingPrice == null) {
Logger.severe("Starting price magically became null");
Logger.altitudeLogs.error("Starting price magically became null");
replyCallbackAction.setEmbeds(Util.genericSuccessEmbed("Error", "Failed to store auction"))
.queue();
return;

View File

@ -83,7 +83,7 @@ public class CommandPoll extends DiscordCommand {
String subcommandName = event.getInteraction().getSubcommandGroup();
subcommandName = subcommandName == null ? event.getInteraction().getSubcommandName() : subcommandName;
if (subcommandName == null) {
Logger.severe("No subcommand found for %", getName());
Logger.altitudeLogs.error("No subcommand found for " + getName());
return;
}

View File

@ -83,7 +83,7 @@ public class SubCommandAdd extends SubCommand {
}
private void failedCreatingPoll(Throwable throwable, InteractionHook hook) {
Logger.warning(throwable.getMessage());
Logger.altitudeLogs.warning(throwable.getMessage());
hook.editOriginalEmbeds(Util.genericErrorEmbed("Failed to create Poll",
"Unable to create poll, please contact an Admin."))
.queue();

View File

@ -82,7 +82,7 @@ public class SubCommandAddButton extends SubCommand {
}
private void failedToGetMessage(Throwable throwable, InteractionHook hook) {
Logger.warning(throwable.getMessage());
Logger.altitudeLogs.warning(throwable.getMessage());
hook.editOriginalEmbeds(Util.genericErrorEmbed("Failed to get poll message",
"Please check if the poll still exists and the message id is correct."))
.queue();

View File

@ -3,8 +3,6 @@ package com.alttd.config;
import com.alttd.AltitudeBot;
import com.alttd.util.Logger;
import io.leangen.geantyref.TypeToken;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.ConfigurationOptions;
import org.spongepowered.configurate.serialize.SerializationException;
@ -18,7 +16,6 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
@SuppressWarnings({"unused", "SameParameterValue"})
@ -70,7 +67,7 @@ public abstract class AbstractConfig {
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (Exception ex) {
Logger.severe("Error invoking %.", method.toString());
Logger.altitudeLogs.error("Error invoking " + method);
ex.printStackTrace();
}
}

View File

@ -25,15 +25,15 @@ public class ConsoleActivity extends ConsoleCommand {
if (args.length == 1) {
Activity activity = jda.getPresence().getActivity();
if (activity == null)
Logger.info("No activity found.");
Logger.altitudeLogs.info("No activity found.");
else
Logger.info("Current activity: Listening to " + activity.getName());
Logger.altitudeLogs.info("Current activity: Listening to " + activity.getName());
return;
}
String newActivity = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
SettingsConfig.setActivity(newActivity);
jda.getPresence().setActivity(Activity.listening(newActivity));
Logger.info("Set activity to: Listening to " + newActivity);
Logger.altitudeLogs.info("Set activity to: Listening to " + newActivity);
}
@Override

View File

@ -36,7 +36,7 @@ public class ConsoleCommandManager {
.filter(consoleCommand -> consoleCommand.getName().equalsIgnoreCase(command))
.findFirst();
if (first.isEmpty()) {
Logger.info("Invalid command, see help for more info.");
Logger.altitudeLogs.info("Invalid command, see help for more info.");
return;
}
first.get().execute(command, args);
@ -47,7 +47,7 @@ public class ConsoleCommandManager {
}
public static void startConsoleCommands(JDA jda) {
Logger.info("Starting console commands");
Logger.altitudeLogs.info("Starting console commands");
if (instance == null)
instance = new ConsoleCommandManager(jda);
}

View File

@ -24,7 +24,7 @@ public class ConsoleHelp extends ConsoleCommand {
Template template = Template.of("commands", commandManager.getCommands().stream()
.map(ConsoleCommand::getHelpMessage)
.collect(Collectors.joining("\n")));
Logger.info(Parser.parse("Commands:\n<commands>", template));
Logger.altitudeLogs.info(Parser.parse("Commands:\n<commands>", template));
}
@Override

View File

@ -13,20 +13,18 @@ public class ConsoleReload extends ConsoleCommand {
@Override
public void execute(String command, String[] args) {
if (args.length != 2) {
Logger.info("Invalid argument length: " + getHelpMessage());
Logger.altitudeLogs.info("Invalid argument length: " + getHelpMessage());
return;
}
switch (args[1]) {
case "config" -> {
MessagesConfig.reload();
Logger.info("Reloaded Messages config.");
Logger.altitudeLogs.info("Reloaded Messages config.");
SettingsConfig.reload();
Logger.info("Reloaded Settings config.");
Logger.altitudeLogs.info("Reloaded Settings config.");
}
case "database" -> {
Logger.info("NOT IMPLEMENTED YET");
}
default -> Logger.info("Invalid argument: " + args[1]);
case "database" -> Logger.altitudeLogs.info("NOT IMPLEMENTED YET");
default -> Logger.altitudeLogs.info("Invalid argument: " + args[1]);
}
}

View File

@ -4,7 +4,6 @@ import com.alttd.config.SettingsConfig;
import com.alttd.util.Logger;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import java.util.Arrays;
import java.util.stream.Collectors;
@ -26,20 +25,20 @@ public class ConsoleStatus extends ConsoleCommand{
public void execute(String command, String[] args) {
if (args.length == 1) {
OnlineStatus status = jda.getPresence().getStatus();
Logger.info("Current status: " + status.getKey());
Logger.altitudeLogs.info("Current status: " + status.getKey());
return;
}
if (args.length != 2) {
Logger.info("Invalid argument length.");
Logger.altitudeLogs.info("Invalid argument length.");
return;
}
try {
OnlineStatus status = OnlineStatus.fromKey(args[1].toLowerCase());
SettingsConfig.setStatus(status.getKey());
jda.getPresence().setStatus(status);
Logger.info("Set status to: " + SettingsConfig.STATUS);
Logger.altitudeLogs.info("Set status to: " + SettingsConfig.STATUS);
} catch (IllegalArgumentException exception) {
Logger.info("Invalid status please use any of the following "
Logger.altitudeLogs.info("Invalid status please use any of the following "
+ Arrays.stream(OnlineStatus.values())
.map(OnlineStatus::getKey)
.collect(Collectors.joining(", ")));

View File

@ -11,7 +11,7 @@ public class ConsoleStop extends ConsoleCommand {
@Override
public void execute(String command, String[] args) {
Logger.info("Stopping bot...");
Logger.altitudeLogs.info("Stopping bot...");
AltitudeBot.getInstance().getJDA().cancelRequests();
System.exit(0);
}

View File

@ -18,7 +18,7 @@ public class Database {
try {
instance.openConnection();
} catch (Exception e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
}
@ -34,7 +34,7 @@ public class Database {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
connection = DriverManager.getConnection(
"jdbc:" + SettingsConfig.DATABASE_DRIVER
@ -55,11 +55,8 @@ public class Database {
try {
instance.openConnection();
}
catch (SQLException e) {
Logger.sql(e);
}
catch (Exception e){
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
return instance.connection;

View File

@ -11,30 +11,32 @@ import java.sql.SQLException;
public class DatabaseTables {
private static DatabaseTables instance = null;
private Connection connection;
private final Connection connection;
protected DatabaseTables (Connection connection) {
protected DatabaseTables(Connection connection) {
this.connection = connection;
init(DatabaseTables.class, this);
}
private void init(Class<?> clazz, Object instance) {
for (Method method : clazz.getDeclaredMethods()) {
if (Modifier.isPrivate(method.getModifiers())) {
if (method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE && method.getName().contains("Table")) {
if (!Modifier.isPrivate(method.getModifiers())) {
continue;
}
if (method.getParameterTypes().length != 0 || method.getReturnType() != Void.TYPE || !method.getName().contains("Table")) {
continue;
}
try {
method.setAccessible(true);
method.invoke(instance);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (Exception ex) {
Logger.severe("Error invoking %.", method.toString());
Logger.altitudeLogs.error("Error invoking " + method);
ex.printStackTrace();
}
}
}
}
}
private void createPollsTable() {
String sql = "CREATE TABLE IF NOT EXISTS polls(" +
@ -49,8 +51,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create polls table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create polls table, shutting down...");
}
}
@ -64,8 +66,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create commands table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create commands table, shutting down...");
}
}
@ -80,8 +82,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create output channel table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create output channel table, shutting down...");
}
}
@ -94,8 +96,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create toggleable roles table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create toggleable roles table, shutting down...");
}
}
@ -118,8 +120,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create reminders table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create reminders table, shutting down...");
}
}
@ -132,8 +134,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create locked channels table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create locked channels table, shutting down...");
}
}
@ -152,8 +154,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create auction table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create auction table, shutting down...");
}
}
@ -169,8 +171,8 @@ public class DatabaseTables {
try {
connection.prepareStatement(sql).executeUpdate();
} catch (SQLException e) {
Logger.sql(e);
Logger.severe("Unable to create auction action table, shutting down...");
Logger.altitudeLogs.error(e);
Logger.altitudeLogs.error("Unable to create auction action table, shutting down...");
}
}

View File

@ -2,7 +2,6 @@ package com.alttd.database.queries;
import com.alttd.database.Database;
import com.alttd.util.Logger;
import com.google.protobuf.StringValue;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -65,7 +64,7 @@ public class QueriesAssignAppeal {
if (nextUserId == -1) {
nextUserId = selectNextAssignment(0);
if (nextUserId == -1) {
Logger.warning("No one to assign appeals to!");
Logger.altitudeLogs.warning("No one to assign appeals to!");
return;
}
}
@ -82,7 +81,7 @@ public class QueriesAssignAppeal {
int res1 = statement1.executeUpdate();
int res2 = statement2.executeUpdate();
if (res1 != 1 || res2 != 1) {
Logger.warning("Unable to assign next appeal but got no error? results: " + res1 + res2);
Logger.altitudeLogs.warning("Unable to assign next appeal but got no error? results: " + res1 + res2);
}
} catch (SQLException exception) {
exception.printStackTrace();
@ -96,7 +95,7 @@ public class QueriesAssignAppeal {
private static void resetAssignedAppeal() {
long userId = selectNextAssignment(0);
if (userId == -1) {
Logger.warning("No one to assign appeals to!");
Logger.altitudeLogs.warning("No one to assign appeals to!");
} else {
setNextAppeal(userId);
}

View File

@ -50,7 +50,7 @@ public class QueriesAuctionAction {
try {
auctionType = AuctionType.valueOf(actionTypeString);
} catch (IllegalArgumentException e) {
Logger.warning("Invalid auction type found in database for message: % at time: %", messageId + "", actionTime + "");
Logger.altitudeLogs.warning("Invalid auction type found in database for message: " + messageId + " at time: " + actionTime);
continue;
}
actions.add(new AuctionAction(auctionType, userId, messageId, price, actionTime));

View File

@ -37,7 +37,7 @@ public class QueriesReminders {
return -1;
} catch (SQLException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
return -1;
}
@ -59,7 +59,7 @@ public class QueriesReminders {
return -1;
} catch (SQLException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
return -1;
}
@ -73,7 +73,7 @@ public class QueriesReminders {
return preparedStatement.executeUpdate() == 1;
} catch (SQLException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
return false;
}
@ -90,7 +90,7 @@ public class QueriesReminders {
}
return reminders;
} catch (SQLException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
return null;
}
@ -110,9 +110,11 @@ public class QueriesReminders {
byte[] data = null;
try {
data = resultSet.getBlob("data").getBinaryStream().readAllBytes();
Blob blob = resultSet.getBlob("data");
if (blob != null)
data = blob.getBinaryStream().readAllBytes();
} catch (IOException e) {
Logger.warning("Unable to read data for reminder with id: " + id);
Logger.altitudeLogs.warning("Unable to read data for reminder with id: " + id);
}
return new Reminder(id, title, desc, userId, guildId, channelId, messageId, shouldRepeat, creationDate, remindDate, reminderType, data);

View File

@ -33,7 +33,7 @@ public record Reminder (int id, String title, String description, long userId, l
if (channelById == null)
channelById = guildById.getThreadChannelById(this.channelId);
if (channelById == null) {
Logger.warning("Unable to find text channel for reminder, text channel id: [" + channelId + "]");
Logger.altitudeLogs.warning("Unable to find text channel for reminder, text channel id: [" + channelId + "]");
return null;
}
@ -43,7 +43,7 @@ public record Reminder (int id, String title, String description, long userId, l
public Guild getGuild(JDA jda) {
Guild guildById = jda.getGuildById(guildId);
if (guildById == null) {
Logger.warning("Unable to find guild for reminder, guild id: [" + guildId + "]");
Logger.altitudeLogs.warning("Unable to find guild for reminder, guild id: [" + guildId + "]");
return null;
}

View File

@ -24,7 +24,7 @@ public class CommandOutputChannels {
return preparedStatement.executeUpdate() == 1;
} catch (SQLException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
return false;
}
}
@ -68,7 +68,7 @@ public class CommandOutputChannels {
}
}
} catch (SQLException e) {
Logger.exception(e);
Logger.altitudeLogs.error(e);
}
return null;
}

View File

@ -31,56 +31,46 @@ public class AppealRepost extends ListenerAdapter {
private final ButtonManager buttonManager;
public AppealRepost(ButtonManager buttonManager) {
Logger.info("Created Appeal Repost -----------------------------------------------------------------------------------------------------------");
Logger.altitudeLogs.info("Created Appeal Repost -----------------------------------------------------------------------------------------------------------");
this.buttonManager = buttonManager;
}
@Override
public void onMessageReceived(@Nonnull MessageReceivedEvent event) {
Logger.info("Message received:");
Logger.info(event.getMessage() + "\n\n" + event.getMessage().getContentRaw() + "\n\nembeds: " + event.getMessage().getEmbeds().size());
if (event.getMember() != null) { //Webhooks aren't members
Logger.info("Return 1");
return;
}
if (event.getGuild().getIdLong() != 514920774923059209L) {
Logger.info("Return 2");
if (!event.isFromGuild() || event.getGuild().getIdLong() != 514920774923059209L) {
return;
}
if (event.getChannel().getIdLong() != 514922555950235681L) {
Logger.info("Return 3 channel was: " + event.getChannel().getId());
return;
}
Message message = event.getMessage();
List<MessageEmbed> embeds = message.getEmbeds();
if (embeds.size() == 0) {
Logger.info("Return 4");
return;
}
MessageEmbed messageEmbed = embeds.get(0);
List<MessageEmbed.Field> fields = messageEmbed.getFields();
if (fields.size() == 0) {
Logger.info("Return 5");
return;
}
String name = fields.get(0).getName();
if (name == null || !name.equals("Punishment info")) {
Logger.info("Return 6");
return;
}
Logger.altitudeLogs.debug("Creating appeal");
EmbedBuilder embedBuilder = new EmbedBuilder(messageEmbed);
long userId = QueriesAssignAppeal.getAssignAppeal();
if (userId == -1){
Logger.info("user id was -1");
assignAndSendAppeal(embedBuilder, message, null);
} else {
Guild guild = message.getGuild();
Member member = guild.getMemberById(userId);
if (member != null) {
Logger.info("member was in cache");
assignAndSendAppeal(embedBuilder, message, member);
} else {
Logger.info("member wasn't in cache");
guild.retrieveMemberById(userId).queue(result -> assignAndSendAppeal(embedBuilder, message, result));
}
}
@ -96,7 +86,7 @@ public class AppealRepost extends ListenerAdapter {
Button reminderInProgress = buttonManager.getButtonFor("reminder_in_progress");
Button reminderDenied = buttonManager.getButtonFor("reminder_denied");
if (reminderAccepted == null || reminderInProgress == null || reminderDenied == null) {
Logger.warning("Unable to get a button for appeals");
Logger.altitudeLogs.warning("Unable to get a button for appeals");
return;
}
message.getChannel().sendMessageEmbeds(embed).queue(res -> {
@ -108,7 +98,7 @@ public class AppealRepost extends ListenerAdapter {
threadChannel.sendMessage(member.getAsMention() + " you have a new appeal!").queue();
}
}),
failure -> Logger.warning("Unable to create thread channel so won't schedule reminder..."));
failure -> Logger.altitudeLogs.warning("Unable to create thread channel so won't schedule reminder..."));
});
message.delete().queue();
@ -144,7 +134,7 @@ public class AppealRepost extends ListenerAdapter {
int id = QueriesReminders.storeReminder(reminder);
if (id == 0) {
Logger.warning("Unable to store reminder for appeal with message id: " + message.getId());
Logger.altitudeLogs.warning("Unable to store reminder for appeal with message id: " + message.getId());
return;
}
@ -153,7 +143,7 @@ public class AppealRepost extends ListenerAdapter {
ReminderScheduler instance = ReminderScheduler.getInstance(message.getJDA());
if (instance == null) {
QueriesReminders.removeReminder(reminder.id());
Logger.warning("Unable to start reminder, removing it from the database...");
Logger.altitudeLogs.warning("Unable to start reminder, removing it from the database...");
return;
}

View File

@ -27,7 +27,7 @@ public class JDAListener extends ListenerAdapter {
@Override
public void onReady(@NotNull ReadyEvent event) {
Logger.info("JDA ready to register commands.");
Logger.altitudeLogs.info("JDA ready to register commands.");
LockedChannel lockedChannel = new LockedChannel();
ButtonManager buttonManager = new ButtonManager();
AppealRepost appealRepost = new AppealRepost(buttonManager);
@ -43,11 +43,11 @@ public class JDAListener extends ListenerAdapter {
private void startSchedulers() {
ReminderScheduler reminderScheduler = ReminderScheduler.getInstance(jda);
if (reminderScheduler == null)
Logger.severe("Unable to start reminder scheduler!");
Logger.altitudeLogs.error("Unable to start reminder scheduler!");
AuctionScheduler auctionScheduler = AuctionScheduler.getInstance();
if (auctionScheduler == null)
Logger.severe("Unable to start auction scheduler!");
Logger.altitudeLogs.error("Unable to start auction scheduler!");
}
@Override

View File

@ -18,7 +18,7 @@ public class LockedChannel extends ListenerAdapter {
HashMap<Long, HashSet<Long>> tmp = QueriesLockedChannels.getLockedChannels();
lockedChannels = Objects.requireNonNullElseGet(tmp, HashMap::new);
if (tmp == null)
Logger.severe("Unable to load data from Locked Channels table");
Logger.altitudeLogs.error("Unable to load data from Locked Channels table");
}
public synchronized boolean lockChannel(long guildId, long channelId) {

View File

@ -23,6 +23,7 @@ public class RequestConfig extends AbstractConfig {
public static String REQUEST_CATEGORY = "776590138296893481";
public static String REQUEST_CHANNEL = "1017787342561476709";
public static String REQUEST_MESSAGE = "";
@SuppressWarnings("unused")
private void settings() {
REQUEST_GUILD_ID = requestConfig.getString("request.guild", REQUEST_GUILD_ID);
REQUEST_CATEGORY = requestConfig.getString("request.category", REQUEST_CATEGORY);
@ -37,6 +38,7 @@ public class RequestConfig extends AbstractConfig {
}
public static final List<Request> requests = new ArrayList<>();
@SuppressWarnings("unused")
private void loadRequests() {
requests.clear();
requestConfig.getNode("types").childrenMap().forEach((key, value) -> {
@ -48,7 +50,7 @@ public class RequestConfig extends AbstractConfig {
String description = value.node("description").getString();
String message = value.node("message").getString();
if (id == null || category == null || channel == null || name == null || description == null || message == null) {
Logger.warning("Requests are set up incorrectly!");
Logger.altitudeLogs.warning("Requests are set up incorrectly!");
} else {
requests.add(new Request(id, category, channel, name, title, description, message));
}

View File

@ -30,7 +30,7 @@ public class AuctionScheduler {
instance = this;
auctions = QueriesAuction.getAuctions();
if (auctions == null) {
Logger.severe("Unable to retrieve auctions");
Logger.altitudeLogs.error("Unable to retrieve auctions");
instance = null;
return;
}
@ -41,10 +41,7 @@ public class AuctionScheduler {
private void setNextAuction() {
Optional<Auction> first = auctions.values().stream().sorted().findFirst();
if (first.isEmpty())
nextAuction = null;
else
nextAuction = first.get();
nextAuction = first.orElse(null);
}
public static AuctionScheduler getInstance() {
@ -55,7 +52,7 @@ public class AuctionScheduler {
public synchronized void addAuction(Auction auction) {
if (!QueriesAuction.saveAuction(auction))
Logger.warning("Unable to save auction %", auction.getMessageId() + "");
Logger.altitudeLogs.warning("Unable to save auction " + auction.getMessageId());
auctions.put(auction.getMessageId(), auction);
setNextAuction();
}
@ -69,7 +66,7 @@ public class AuctionScheduler {
auctions.remove(auction.getMessageId());
setNextAuction();
if (!QueriesAuction.removeAuction(auction))
Logger.warning("Unable to remove auction %", auction.getMessageId() + "");
Logger.altitudeLogs.warning("Unable to remove auction " + auction.getMessageId());
}
public Auction getAuction(long messageId) {
@ -80,17 +77,17 @@ public class AuctionScheduler {
auction.updateMessage(success -> {
List<MessageEmbed> embeds = success.getEmbeds();
if (embeds.isEmpty()) {
Logger.warning("Received auction with no embed contents");
Logger.altitudeLogs.warning("Received auction with no embed contents");
return;
}
GuildChannel outputChannel = CommandOutputChannels.getOutputChannel(success.getGuild(), OutputType.AUCTION_LOG);
if (outputChannel != null) {
if (!(outputChannel instanceof GuildMessageChannel channel)) {
Logger.warning("Error" + outputChannel.getType().name() + " is not a valid crate auction log channel type");
Logger.altitudeLogs.warning("Error" + outputChannel.getType().name() + " is not a valid crate auction log channel type");
return;
}
if (!channel.canTalk()) {
Logger.warning("Error can't talk in auction log channel");
Logger.altitudeLogs.warning("Error can't talk in auction log channel");
return;
}
if (sendEmbed(embeds.get(0), channel, instaBuy))
@ -129,7 +126,7 @@ public class AuctionScheduler {
embedBuilder.setColor(Color.GREEN);
else
embedBuilder.setColor(Color.RED);
textChannel.sendMessageEmbeds(embedBuilder.build()).queue(Util::ignoreSuccess, failure -> Logger.warning("Failed to log auction result"));
textChannel.sendMessageEmbeds(embedBuilder.build()).queue(Util::ignoreSuccess, failure -> Logger.altitudeLogs.warning("Failed to log auction result"));
return true;
}
private class AuctionRun implements Runnable {

View File

@ -20,7 +20,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ -37,7 +36,7 @@ public class ReminderScheduler {
this.jda = jda;
reminders = QueriesReminders.getReminders();
if (reminders == null) {
Logger.severe("Unable to retrieve reminders");
Logger.altitudeLogs.error("Unable to retrieve reminders");
instance = null;
return;
}
@ -58,12 +57,14 @@ public class ReminderScheduler {
}
public synchronized void addReminder(Reminder reminder) {
Logger.altitudeLogs.debug("Adding reminder with messageId: " + reminder.messageId());
reminders.add(reminder);
reminders.sort(Comparator.comparingLong(Reminder::remindDate));
nextReminder = reminders.get(0);
}
public synchronized void removeReminder(Reminder reminder, boolean removeFromDatabase) {
Logger.altitudeLogs.debug("Removing reminder with messageId: " + reminder.messageId());
reminders.remove(reminder);
if (reminders.size() == 0)
nextReminder = null;
@ -74,6 +75,7 @@ public class ReminderScheduler {
}
public synchronized void removeReminder(long messageId) {
Logger.altitudeLogs.debug("Attempting to remove reminder with messageId: " + messageId);
reminders.stream()
.filter(reminder -> reminder.messageId() == messageId)
.findAny()
@ -88,7 +90,7 @@ public class ReminderScheduler {
while (nextReminder != null && time > nextReminder.remindDate()) {
Channel channel = nextReminder.getChannel(jda);
if (channel == null) {
Logger.warning("Couldn't find channel, unable to run reminder: " + nextReminder.id() +
Logger.altitudeLogs.warning("Couldn't find channel, unable to run reminder: " + nextReminder.id() +
"\ntitle: [" + nextReminder.title() +
"]\ndescription: [" + nextReminder.description() + "]");
return;
@ -143,9 +145,7 @@ public class ReminderScheduler {
return threadChannel.sendMessageEmbeds(embedBuilder.build());
}
}
default -> {
Logger.warning("Received unexpected channel type " + channel.getType() + " can't send reminder...");
}
default -> Logger.altitudeLogs.warning("Received unexpected channel type " + channel.getType() + " can't send reminder...");
}
return null;
}

View File

@ -2,11 +2,13 @@ package com.alttd.util;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.utils.FileUpload;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
@ -28,7 +30,7 @@ public class ExcelWriter {
public synchronized void addRow(String... data) {
if (done) {
Logger.warning("Tried to write to finished excel file");
Logger.altitudeLogs.warning("Tried to write to finished excel file");
return;
}
Row row = sheet.createRow(currentRow++);

View File

@ -1,84 +1,32 @@
package com.alttd.util;
import com.alttd.AltitudeBot;
import com.alttd.AltitudeLogs;
import com.alttd.LogLevel;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
public class Logger { //TODO make this log to a file
private static final java.util.logging.Logger info;
private static final java.util.logging.Logger error;
private static final java.util.logging.Logger sql;
public class Logger {
public static AltitudeLogs altitudeLogs;
static {
File logDir = new File(new File(AltitudeBot.getInstance().getDataFolder()).getParent() + File.separator + "logs");
if (!logDir.exists())
{
if (!logDir.mkdir()) {
Logger.info("UNABLE TO CREATE LOGGING DIRECTORY");
System.exit(1);
}
}
info = java.util.logging.Logger.getLogger("info");
error = java.util.logging.Logger.getLogger("error");
sql = java.util.logging.Logger.getLogger("sql");
info.setLevel(Level.ALL);
error.setLevel(Level.ALL);
sql.setLevel(Level.ALL);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd");
Date date = new Date();
String formattedTime = dateFormat.format(date.getTime());
Logger.altitudeLogs = new AltitudeLogs().setTimeFormat("[HH:mm:ss] ");
try {
info.addHandler(new FileHandler(logDir.getAbsolutePath() + File.separator +
formattedTime + "info.log"));
error.addHandler(new FileHandler(logDir.getAbsolutePath() + File.separator +
formattedTime + "error.log"));
sql.addHandler(new FileHandler(logDir.getAbsolutePath() + File.separator +
formattedTime + "sql.log"));
Logger.altitudeLogs
.setLogPath(new File(AltitudeBot.getInstance().getDataFolder()).getParent() + File.separator + "logs")
.setLogName("debug.log", LogLevel.DEBUG)
.setLogName("info.log", LogLevel.INFO)
.setLogName("warning.log", LogLevel.WARNING)
.setLogName("error.log", LogLevel.ERROR)
.setLogDateFormat("yyyy-MM-dd");
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
Logger.altitudeLogs.error(e);
}
}
public static void info(String message, String... replacements) {
message = replace(message, replacements);
info.info(message);
}
public static void warning(String message, String... replacements) {
message = replace(message, replacements);
error.warning(message);
}
public static void severe(String message, String... replacements) {
message = replace(message, replacements);
error.severe(message);
}
public static void sql(String message) {
sql.info(message);
}
public static void sql(SQLException exception) {
exception.printStackTrace();
sql.info("SQLState: " + exception.getSQLState() + "\n");
sql.severe("Error:\n" + exception.getMessage());
}
public static void exception(Exception exception) {
exception.printStackTrace();
error.severe("Error:\n" + exception.getMessage());
Logger.altitudeLogs.warning(message);
}
private static String replace(String message, String... replacements) {
@ -90,4 +38,7 @@ public class Logger { //TODO make this log to a file
return message;
}
public static void setDebugActive(boolean debug) {
Logger.altitudeLogs.setLogLevelActive(LogLevel.DEBUG, debug);
}
}

View File

@ -4,7 +4,6 @@ import com.alttd.commandManager.CommandManager;
import com.alttd.commandManager.ScopeInfo;
import com.alttd.commandManager.SubOption;
import com.alttd.config.MessagesConfig;
import com.alttd.config.SettingsConfig;
import com.alttd.templates.Parser;
import com.alttd.templates.Template;
import net.dv8tion.jda.api.EmbedBuilder;
@ -34,12 +33,12 @@ public class Util {
.collect(Collectors.toList());
}
public static void ignoreSuccess(Object o) {
public static void ignoreSuccess(Object ignoredO) {
// IDK I thought this looked nicer in the .queue call
}
public static void handleFailure(Throwable failure) {
Logger.severe(failure.getMessage());
Logger.altitudeLogs.error(failure.getMessage());
}
public static MessageEmbed guildOnlyCommand(String commandName) {
@ -108,8 +107,7 @@ public class Util {
for (ScopeInfo info : commandManager.getActiveLocations(commandName)) {
switch (info.getScope()) {
case GLOBAL -> {
if (SettingsConfig.DEBUG)
Logger.info("Loading command [" + commandName + "] on global.");
Logger.altitudeLogs.debug("Loading command [" + commandName + "] on global.");
jda.upsertCommand(commandData).queue();
// jda.updateCommands().addCommands(commandData).queue();
}
@ -117,7 +115,7 @@ public class Util {
Guild guildById = jda.getGuildById(info.getId());
if (guildById == null)
{
Logger.warning("Tried to add command % to invalid guild %.", commandName, String.valueOf(info.getId()));
Logger.altitudeLogs.warning("Tried to add command " + commandName + " to invalid guild " + info.getId());
continue;
}
registerCommand(guildById, commandData, commandName);
@ -127,15 +125,13 @@ public class Util {
}
public static void registerCommand(Guild guild, CommandData commandData, String commandName) {
if (SettingsConfig.DEBUG)
Logger.info("Loading command [" + commandName + "] on guild [" + guild.getName() + "].");
Logger.altitudeLogs.debug("Loading command [" + commandName + "] on guild [" + guild.getName() + "].");
// guild.upsertCommand(commandData).queue();
guild.upsertCommand(commandData).queue(RestAction.getDefaultSuccess(), Util::handleFailure);
}
public static void deleteCommand(Guild guild, long id, String commandName) {
if (SettingsConfig.DEBUG)
Logger.info("Deleting command [" + commandName + "] on guild [" + guild.getName() + "].");
Logger.altitudeLogs.debug("Deleting command [" + commandName + "] on guild [" + guild.getName() + "].");
guild.deleteCommandById(id).queue();
}