diff --git a/src/main/java/com/mcmoddev/mmdbot/MMDBot.java b/src/main/java/com/mcmoddev/mmdbot/MMDBot.java index 859e3ee8..4fef74e1 100644 --- a/src/main/java/com/mcmoddev/mmdbot/MMDBot.java +++ b/src/main/java/com/mcmoddev/mmdbot/MMDBot.java @@ -159,14 +159,18 @@ public static void main(final String[] args) { .disableCache(CacheFlag.CLIENT_STATUS) .disableCache(CacheFlag.ONLINE_STATUS) .addEventListeners(new ThreadedEventListener(new MiscEvents(), GENERAL_EVENT_THREAD_POOL)) - .setActivity(Activity.watching("through the mist...")) - .build(); + .build().awaitReady(); CommandModule.setupCommandModule(); LoggingModule.setupLoggingModule(); + + MMDBot.getInstance().getPresence().setActivity(Activity.of(config.getActivityType(), config.getActivityName())); } catch (final LoginException exception) { MMDBot.LOGGER.error("Error logging in the bot! Please give the bot a valid token in the config file.", exception); System.exit(1); + } catch (InterruptedException e) { + MMDBot.LOGGER.error("Error awaiting caching.", e); + System.exit(1); } } diff --git a/src/main/java/com/mcmoddev/mmdbot/core/BotConfig.java b/src/main/java/com/mcmoddev/mmdbot/core/BotConfig.java index e83a69a1..b69f304f 100644 --- a/src/main/java/com/mcmoddev/mmdbot/core/BotConfig.java +++ b/src/main/java/com/mcmoddev/mmdbot/core/BotConfig.java @@ -30,6 +30,7 @@ import com.jagrosh.jdautilities.commons.utils.SafeIdUtil; import com.mcmoddev.mmdbot.MMDBot; import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Message; import org.jetbrains.annotations.NotNull; @@ -503,4 +504,12 @@ public void addRolePanel(final long channelId, final long messageId, final Strin public boolean isRolePanelPermanent(final long channelId, final long messageId) { return config.getOrElse("role_panels.%s-%s.permanent".formatted(channelId, messageId), false); } + + public Activity.ActivityType getActivityType() { + return Activity.ActivityType.valueOf(config.getOrElse("bot.activity.type", "PLAYING")); + } + + public String getActivityName() { + return config.getOrElse("bot.activity.name", ""); + } } diff --git a/src/main/java/com/mcmoddev/mmdbot/core/TaskScheduler.java b/src/main/java/com/mcmoddev/mmdbot/core/TaskScheduler.java index cb3cfb2a..ec677d95 100644 --- a/src/main/java/com/mcmoddev/mmdbot/core/TaskScheduler.java +++ b/src/main/java/com/mcmoddev/mmdbot/core/TaskScheduler.java @@ -73,4 +73,8 @@ public static void init() { } }, 0, 14, TimeUnit.DAYS); } + + public static void scheduleTask(Runnable toRun, long delay, TimeUnit unit) { + TIMER.schedule(toRun, delay, unit); + } } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/CommandModule.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/CommandModule.java index 3536fd28..6e90d963 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/CommandModule.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/CommandModule.java @@ -28,10 +28,10 @@ import com.mcmoddev.mmdbot.modules.commands.bot.info.CmdAbout; import com.mcmoddev.mmdbot.modules.commands.bot.info.CmdGist; import com.mcmoddev.mmdbot.modules.commands.bot.info.CmdHelp; -import com.mcmoddev.mmdbot.modules.commands.bot.info.CmdUptime; import com.mcmoddev.mmdbot.modules.commands.bot.management.CmdAvatar; import com.mcmoddev.mmdbot.modules.commands.bot.management.CmdRefreshScamLinks; import com.mcmoddev.mmdbot.modules.commands.bot.management.CmdRename; +import com.mcmoddev.mmdbot.modules.commands.bot.management.CmdRestart; import com.mcmoddev.mmdbot.modules.commands.bot.management.CmdShutdown; import com.mcmoddev.mmdbot.modules.commands.contextmenu.GuildOnlyMenu; import com.mcmoddev.mmdbot.modules.commands.contextmenu.message.ContextMenuAddQuote; @@ -62,14 +62,11 @@ import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdAddTrick; import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdEditTrick; import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdListTricks; -import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdRemoveTrick; import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdRunTrick; -import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdRunTrickExplicitly; +import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdTrick; import com.mcmoddev.mmdbot.utilities.ThreadedEventListener; import com.mcmoddev.mmdbot.utilities.Utils; -import com.mcmoddev.mmdbot.utilities.tricks.Tricks; import me.shedaniel.linkie.Namespaces; -import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.hooks.EventListener; import net.dv8tion.jda.api.interactions.commands.build.CommandData; @@ -140,21 +137,20 @@ public static void setupCommandModule() { new CmdOldChannels(), new CmdAvatar(), new CmdRename(), - new CmdUptime(), //TODO Setup DB storage for tricks and polish them off/add permission restrictions for when needed. - new CmdAddTrick(), new CmdEditTrick(), new CmdListTricks(), - new CmdRemoveTrick(), - new CmdRunTrickExplicitly(), + new CmdRunTrick(), new CmdShutdown(), + new CmdRestart(), new CmdQuote(), new CmdRolePanel(), - new CmdWarning()); + new CmdWarning(), + new CmdTrick()); addSlashCommand(CmdTranslateMappings.createCommands()); addSlashCommand(CmdMappings.createCommands()); // TODO: This is broken beyond belief. Consider moving away from linkie. - Curle - addSlashCommand(Tricks.getTricks().stream().map(CmdRunTrick::new).toArray(SlashCommand[]::new)); + // addSlashCommand(Tricks.getTricks().stream().map(CmdRunTrickSeparated::new).toArray(SlashCommand[]::new)); commandClient.addCommand(new CmdRefreshScamLinks()); commandClient.addCommand(new CmdReact()); @@ -176,8 +172,8 @@ public static void setupCommandModule() { MMDBot.getInstance().addEventListener(buttonListener(CmdTranslateMappings.ButtonListener.INSTANCE)); MMDBot.getInstance().addEventListener(buttonListener(CmdRoles.getListener())); MMDBot.getInstance().addEventListener(buttonListener(CmdHelp.getListener())); - MMDBot.getInstance().addEventListener(buttonListener(CmdListTricks.getListener())); - MMDBot.getInstance().addEventListener(buttonListener(CmdQuote.ListQuotes.getListener())); + MMDBot.getInstance().addEventListener(buttonListener(CmdListTricks.getListListener())); + MMDBot.getInstance().addEventListener(buttonListener(CmdQuote.ListQuotes.getQuoteListener())); MMDBot.LOGGER.warn("Command module enabled and loaded."); } else { MMDBot.LOGGER.warn("Command module disabled via config, commands will not work at this time!"); diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdAbout.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdAbout.java index d9f3eff5..da3ec135 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdAbout.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdAbout.java @@ -29,6 +29,9 @@ import java.awt.Color; import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; /** * Shows information about the bot. @@ -81,6 +84,10 @@ protected void execute(final SlashCommandEvent event) { true); embed.addField("Current maintainers:", "jriwanek, WillBL, KiriCattus, sciwhiz12, Curle, matyrobbrt", true); + embed.addField("I've been online for: ", Utils.getTimeDifference(Utils.getTimeFromUTC( + References.STARTUP_TIME), OffsetDateTime.now(ZoneOffset.UTC), + ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.HOURS, ChronoUnit.SECONDS) + , false); embed.setTimestamp(Instant.now()); if (event.isFromGuild() && Utils.memberHasRole(event.getMember(), MMDBot.getConfig().getRole("bot_maintainer"))) { diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdHelp.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdHelp.java index 3c6e520c..5435da07 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdHelp.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdHelp.java @@ -49,7 +49,7 @@ public class CmdHelp extends PaginatedCommand { private List commands; - private static CmdHelp.HelpListener listener; + private static ButtonListener helpListener; public CmdHelp() { super("help", @@ -59,15 +59,16 @@ public CmdHelp() { 25); arguments = "[command]"; - listener = new CmdHelp.HelpListener(); + this.listener = new PaginatedCommand.ButtonListener(); + helpListener = this.listener; } /** * Returns the instance of our button listener. * Used for handling the pagination buttons. */ - public static PaginatedCommand.ButtonListener getListener() { - return listener; + public static ButtonListener getListener() { + return helpListener; } /** @@ -136,8 +137,5 @@ protected EmbedBuilder getEmbed(int index) { return embed; } - - public class HelpListener extends PaginatedCommand.ButtonListener { - } } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdUptime.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdUptime.java deleted file mode 100644 index 24f87d3b..00000000 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/info/CmdUptime.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * MMDBot - https://github.com/MinecraftModDevelopment/MMDBot - * Copyright (C) 2016-2022 - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - * USA - * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html - */ -package com.mcmoddev.mmdbot.modules.commands.bot.info; - -import com.jagrosh.jdautilities.command.SlashCommand; -import com.mcmoddev.mmdbot.core.References; -import com.mcmoddev.mmdbot.utilities.Utils; -import net.dv8tion.jda.api.EmbedBuilder; -import com.jagrosh.jdautilities.command.SlashCommandEvent; - -import java.awt.Color; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.temporal.ChronoUnit; - -/** - * Shows how long the bot has been online. - * - * @author KiriCattus - * @author Curle - */ -public class CmdUptime extends SlashCommand { - - /** - * Instantiates a new Cmd uptime. - */ - public CmdUptime() { - super(); - name = "uptime"; - help = "State how long the current instance of the bot has been running, can also be used as a ping test."; - category = new Category("Info"); - guildOnly = false; - } - - /** - * Execute. - * - * @param event The {@link SlashCommandEvent CommandEvent} that triggered this Command. - */ - @Override - protected void execute(final SlashCommandEvent event) { - final var embed = new EmbedBuilder(); - - embed.setTitle("Time spent online."); - embed.setColor(Color.GREEN); - embed.addField("I've been online for: ", Utils.getTimeDifference(Utils.getTimeFromUTC( - References.STARTUP_TIME), OffsetDateTime.now(ZoneOffset.UTC), - ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.HOURS, ChronoUnit.SECONDS) - , false); - embed.setTimestamp(Instant.now()); - event.replyEmbeds(embed.build()).mentionRepliedUser(false).queue(); - } -} diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdRestart.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdRestart.java index 8b35803d..5dc5e149 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdRestart.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdRestart.java @@ -22,13 +22,20 @@ import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; +import com.jagrosh.jdautilities.command.SlashCommand; +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import com.mcmoddev.mmdbot.MMDBot; +import com.mcmoddev.mmdbot.core.TaskScheduler; + +import java.util.concurrent.TimeUnit; /** * Restart the bot on command rather than via console. * * @author KiriCattus + * @author matyrobbrt */ -public class CmdRestart extends Command { +public class CmdRestart extends SlashCommand { /** * Instantiates a new Cmd. @@ -43,13 +50,14 @@ public CmdRestart() { guildOnly = false; } - /** - * Try to restart the command from Discord rather than having to get someone with actual console access. - * - * @param event The event. - */ @Override - protected void execute(final CommandEvent event) { - //TODO Work on restart code, attempt to make it platform agnostic. -KiriCattus + protected void execute(final SlashCommandEvent event) { + event.reply("Restarting the bot!").queue(); + event.getJDA().shutdown(); + MMDBot.LOGGER.warn("Restarting the bot by request of {} via Discord!", event.getUser().getName()); + TaskScheduler.scheduleTask(() -> { + // TODO some other things may need to be nullified for this to restart with no exceptions! + MMDBot.main(new String[]{}); + }, 3, TimeUnit.SECONDS); } } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdShutdown.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdShutdown.java index ee0eb658..db8b32a1 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdShutdown.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/bot/management/CmdShutdown.java @@ -85,7 +85,7 @@ protected void execute(final SlashCommandEvent event) { }, "GuildCommandClearing").start(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); - msg.get().editOriginal("Error! Shutdown cancelled!").queue(); + event.reply("Error! Shutdown cancelled!").queue(); } return; } @@ -103,7 +103,7 @@ protected void execute(final SlashCommandEvent event) { }, "GlobalCommandClearing").start(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); - msg.get().editOriginal("Error! Shutdown cancelled!").queue(); + event.reply("Error! Shutdown cancelled!").queue(); } return; } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/general/PaginatedCommand.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/general/PaginatedCommand.java index 6d6aaaeb..1df1f7b2 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/general/PaginatedCommand.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/general/PaginatedCommand.java @@ -52,6 +52,7 @@ public abstract class PaginatedCommand extends SlashCommand { protected int items_per_page = 25; // The maximum number of items in the list. Update with #updateMaximum protected int maximum = 0; + protected PaginatedCommand.ButtonListener listener = new ButtonListener(); public PaginatedCommand(String name, String help, boolean guildOnly, List options, int items) { super(); @@ -106,9 +107,9 @@ protected void sendPaginatedMessage(SlashCommandEvent event) { * @return A row of buttons to go back and forth by one page. */ private ItemComponent[] createScrollButtons(int start) { - Button backward = Button.primary(getName() + "-" + start + "-prev", + Button backward = Button.primary(listener.getButtonID() + "-" + start + "-prev", Emoji.fromUnicode("◀️")).asDisabled(); - Button forward = Button.primary(getName() + "-" + start + "-next", + Button forward = Button.primary(listener.getButtonID() + "-" + start + "-next", Emoji.fromUnicode("▶️")).asDisabled(); if (start != 0) { @@ -130,7 +131,7 @@ private ItemComponent[] createScrollButtons(int start) { * Implement the {@link #getButtonID()} function in any way you like. * Make sure that this listener is registered to the {@link com.jagrosh.jdautilities.command.CommandClient}. */ - public abstract class ButtonListener extends ListenerAdapter { + public class ButtonListener extends ListenerAdapter { public String getButtonID() { return PaginatedCommand.this.getName(); diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/quotes/CmdQuote.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/quotes/CmdQuote.java index 940c385d..8bafaec6 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/quotes/CmdQuote.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/quotes/CmdQuote.java @@ -288,7 +288,7 @@ protected void execute(final SlashCommandEvent event) { * @author Curle */ public class ListQuotes extends PaginatedCommand { - private static QuoteListener listener; + private static ButtonListener quoteListener; /** * Create the command. @@ -299,11 +299,12 @@ public ListQuotes() { category = new Category("Fun"); guildOnly = true; - listener = new QuoteListener(); + this.listener = new QuoteListener(); + quoteListener = this.listener; } - public static QuoteListener getListener() { - return listener; + public static ButtonListener getQuoteListener() { + return quoteListener; } @Override @@ -353,7 +354,7 @@ protected EmbedBuilder getEmbed(int start) { } else { // Put it in the description. // message - author - embed.addField(String.valueOf(fetchedQuote.getID()), + embed.addField(String.valueOf(fetchedQuote.getID()), fetchedQuote.getQuoteText() + " - " + fetchedQuote.getQuotee().resolveReference(), false); } } @@ -364,7 +365,7 @@ protected EmbedBuilder getEmbed(int start) { public class QuoteListener extends PaginatedCommand.ButtonListener { @Override public String getButtonID() { - return "list"; + return "quotelist"; } } } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdAddTrick.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdAddTrick.java index 616a01cb..f6a3daa9 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdAddTrick.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdAddTrick.java @@ -23,11 +23,13 @@ import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jdautilities.command.SlashCommand; +import com.jagrosh.jdautilities.command.SlashCommandEvent; import com.mcmoddev.mmdbot.MMDBot; import com.mcmoddev.mmdbot.utilities.Utils; import com.mcmoddev.mmdbot.utilities.tricks.Trick; import com.mcmoddev.mmdbot.utilities.tricks.Tricks; -import com.jagrosh.jdautilities.command.SlashCommandEvent; + +import java.util.Optional; /** * Adds a trick to the list. @@ -40,63 +42,43 @@ * * @author Will BL * @author Curle + * @author matyrobbrt */ public final class CmdAddTrick extends SlashCommand { - /** - * Instantiates a new Cmd add trick. - */ - public CmdAddTrick() { - super(); - name = "addtrick"; - help = "Adds a new trick, either a string or an embed, if a string you only need the and ."; - category = new Category("Info"); - arguments = "( (or) " - + "<description> <colour-as-hex-code>"; - aliases = new String[]{"add-trick"}; - enabledRoles = new String[]{Long.toString(MMDBot.getConfig().getRole("bot_maintainer"))}; - guildOnly = true; - // we need to use this unfortunately :( can't create more than one commandclient - //guildId = Long.toString(MMDBot.getConfig().getGuildID()); - - children = Tricks.getTrickTypes().entrySet().stream().map(entry -> new SubCommand(entry.getKey(), entry.getValue())).toArray(SlashCommand[]::new); + private final Trick.TrickType<?> trickType; + + public CmdAddTrick(String name, Trick.TrickType<?> trickType) { + this.trickType = trickType; + this.name = "create-" + name; + this.help = "Add or create a " + name + "-type trick."; + this.guildOnly = true; + this.options = trickType.getArgs(); + enabledRoles = new String[]{Long.toString(MMDBot.getConfig().getRole(""))}; } @Override protected void execute(final SlashCommandEvent event) { - } - - /** - * A child command of AddTrick, handles adding a particular type of trick. - * - * @author Curle - * @author Will BL - */ - private static class SubCommand extends SlashCommand { - private final Trick.TrickType<?> trickType; - - public SubCommand(String name, Trick.TrickType<?> trickType) { - this.trickType = trickType; - this.name = name; - this.help = "Create a " + name + "-type trick."; - this.guildOnly = true; - this.options = trickType.getArgs(); + if (!Utils.checkCommand(this, event)) { + return; } - @Override - protected void execute(final SlashCommandEvent event) { - if (!Utils.checkCommand(this, event)) { - return; - } - - try { - Tricks.addTrick(trickType.createFromCommand(event)); - event.reply("Added trick!").mentionRepliedUser(false).setEphemeral(true).queue(); - } catch (IllegalArgumentException e) { - event.reply("A command with that name already exists!").mentionRepliedUser(false).setEphemeral(true).queue(); - MMDBot.LOGGER.warn("Failure adding trick: {}", e.getMessage()); - } + if (!Utils.memberHasRole(event.getMember(), MMDBot.getConfig().getRole("bot_maintainer"))) { + event.deferReply(true).setContent("Only Bot Maintainers can use this command.").queue(); + return; } + + Trick trick = trickType.createFromCommand(event); + Optional<Trick> originalTrick = Tricks.getTricks().stream() + .filter(t -> t.getNames().stream().anyMatch(n -> trick.getNames().contains(n))).findAny(); + + originalTrick.ifPresentOrElse(original -> { + Tricks.replaceTrick(original, trick); + event.reply("Updated trick!").mentionRepliedUser(false).setEphemeral(true).queue(); + }, () -> { + Tricks.addTrick(trick); + event.reply("Added trick!").mentionRepliedUser(false).setEphemeral(true).queue(); + }); } public static final class Prefix extends Command { diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdListTricks.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdListTricks.java index fd06bd9f..09992172 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdListTricks.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdListTricks.java @@ -37,25 +37,24 @@ * * @author Will BL * @author Curle + * @author matyrobbrt */ public final class CmdListTricks extends PaginatedCommand { - private static TrickListListener listener; + private static ButtonListener listListener; /** * Instantiates a new Cmd list tricks. */ public CmdListTricks() { - super("listtricks", "List all registered tricks.", true, new ArrayList<>(), 10); + super("list", "List all registered tricks.", true, new ArrayList<>(), 10); category = new Category("Fun"); - aliases = new String[]{"list-tricks", "tricks"}; guildOnly = true; - // we need to use this unfortunately :( can't create more than one commandclient - //guildId = Long.toString(MMDBot.getConfig().getGuildID()); - listener = new TrickListListener(); + this.listener = new TrickListListener(); + listListener = this.listener; } - public static TrickListListener getListener() { - return listener; + public static ButtonListener getListListener() { + return listListener; } /** @@ -88,7 +87,7 @@ protected EmbedBuilder getEmbed(int from) { public class TrickListListener extends ButtonListener { @Override public String getButtonID() { - return CmdListTricks.this.getName(); + return "listtricks"; } } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRemoveTrick.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRemoveTrick.java index 2d1f207c..6891ca05 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRemoveTrick.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRemoveTrick.java @@ -40,6 +40,7 @@ * * @author Will BL * @author Curle + * @author matyrobbrt */ public final class CmdRemoveTrick extends SlashCommand { @@ -48,16 +49,11 @@ public final class CmdRemoveTrick extends SlashCommand { */ public CmdRemoveTrick() { super(); - name = "removetrick"; + name = "remove"; help = "Removes a trick"; category = new Category("Management"); arguments = "<trick_name>"; - aliases = new String[]{"remove-trick", "remtrick"}; - enabledRoles = new String[]{Long.toString(MMDBot.getConfig().getRole("bot_maintainer"))}; guildOnly = true; - // we need to use this unfortunately :( can't create more than one commandclient - //guildId = Long.toString(MMDBot.getConfig().getGuildID()); - options = Collections.singletonList(new OptionData(OptionType.STRING, "trick", "The trick to delete.").setRequired(true)); } @@ -72,6 +68,11 @@ protected void execute(final SlashCommandEvent event) { return; } + if (!Utils.memberHasRole(event.getMember(), MMDBot.getConfig().getRole("bot_maintainer"))) { + event.deferReply(true).setContent("Only Bot Maintainers can use this command.").queue(); + return; + } + Tricks.getTrick(Utils.getOrEmpty(event, "trick")).ifPresent(Tricks::removeTrick); event.reply("Removed trick!").setEphemeral(true).queue(); } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrick.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrick.java index b4f878d7..8be3b261 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrick.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrick.java @@ -21,56 +21,50 @@ package com.mcmoddev.mmdbot.modules.commands.server.tricks; import com.jagrosh.jdautilities.command.SlashCommand; -import com.mcmoddev.mmdbot.modules.commands.CommandModule; -import com.mcmoddev.mmdbot.modules.commands.server.DeletableCommand; -import com.mcmoddev.mmdbot.utilities.Utils; -import com.mcmoddev.mmdbot.utilities.tricks.Trick; import com.jagrosh.jdautilities.command.SlashCommandEvent; +import com.mcmoddev.mmdbot.utilities.Utils; import com.mcmoddev.mmdbot.utilities.tricks.Tricks; +import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; -import java.util.ArrayList; -import java.util.Collections; +import javax.annotation.Nonnull; +import java.util.List; /** - * Runs a certain trick. - * Takes zero or one parameters, the argument string to be passed to the trick. + * Fetch and execute a given trick. + * Takes one or two parameters: the trick name, and optionally any arguments to be passed to the trick. * <p> * Takes the form: - * /test - * /[trickname] [args] + * /trick test + * /trick [name] [args] * * @author Will BL * @author Curle + * @author matyrobbrt */ -public final class CmdRunTrick extends SlashCommand implements DeletableCommand { - - private final String trickName; - private boolean deleted = false; +public final class CmdRunTrick extends SlashCommand { /** - * Instantiates a new command for a certain trick. + * Instantiates a new trick-running command */ - public CmdRunTrick(String trickName) { + public CmdRunTrick() { super(); - this.trickName = trickName; - name = trickName; - aliases = Tricks.getTrick(trickName).map(t -> t.getNames()).orElse(new ArrayList<>()).toArray(String[]::new); - help = "Invoke the trick " + trickName; - category = new Category("Fun"); - guildOnly = true; - options = Collections.singletonList(new OptionData(OptionType.STRING, "args", "The arguments for the trick, if any").setRequired(false)); - } + name = "run"; + help = "Invoke a specific trick by name."; - public CmdRunTrick(Trick trick) { - this(trick.getNames().get(0)); + options = List.of( + new OptionData(OptionType.STRING, "name", "The name of the trick to run").setRequired(true).setAutoComplete(true), + new OptionData(OptionType.STRING, "args", "The arguments for the trick, if any").setRequired(false) + ); } /** - * Execute. + * Executes the command. * - * @param event the event + * @param event the slash command event */ @Override protected void execute(final SlashCommandEvent event) { @@ -78,23 +72,14 @@ protected void execute(final SlashCommandEvent event) { return; } - Tricks.getTrick(trickName).ifPresentOrElse(trick -> event.reply(trick.getMessage(Utils.getOrEmpty(event, "args").split(" "))).setEphemeral(false).queue(), - () -> event.deferReply(true).setContent("This trick does not exist anymore!").queue()); - } - - @Override - public void delete() { - deleted = true; - } - - @Override - public void restore() { - deleted = false; - CommandModule.upsertCommand(this); + Tricks.getTrick(Utils.getOrEmpty(event, "name")).ifPresentOrElse( + trick -> event.reply(trick.getMessage(Utils.getOrEmpty(event, "args").split(" "))).setEphemeral(false).queue(), + () -> event.reply("No trick with that name was found.").setEphemeral(true).queue() + ); } @Override - public boolean isDeleted() { - return deleted; + public void onAutoComplete(final CommandAutoCompleteInteractionEvent event) { + event.replyChoiceStrings(Tricks.getTricks().stream().map(t -> t.getNames().get(0)).toList()).queue(); } } diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrickExplicitly.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrickExplicitly.java deleted file mode 100644 index c9815ee4..00000000 --- a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrickExplicitly.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * MMDBot - https://github.com/MinecraftModDevelopment/MMDBot - * Copyright (C) 2016-2022 <MMD - MinecraftModDevelopment> - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 - * USA - * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html - */ -package com.mcmoddev.mmdbot.modules.commands.server.tricks; - -import com.jagrosh.jdautilities.command.SlashCommand; -import com.mcmoddev.mmdbot.utilities.Utils; -import com.mcmoddev.mmdbot.utilities.tricks.Tricks; -import com.jagrosh.jdautilities.command.SlashCommandEvent; -import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.OptionData; - -import java.util.List; - -/** - * Fetch and execute a given trick. - * Takes one or two parameters: the trick name, and optionally any arguments to be passed to the trick. - * <p> - * Takes the form: - * /trick test - * /trick [name] [args] - * - * @author Will BL - * @author Curle - */ -public final class CmdRunTrickExplicitly extends SlashCommand { - - private static final String NAME = "trick"; - - /** - * Instantiates a new trick-running command - */ - public CmdRunTrickExplicitly() { - super(); - name = NAME; - help = "Invoke a specific trick by name."; - category = new Category("Fun"); - guildOnly = true; - // we need to use this unfortunately :( can't create more than one commandclient - //guildId = Long.toString(MMDBot.getConfig().getGuildID()); - - options = List.of( - new OptionData(OptionType.STRING, "name", "The name of the trick to run").setRequired(true), - new OptionData(OptionType.STRING, "args", "The arguments for the trick, if any").setRequired(false) - ); - } - - /** - * Executes the command. - * - * @param event the slash command event - */ - @Override - protected void execute(final SlashCommandEvent event) { - if (!Utils.checkCommand(this, event)) { - return; - } - - Tricks.getTrick(Utils.getOrEmpty(event, "name")).ifPresentOrElse( - trick -> event.reply(trick.getMessage(Utils.getOrEmpty(event, "args").split(" "))).setEphemeral(false).queue(), - () -> event.reply("No trick with that name was found.").setEphemeral(true).queue() - ); - } -} diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrickSeparated.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrickSeparated.java new file mode 100644 index 00000000..2a071b25 --- /dev/null +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdRunTrickSeparated.java @@ -0,0 +1,103 @@ +/* + * MMDBot - https://github.com/MinecraftModDevelopment/MMDBot + * Copyright (C) 2016-2022 <MMD - MinecraftModDevelopment> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + */ +package com.mcmoddev.mmdbot.modules.commands.server.tricks; + +import com.jagrosh.jdautilities.command.SlashCommand; +import com.mcmoddev.mmdbot.modules.commands.CommandModule; +import com.mcmoddev.mmdbot.modules.commands.server.DeletableCommand; +import com.mcmoddev.mmdbot.utilities.Utils; +import com.mcmoddev.mmdbot.utilities.tricks.Trick; +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import com.mcmoddev.mmdbot.utilities.tricks.Tricks; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; + +import java.util.ArrayList; +import java.util.Collections; + +/** + * Runs a certain trick. + * Takes zero or one parameters, the argument string to be passed to the trick. + * <p> + * Takes the form: + * /test + * /[trickname] [args] + * + * @deprecated This system is bad, and such I added autocomplete to `/trick run` - matyrobbrt + * + * @author Will BL + * @author Curle + */ +@Deprecated(forRemoval = true) +public final class CmdRunTrickSeparated extends SlashCommand implements DeletableCommand { + + private final String trickName; + private boolean deleted = false; + + /** + * Instantiates a new command for a certain trick. + */ + public CmdRunTrickSeparated(String trickName) { + super(); + this.trickName = trickName; + name = trickName; + aliases = Tricks.getTrick(trickName).map(t -> t.getNames()).orElse(new ArrayList<>()).toArray(String[]::new); + help = "Invoke the trick " + trickName; + category = new Category("Fun"); + guildOnly = true; + options = Collections.singletonList(new OptionData(OptionType.STRING, "args", "The arguments for the trick, if any").setRequired(false)); + } + + public CmdRunTrickSeparated(Trick trick) { + this(trick.getNames().get(0)); + } + + /** + * Execute. + * + * @param event the event + */ + @Override + protected void execute(final SlashCommandEvent event) { + if (!Utils.checkCommand(this, event)) { + return; + } + + Tricks.getTrick(trickName).ifPresentOrElse(trick -> event.reply(trick.getMessage(Utils.getOrEmpty(event, "args").split(" "))).setEphemeral(false).queue(), + () -> event.deferReply(true).setContent("This trick does not exist anymore!").queue()); + } + + @Override + public void delete() { + deleted = true; + } + + @Override + public void restore() { + deleted = false; + CommandModule.upsertCommand(this); + } + + @Override + public boolean isDeleted() { + return deleted; + } +} diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdTrick.java b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdTrick.java new file mode 100644 index 00000000..98087c51 --- /dev/null +++ b/src/main/java/com/mcmoddev/mmdbot/modules/commands/server/tricks/CmdTrick.java @@ -0,0 +1,63 @@ +/* + * MMDBot - https://github.com/MinecraftModDevelopment/MMDBot + * Copyright (C) 2016-2022 <MMD - MinecraftModDevelopment> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + * USA + * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html + */ +package com.mcmoddev.mmdbot.modules.commands.server.tricks; + +import com.jagrosh.jdautilities.command.SlashCommand; +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import com.mcmoddev.mmdbot.utilities.tricks.Tricks; +import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * This class is the parent of all the trick commands. + * @author matyrobbrt + */ +public final class CmdTrick extends SlashCommand { + + public CmdTrick() { + name = "trick"; + help = "Does stuff regarding tricks"; + guildOnly = true; + + final List<SlashCommand> child = new ArrayList<>(); + child.add(new CmdRunTrick()); + Tricks.getTrickTypes().entrySet().stream().map(entry -> new CmdAddTrick(entry.getKey(), entry.getValue())).forEach(child::add); + child.add(new CmdRemoveTrick()); + child.add(new CmdListTricks()); + + children = child.toArray(SlashCommand[]::new); + } + + @Override + protected void execute(final SlashCommandEvent event) { + + } + + @Override + public void onAutoComplete(final CommandAutoCompleteInteractionEvent event) { + if (Objects.equals(event.getSubcommandName(), "run")) { + children[0].onAutoComplete(event); + } + } +} diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/MiscEvents.java b/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/MiscEvents.java index d834e3df..6bb3399c 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/MiscEvents.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/MiscEvents.java @@ -76,7 +76,7 @@ public void onReady(final @NotNull ReadyEvent event) { References.STARTUP_TIME = Instant.now(); References.BOT_READY = true; - event.getJDA().updateCommands().addCommands(CommandModule.GLOBAL_CMDS).queue(); + event.getJDA().updateCommands().addCommands(CommandModule.GLOBAL_CMDS).queue($ -> {}, e -> {}); event.getJDA().getGuilds().forEach(guild -> guild.updateCommands().addCommands(CommandModule.GUILD_CMDS .computeIfAbsent(guild.getIdLong(), k -> new ArrayList<>())).queue(commands -> { // TODO privileges should work diff --git a/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/ThreadChannelCreatorEvents.java b/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/ThreadChannelCreatorEvents.java index ab1ec95c..b47e406b 100644 --- a/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/ThreadChannelCreatorEvents.java +++ b/src/main/java/com/mcmoddev/mmdbot/modules/logging/misc/ThreadChannelCreatorEvents.java @@ -57,7 +57,8 @@ private void createThread(final MessageReceivedEvent event, final Type threadTyp thread.sendMessageEmbeds(new EmbedBuilder().setTitle("%s discussion thread".formatted(Utils.uppercaseFirstLetter(threadTypeStr))) .setColor(Color.CYAN).setDescription(""" **This thread is intended for discussing %s's %s. The %s:** - %s""".formatted(author.getAsMention(), threadTypeStr, threadTypeStr, event.getMessage().getContentRaw())).build()).queue(); + %s""".formatted(author.getAsMention(), threadTypeStr, threadTypeStr, event.getMessage().getContentRaw())).build()) + .queue(msg -> msg.pin().queue()); }); }); } diff --git a/src/main/java/com/mcmoddev/mmdbot/utilities/tricks/Tricks.java b/src/main/java/com/mcmoddev/mmdbot/utilities/tricks/Tricks.java index 4b3d48f0..54510074 100644 --- a/src/main/java/com/mcmoddev/mmdbot/utilities/tricks/Tricks.java +++ b/src/main/java/com/mcmoddev/mmdbot/utilities/tricks/Tricks.java @@ -30,7 +30,7 @@ import com.mcmoddev.mmdbot.MMDBot; import com.mcmoddev.mmdbot.modules.commands.CommandModule; import com.mcmoddev.mmdbot.modules.commands.server.DeletableCommand; -import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdRunTrick; +import com.mcmoddev.mmdbot.modules.commands.server.tricks.CmdRunTrickSeparated; import com.mcmoddev.mmdbot.utilities.tricks.Trick.TrickType; import org.jetbrains.annotations.Nullable; @@ -148,7 +148,7 @@ public static Map<String, Trick.TrickType<?>> getTrickTypes() { public static void addTrick(final Trick trick) { getTricks().add(trick); write(); - addOrRestoreCommand(trick); + // addOrRestoreCommand(trick); } /** @@ -159,7 +159,7 @@ public static void addTrick(final Trick trick) { public static void removeTrick(final Trick trick) { getTricks().remove(trick); write(); - CommandModule.removeCommand(trick.getNames().get(0), true); + // CommandModule.removeCommand(trick.getNames().get(0), true); } public static void replaceTrick(final Trick oldTrick, final Trick newTrick) { @@ -196,7 +196,7 @@ private static void addOrRestoreCommand(final Trick trick) { .findFirst().ifPresentOrElse( DeletableCommand::restore, () -> { - final var cmd = new CmdRunTrick(trick); + final var cmd = new CmdRunTrickSeparated(trick); CommandModule.getCommandClient().addSlashCommand(cmd); CommandModule.upsertCommand(cmd); }); diff --git a/src/main/resources/default-config.toml b/src/main/resources/default-config.toml index 759fa692..0bd03bc6 100644 --- a/src/main/resources/default-config.toml +++ b/src/main/resources/default-config.toml @@ -20,6 +20,13 @@ # Event logging will be filtered to only receive from this guild guildId = "" + [bot.activity] + # The type of activity the bot has. + type = "PLAYING" + + # The name of the activity the bot has. + name = "Type /help" + # Configuration of aliases # Aliases may be used as substitutes in entries that require snowflake IDs, such as channel blocklists # This allows for more human-readable configuration of other settings