Skip to content

Commit

Permalink
Refactor resource bundle method and update class instances.
Browse files Browse the repository at this point in the history
  • Loading branch information
SeveralCircles committed Mar 29, 2024
1 parent f70cd96 commit f194bf2
Show file tree
Hide file tree
Showing 14 changed files with 89 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 20 additions & 10 deletions src/main/java/com/severalcircles/flames/Flames.java
Original file line number Diff line number Diff line change
Expand Up @@ -197,16 +197,26 @@ public static void incrementErrorCount() {
System.exit(2);
}
}
public static ResourceBundle local() {
StackTraceElement[] st = Thread.currentThread().getStackTrace();
String className = st[2].getClassName();
className = className.replace(".", "/"); // This is a hack to make the ResourceBundle work
return ResourceBundle.getBundle(className);
public static ResourceBundle local(Class<?> cls) {
String className = cls.getName().replace(".", "/");
try {
return ResourceBundle.getBundle(className);
} catch (MissingResourceException e) {
// Add an appropriate error handler here.
// For instance: return a default ResourceBundle or log an error message
Logger.getLogger("Main").log(Level.WARNING, "Failed to get resource bundle for " + className, e);
throw e;
}
}
public static ResourceBundle local(Locale locale) {
StackTraceElement[] st = Thread.currentThread().getStackTrace();
String className = st[2].getClassName();
className = className.replace(".", "/"); // This is a hack to make the ResourceBundle work
return ResourceBundle.getBundle(className, locale);
public static ResourceBundle local(Class<?> cls, Locale locale) {
String className = cls.getName().replace(".", "/");
try {
return ResourceBundle.getBundle(className, locale);
} catch (MissingResourceException e) {
// Add an appropriate error handler here.
// For instance: return a default ResourceBundle or log an error message
Logger.getLogger("Main").log(Level.WARNING, "Failed to get resource bundle for " + className, e);
throw e;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ public class SparkConversation extends Conversation {
Timer t2 = new Timer();
int votes = 0;
MessageChannelUnion channel;

/**
* Initializes a new SparkConversation object.
*
* @param channel The message channel in which the conversation is taking place.
* @param question The question for the conversation.
* @param minutes The duration of the conversation in minutes (between 1 and 5).
*/
public SparkConversation(MessageChannelUnion channel, String question, int minutes) {
super((GuildMessageChannel) channel);
this.channel = channel;
Expand All @@ -51,6 +59,11 @@ public void run() {
}, minutes * 60000L);
channel.asTextChannel().getManager().setSlowmode(minutes * 60).complete();
}

/**
* Finish the spark conversation by selecting the message with the highest votes,
* sending the results as an embed, and performing necessary cleanup tasks.
*/
void finish() {
AtomicReference<String> answer = new AtomicReference<>("");
AtomicInteger highest = new AtomicInteger();
Expand All @@ -65,12 +78,27 @@ void finish() {
channel.asTextChannel().getManager().setSlowmode(0).complete();
Logger.getGlobal().info("Spark conversation ended.");
}

/**
* Process a message in the conversation.
*
* @param message The message to be processed.
* @param finishedAnalysis The analysis result of the message.
* @throws ExpiredConversationException if the conversation has expired.
*/
@Override
public void processMessage(Message message, FinishedAnalysis finishedAnalysis) throws ExpiredConversationException {
super.processMessage(message, finishedAnalysis);

}

/**
* Adds a vote to a message by a user.
*
* @param message The message to vote for.
* @param user The user who is voting.
* @throws AlreadyVotedException if the user has already voted for the message.
*/
public void addMessageVote(Message message, User user) throws AlreadyVotedException {
if (alreadyVoted.contains(user.getId())) {
throw new AlreadyVotedException("User has already voted.");
Expand Down
51 changes: 25 additions & 26 deletions src/main/java/com/severalcircles/flames/events/CommandEvent.java
Original file line number Diff line number Diff line change
@@ -1,50 +1,49 @@
/*
* Copyright (c) 2021 Several Circles.
*/

package com.severalcircles.flames.events;

import com.severalcircles.flames.Flames;
import com.severalcircles.flames.data.FlamesDataManager;
import com.severalcircles.flames.data.user.FlamesUser;
import com.severalcircles.flames.events.FlamesDiscordEvent;
import com.severalcircles.flames.exception.FlamesException;
import com.severalcircles.flames.exception.handle.ExceptionHandler;
import com.severalcircles.flames.frontend.FlamesCommand;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CommandEvent extends ListenerAdapter implements FlamesDiscordEvent {

private final Logger logger = Logger.getLogger(CommandEvent.class.getName());

public void register(JDA api) {
api.addEventListener(new CommandEvent());
Logger.getGlobal().log(Level.FINE, "Registering " + MessageEvent.class.getName());
logger.log(Level.FINE, "Registering " + MessageEvent.class.getName());
}

@Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
new Thread(() ->{
System.out.println("Slash command detected");
//noinspection ResultOfMethodCallIgnored
event.deferReply(true);
System.out.println(event.getName());
for (Map.Entry<String, FlamesCommand> entry : Flames.commandMap.entrySet()) {
if (entry.getKey().contains(event.getName())) {
try {
// System.out.println(Flames.commandMap.get(entry.getKey()));
FlamesUser fl = FlamesDataManager.readUser(event.getUser());
// throw new BadArgumentsException(fl, "This is a shitpost");
Flames.commandMap.get(entry.getKey()).execute(event, fl);
} catch (FlamesException e) {
event.replyEmbeds(e.getHandler().handleThenGetFrontend()).complete();
} catch (Exception e) {
event.replyEmbeds(new ExceptionHandler(e).handleThenGetFrontend()).complete();
}
}
}
}).start();}}
logger.log(Level.FINE, "Slash command detected");

logger.log(Level.FINE, event.getName());
Flames.commandMap.entrySet().stream()
.filter(entry -> entry.getKey().contains(event.getName()))
.findFirst()
.ifPresentOrElse(entry -> {
try {
FlamesUser flu = FlamesDataManager.readUser(event.getUser());
entry.getValue().execute(event, flu);
} catch (FlamesException e) {
event.replyEmbeds(e.getHandler().handleThenGetFrontend()).complete();
} catch (Exception e) {
event.replyEmbeds(new ExceptionHandler(e).handleThenGetFrontend()).complete();
}
}, () -> {
logger.log(Level.INFO, "No Command Found.");
});
}).start();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@
import java.util.logging.Logger;

public class MessageEvent extends ListenerAdapter implements FlamesDiscordEvent {

/**
* This method is called when a message is received in the Discord server. It processes the message, analyzes its content, and performs various actions based on the analysis.
*
* @param event The event containing the received message.
*/
@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
Logger.getGlobal().log(Level.FINE,event.getAuthor().getId() + " Triggered Message Event");
Expand All @@ -38,6 +42,7 @@ public void onMessageReceived(@NotNull MessageReceivedEvent event) {
// Check to make sure it's worth processing the message
// Bots don't get processed by Flames, simply because it's easier on everyone.
if (user.isBot()) return;

if (user.getName().toUpperCase(Locale.ROOT).contains("GOLDLEWIS")) event.getMessage().reply("https://media.discordapp.net/attachments/543162982536970240/943936840015159336/SpottedGoldlewis.gif").complete();
String nick = "";

Check warning on line 47 in src/main/java/com/severalcircles/flames/events/MessageEvent.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unused assignment

Variable `nick` initializer `""` is redundant
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public ConversationEmbed(User user, FlamesUser flamesUser, Conversation conversa
this.user = user;
this.flamesUser = flamesUser;
this.conversation = conversation;
resources = Flames.local(flamesUser.getConfig().getLocale());
resources = Flames.local(getClass(),flamesUser.getConfig().getLocale());
}
public MessageEmbed get() {
String trendingEntity = "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public SparkResultsEmbed(String question, String answer, int votes) {
this.answer = answer;
this.votes = votes;
}
ResourceBundle local = Flames.local();
ResourceBundle local = Flames.local(SparkStartEmbed.class);
@Override
public MessageEmbed get() {
MessageEmbed embed = null;

Check warning on line 29 in src/main/java/com/severalcircles/flames/frontend/conversations/SparkResultsEmbed.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unused assignment

Variable `embed` initializer `null` is redundant
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class SparkStartEmbed implements FlamesEmbed {
String question;
int minutes;
public SparkStartEmbed(FlamesUser fluser, User user, String question, int minutes) {
local = Flames.local();
local = Flames.local(getClass());
this.fluser = fluser;
this.user = user;
this.question = question;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class GlobalDataEmbed implements FlamesEmbed {
// I'll fix this later lmao
private final ResourceBundle resources;
public GlobalDataEmbed(User user, FlamesUser flamesUser) {
resources = Flames.local(flamesUser.getConfig().getLocale());
resources = Flames.local(getClass(), flamesUser.getConfig().getLocale());
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class UserDataEmbed implements FlamesEmbed {
public UserDataEmbed(User user, FlamesUser flamesUser) {
this.user = user;
this.flamesUser = flamesUser;
resources = Flames.local(flamesUser.getConfig().getLocale());
resources = Flames.local(getClass(), flamesUser.getConfig().getLocale());
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public WelcomeBackEmbed(int dailyBonus, User user, FlamesUser flamesUser) {
this.dailyBonus = dailyBonus;
this.user = user;
this.flamesUser = flamesUser;
resources = Flames.local(flamesUser.getConfig().getLocale());
resources = Flames.local(getClass(), flamesUser.getConfig().getLocale());
}
public MessageEmbed get() {
Date now = Date.from(Instant.now());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class AboutEmbed implements FlamesEmbed {
private final ResourceBundle local;

public AboutEmbed(FlamesUser user) {
this.local = Flames.local(user.getConfig().getLocale());
this.local = Flames.local(getClass(), user.getConfig().getLocale());
}
public MessageEmbed get() {
return new EmbedBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public ThanksEmbed(User thanked, User sender, FlamesUser flamesUserThanked, Stri
this.sender = sender;
this.flamesUserThanked = flamesUserThanked;
this.msg = msg;
resources = Flames.local(flamesUserThanked.getConfig().getLocale());
resources = Flames.local(getClass(), flamesUserThanked.getConfig().getLocale());
if (this.msg.isEmpty()) this.msg = resources.getString("description");

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class TodayEmbed implements FlamesEmbed {
private static ResourceBundle resources;
public TodayEmbed(User user, FlamesUser flamesUser) {
this.flamesUser = flamesUser;
resources = Flames.local(flamesUser.getConfig().getLocale());
resources = Flames.local(getClass(), flamesUser.getConfig().getLocale());
}
public MessageEmbed get() {
String trendingEntity = "";
Expand Down

0 comments on commit f194bf2

Please sign in to comment.