Remove redundant API command fetcher
All checks were successful
continuous-integration/drone/push Build is passing

We have our own command listener now, so we don't need to rely on Discord's slow API.
This commit is contained in:
Bea 2022-11-22 14:53:46 +01:00
parent 526880e1f1
commit 244e8ace76
6 changed files with 22 additions and 68 deletions

View File

@ -1,18 +1,15 @@
package wtf.beatrice.hidekobot; package wtf.beatrice.hidekobot;
import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import wtf.beatrice.hidekobot.datasource.ConfigurationSource; import wtf.beatrice.hidekobot.datasource.ConfigurationSource;
import wtf.beatrice.hidekobot.datasource.DatabaseSource; import wtf.beatrice.hidekobot.datasource.DatabaseSource;
import wtf.beatrice.hidekobot.listeners.MessageLogger; import wtf.beatrice.hidekobot.listeners.MessageLogger;
import wtf.beatrice.hidekobot.listeners.SlashCommandListener;
import wtf.beatrice.hidekobot.util.Logger; import wtf.beatrice.hidekobot.util.Logger;
import java.awt.*; import java.awt.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Cache public class Cache
{ {
@ -36,7 +33,8 @@ public class Cache
private static final String botVersion = "0.2.0-slash"; // we should probably find a way to make this consistent with Maven private static final String botVersion = "0.2.0-slash"; // we should probably find a way to make this consistent with Maven
private static final String botName = "HidekoBot"; private static final String botName = "HidekoBot";
private static List<Command> registeredCommands = new ArrayList<>();
private static SlashCommandListener slashCommandListener = null;
private final static String defaultInviteLink = private final static String defaultInviteLink =
"https://discord.com/api/oauth2/authorize?client_id=%userid%&scope=bot+applications.commands&permissions=8"; "https://discord.com/api/oauth2/authorize?client_id=%userid%&scope=bot+applications.commands&permissions=8";
@ -202,32 +200,14 @@ public class Cache
return color == null ? defaultColor : color; return color == null ? defaultColor : color;
} }
/**
* Set the list of registered commands. They will be sorted alphabetically. public static void setSlashCommandListener(SlashCommandListener commandListener)
*
* @param commands a list of registered commands.
*/
public static void setRegisteredCommands(List<Command> commands)
{ {
// sort alphabetically by field getName() slashCommandListener = commandListener;
List<Command> tempList = commands
.stream()
.sorted(Comparator.comparing(Command::getName))
.toList();
registeredCommands = new ArrayList<>(tempList);
} }
/** public static SlashCommandListener getSlashCommandListener() { return slashCommandListener; }
* Get a list of all bot registered commands, sorted alphabetically.
*
* @return a copy of the List.
*/
public static List<Command> getRegisteredCommands()
{
return new ArrayList<>(registeredCommands);
}
/** /**
* Set the bot's startup time. Generally only used at boot time. * Set the bot's startup time. Generally only used at boot time.

View File

@ -13,7 +13,6 @@ import wtf.beatrice.hidekobot.listeners.ButtonInteractionListener;
import wtf.beatrice.hidekobot.listeners.MessageListener; import wtf.beatrice.hidekobot.listeners.MessageListener;
import wtf.beatrice.hidekobot.listeners.SlashCommandCompleter; import wtf.beatrice.hidekobot.listeners.SlashCommandCompleter;
import wtf.beatrice.hidekobot.listeners.SlashCommandListener; import wtf.beatrice.hidekobot.listeners.SlashCommandListener;
import wtf.beatrice.hidekobot.runnables.CommandsUpdateTask;
import wtf.beatrice.hidekobot.runnables.ExpiredMessageTask; import wtf.beatrice.hidekobot.runnables.ExpiredMessageTask;
import wtf.beatrice.hidekobot.runnables.HeartBeatTask; import wtf.beatrice.hidekobot.runnables.HeartBeatTask;
import wtf.beatrice.hidekobot.util.Logger; import wtf.beatrice.hidekobot.util.Logger;
@ -109,6 +108,7 @@ public class HidekoBot
slashCommandListener.registerCommand(new InviteCommand()); slashCommandListener.registerCommand(new InviteCommand());
slashCommandListener.registerCommand(new PingCommand()); slashCommandListener.registerCommand(new PingCommand());
slashCommandListener.registerCommand(new SayCommand()); slashCommandListener.registerCommand(new SayCommand());
Cache.setSlashCommandListener(slashCommandListener);
// register listeners // register listeners
jda.addEventListener(new MessageListener()); jda.addEventListener(new MessageListener());
@ -145,8 +145,6 @@ public class HidekoBot
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); // todo: try-with-resources ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); // todo: try-with-resources
ExpiredMessageTask expiredMessageTask = new ExpiredMessageTask(); ExpiredMessageTask expiredMessageTask = new ExpiredMessageTask();
scheduler.scheduleAtFixedRate(expiredMessageTask, 5, 5, TimeUnit.SECONDS); //every 5 seconds scheduler.scheduleAtFixedRate(expiredMessageTask, 5, 5, TimeUnit.SECONDS); //every 5 seconds
CommandsUpdateTask commandsUpdateTask = new CommandsUpdateTask();
scheduler.scheduleAtFixedRate(commandsUpdateTask, 10, 300, TimeUnit.SECONDS); //every 5 minutes
HeartBeatTask heartBeatTask = new HeartBeatTask(); HeartBeatTask heartBeatTask = new HeartBeatTask();
scheduler.scheduleAtFixedRate(heartBeatTask, 10, 30, TimeUnit.SECONDS); //every 30 seconds scheduler.scheduleAtFixedRate(heartBeatTask, 10, 30, TimeUnit.SECONDS); //every 30 seconds

View File

@ -2,7 +2,6 @@ package wtf.beatrice.hidekobot.commands.slash;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Cache; import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot; import wtf.beatrice.hidekobot.HidekoBot;
@ -27,7 +26,7 @@ public class BotInfoCommand implements SlashCommand
// defer reply because this might take a moment // defer reply because this might take a moment
event.deferReply().queue(); event.deferReply().queue();
List<Command> registeredCommands = Cache.getRegisteredCommands(); List<SlashCommand> registeredCommands = Cache.getSlashCommandListener().getRegisteredCommands();
EmbedBuilder embedBuilder = new EmbedBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder();
@ -51,8 +50,8 @@ public class BotInfoCommand implements SlashCommand
commandsListBuilder.append(registeredCommands.size()).append( " total - "); commandsListBuilder.append(registeredCommands.size()).append( " total - ");
for(int i = 0; i < registeredCommands.size(); i++) for(int i = 0; i < registeredCommands.size(); i++)
{ {
Command cmd = registeredCommands.get(i); SlashCommand cmd = registeredCommands.get(i);
commandsListBuilder.append("`" + cmd.getName() + "`"); commandsListBuilder.append("`").append(cmd.getCommandName()).append("`");
if(i + 1 != registeredCommands.size()) // don't add comma in last iteration if(i + 1 != registeredCommands.size()) // don't add comma in last iteration
{ {

View File

@ -5,12 +5,13 @@ import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.objects.SlashCommand; import wtf.beatrice.hidekobot.objects.SlashCommand;
import java.util.HashMap; import java.util.LinkedList;
import java.util.TreeMap;
public class SlashCommandListener extends ListenerAdapter public class SlashCommandListener extends ListenerAdapter
{ {
HashMap<String, SlashCommand> registeredCommands = new HashMap<>(); TreeMap<String, SlashCommand> registeredCommands = new TreeMap<>();
public void registerCommand(SlashCommand command) public void registerCommand(SlashCommand command)
{ {
@ -18,6 +19,14 @@ public class SlashCommandListener extends ListenerAdapter
registeredCommands.put(command.getCommandName(), command); registeredCommands.put(command.getCommandName(), command);
} }
public SlashCommand getRegisteredCommand(String label)
{
return registeredCommands.get(label);
}
public LinkedList<SlashCommand> getRegisteredCommands()
{ return new LinkedList<>(registeredCommands.values()); }
@Override @Override
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event)
{ {

View File

@ -1,25 +0,0 @@
package wtf.beatrice.hidekobot.runnables;
import net.dv8tion.jda.api.JDA;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.util.Logger;
public class CommandsUpdateTask implements Runnable {
private final Logger logger;
public CommandsUpdateTask()
{
logger = new Logger(getClass());
}
@Override
public void run() {
if(Cache.isVerbose()) logger.log("Refreshing commands cache...");
JDA instance = HidekoBot.getAPI();
if(instance == null) return;
Cache.setRegisteredCommands(instance.retrieveCommands().complete());
if(Cache.isVerbose()) logger.log("Commands cache refreshed!");
}
}

View File

@ -7,7 +7,6 @@ import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands; import net.dv8tion.jda.api.interactions.commands.build.Commands;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot; import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.listeners.MessageListener; import wtf.beatrice.hidekobot.listeners.MessageListener;
@ -123,11 +122,5 @@ public class SlashCommandUtil
jdaInstance.updateCommands().addCommands(allCommands).queue(); jdaInstance.updateCommands().addCommands(allCommands).queue();
logger.log("Commands updated. New total: " + allCommands.size() + "."); logger.log("Commands updated. New total: " + allCommands.size() + ".");
} }
// cache the registered commands.
// note that if this is the first time the bot runs after updating commands,
// this will probably still return the previous configuration because the discord api
// needs to propagate. this is why we also set up a command updater task (ExpiredMessageTask).
Cache.setRegisteredCommands(jdaInstance.retrieveCommands().complete());
} }
} }