From c45b79b37dd842df943faf7d023556cfbcb922ab Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 21 Apr 2021 22:00:36 +0200 Subject: [PATCH 001/158] =?UTF-8?q?=E2=9E=95=20Added=20Account=20saving/lo?= =?UTF-8?q?ading=20framework=20for=20version=200.9.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/accounts/Account.java | 55 ++++++++++++++ .../github/mafelp/accounts/AccountLoader.java | 64 ++++++++++++++++ .../mafelp/accounts/AccountManager.java | 75 +++++++++++++++++++ 3 files changed, 194 insertions(+) create mode 100644 src/main/java/com/github/mafelp/accounts/Account.java create mode 100644 src/main/java/com/github/mafelp/accounts/AccountLoader.java create mode 100644 src/main/java/com/github/mafelp/accounts/AccountManager.java diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java new file mode 100644 index 0000000..dd221ad --- /dev/null +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -0,0 +1,55 @@ +package com.github.mafelp.accounts; + +import org.bukkit.entity.Player; +import org.javacord.api.entity.user.User; + +import java.util.UUID; + +public class Account { + private final User user; + private final long userID; + private String username; + private final String mentionTag; + + private final Player player; + private final UUID playerUUDI; + + public Account(User user, Player player) { + this.user = user; + this.userID = user.getId(); + this.username = user.getName(); + this.mentionTag = user.getMentionTag(); + + this.player = player; + this.playerUUDI = player.getUniqueId(); + } + + public User getUser() { + return user; + } + + public long getUserID() { + return userID; + } + + public String getUsername() { + return username; + } + + public Account setUsername(String username) { + this.username = username; + return this; + } + + public String getMentionTag() { + return mentionTag; + } + + public Player getPlayer() { + return player; + } + + public UUID getPlayerUUDI() { + return playerUUDI; + } +} diff --git a/src/main/java/com/github/mafelp/accounts/AccountLoader.java b/src/main/java/com/github/mafelp/accounts/AccountLoader.java new file mode 100644 index 0000000..0c239f5 --- /dev/null +++ b/src/main/java/com/github/mafelp/accounts/AccountLoader.java @@ -0,0 +1,64 @@ +package com.github.mafelp.accounts; + +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.bukkit.entity.Player; +import org.javacord.api.entity.user.User; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class AccountLoader extends Thread{ + JsonParser jsonParser = new JsonParser(); + + private static final File accountFile = new File(Settings.getConfigurationFileDirectory(), "accounts.json"); + + @Override + public void run() { + Scanner scanner; + try { + scanner = new Scanner(accountFile); + } catch (FileNotFoundException e) { + Logging.logException(e, "Configuration file could not be found. Aborting Account loading."); + return; + } + + StringBuilder fileInput = new StringBuilder(); + + while (scanner.hasNextLine()) { + fileInput.append(scanner.nextLine()); + } + + String input = fileInput.toString(); + + JsonElement jsonInput = jsonParser.parse(input); + JsonArray accounts = jsonInput.getAsJsonArray(); + + List linkedAccounts = new ArrayList<>(); + + for (JsonElement jsonElement : accounts) { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + + final long discordID = jsonObject.get("discordID").getAsLong(); + final String username = jsonObject.get("username").getAsString(); + final String minecraftUUID = jsonObject.get("minecraftUUID").getAsString(); + + final Player player = Settings.minecraftServer.getPlayer(minecraftUUID); + final User user = Settings.discordApi.getUserById(discordID).join(); + + if (player == null || user == null) + continue; + + linkedAccounts.add(new Account(user, player).setUsername(username)); + } + + AccountManager.setLinkedAccounts(linkedAccounts); + } +} diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java new file mode 100644 index 0000000..43df2ac --- /dev/null +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -0,0 +1,75 @@ +package com.github.mafelp.accounts; + +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.bukkit.entity.Player; +import org.javacord.api.entity.user.User; + +import java.io.*; +import java.util.*; + +public class AccountManager { + private static List linkedAccounts = new ArrayList<>(); + + private static final File accountFile = new File(Settings.getConfigurationFileDirectory(), "accounts.json"); + + private static final JsonParser jsonParser= new JsonParser(); + + public static void createAccountsFile() throws IOException { + if (accountFile.exists()) { + Logging.info("accounts file " + accountFile.getAbsolutePath() + " already exists. Not overwriting it."); + } else { + boolean fileCreationSuccess = accountFile.createNewFile(); + Logging.info("Accounts file creation... Success: " + fileCreationSuccess); + + if (!fileCreationSuccess) + return; + + PrintStream printStream = new PrintStream(new FileOutputStream(accountFile)); + printStream.println("[]"); + printStream.close(); + } + } + + public static void saveAccounts() throws FileNotFoundException { + JsonArray accounts = new JsonArray(); + + for (Account account: linkedAccounts) { + JsonObject accountInfo = new JsonObject(); + + accountInfo.addProperty("discordID", account.getUserID()); + accountInfo.addProperty("username", account.getUsername()); + accountInfo.addProperty("discordMentionTag", account.getMentionTag()); + + accountInfo.addProperty("minecraftUUID", account.getPlayerUUDI().toString()); + + accounts.add(accountInfo); + } + + PrintStream printStream = new PrintStream(new FileOutputStream(accountFile)); + printStream.print(accounts); + printStream.close(); + } + + public static void loadAccounts() { + if (!accountFile.exists()) + return; + + Thread accountLoaderThread = new AccountLoader(); + accountLoaderThread.setName("AccountLoader"); + accountLoaderThread.start(); + } + + public static List getLinkedAccounts() { + return linkedAccounts; + } + + public static List setLinkedAccounts(List set) { + linkedAccounts = set; + return linkedAccounts; + } +} From d7d6672a429aadc29f173f04d2f9f44d57e9548a Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 21 Apr 2021 22:19:23 +0200 Subject: [PATCH 002/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20for=20?= =?UTF-8?q?the=20newly=20implemented=20Accounts=20System.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/accounts/Account.java | 65 +++++++++++++++++-- .../github/mafelp/accounts/AccountLoader.java | 9 +++ .../mafelp/accounts/AccountManager.java | 39 ++++++++--- 3 files changed, 100 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index dd221ad..8cab020 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -5,15 +5,47 @@ import java.util.UUID; +/** + * The method that stores all necessary information about an account with linked discord user and + * minecraft player. + */ public class Account { + /** + * The discord user + */ private final User user; + + /** + * the discord ID of the {@link Account#user}. + */ private final long userID; + + /** + * The name of the account. The default is the discord name of the {@link Account#user}. + */ private String username; + + /** + * The tag used to mention a Discord {@link User} in a discord message. + */ private final String mentionTag; + /** + * The minecraft {@link Player} to link the discord {@link User} to. + */ private final Player player; - private final UUID playerUUDI; + /** + * The UUID of the minecraft {@link Account#player}. + */ + private final UUID playerUUID; + + /** + * The constructor to create an account from a minecraft {@link Account#playerUUID} and a discord + * {@link Account#userID}. + * @param user The discord {@link User} to link this account to. + * @param player The minecraft {@link Player} to link this account to. + */ public Account(User user, Player player) { this.user = user; this.userID = user.getId(); @@ -21,35 +53,58 @@ public Account(User user, Player player) { this.mentionTag = user.getMentionTag(); this.player = player; - this.playerUUDI = player.getUniqueId(); + this.playerUUID = player.getUniqueId(); } + /** + * The getter for the {@link Account#user}. + * @return The {@link Account#user} field. + */ public User getUser() { return user; } + /** + * The getter for the {@link Account#userID}. + * @return The {@link Account#userID} field. + */ public long getUserID() { return userID; } + /** + * The getter for the {@link Account#username}. + * @return The {@link Account#username} field. + */ public String getUsername() { return username; } + /** + * The setter for the {@link Account#username}. + * @return The {@link Account#username} field. + */ public Account setUsername(String username) { this.username = username; return this; } - public String getMentionTag() { return mentionTag; } + /** + * The getter for the {@link Account#player}. + * @return The {@link Account#player} field. + */ public Player getPlayer() { return player; } - public UUID getPlayerUUDI() { - return playerUUDI; + /** + * The getter for the {@link Account#playerUUID}. + * @return The {@link Account#playerUUID} field. + */ + public UUID getPlayerUUID() { + return playerUUID; } } diff --git a/src/main/java/com/github/mafelp/accounts/AccountLoader.java b/src/main/java/com/github/mafelp/accounts/AccountLoader.java index 0c239f5..a810173 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountLoader.java +++ b/src/main/java/com/github/mafelp/accounts/AccountLoader.java @@ -15,11 +15,20 @@ import java.util.List; import java.util.Scanner; +/** + * The thread, which loads the accounts into AccountManager.linkedAccounts. + */ public class AccountLoader extends Thread{ JsonParser jsonParser = new JsonParser(); + /** + * The file in which all the accounts are stored. + */ private static final File accountFile = new File(Settings.getConfigurationFileDirectory(), "accounts.json"); + /** + * The method that runs the loading in another thread. + */ @Override public void run() { Scanner scanner; diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 43df2ac..3f0be76 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -3,22 +3,29 @@ import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.bukkit.entity.Player; -import org.javacord.api.entity.user.User; import java.io.*; import java.util.*; +/** + * Manager for creating, saving and loading linked discord and minecraft accounts. + */ public class AccountManager { + /** + * The list of all linked accounts + */ private static List linkedAccounts = new ArrayList<>(); + /** + * The file in which the accounts are saved. + */ private static final File accountFile = new File(Settings.getConfigurationFileDirectory(), "accounts.json"); - private static final JsonParser jsonParser= new JsonParser(); - + /** + * The method to create an account file. + * @throws IOException the exception thrown, when the file could not be created, due to an error. + */ public static void createAccountsFile() throws IOException { if (accountFile.exists()) { Logging.info("accounts file " + accountFile.getAbsolutePath() + " already exists. Not overwriting it."); @@ -35,6 +42,10 @@ public static void createAccountsFile() throws IOException { } } + /** + * The method that saves linkedAccounts to a JSON file. + * @throws FileNotFoundException the exception thrown, when the file does not exists, we try to write to. + */ public static void saveAccounts() throws FileNotFoundException { JsonArray accounts = new JsonArray(); @@ -45,7 +56,7 @@ public static void saveAccounts() throws FileNotFoundException { accountInfo.addProperty("username", account.getUsername()); accountInfo.addProperty("discordMentionTag", account.getMentionTag()); - accountInfo.addProperty("minecraftUUID", account.getPlayerUUDI().toString()); + accountInfo.addProperty("minecraftUUID", account.getPlayerUUID().toString()); accounts.add(accountInfo); } @@ -55,6 +66,9 @@ public static void saveAccounts() throws FileNotFoundException { printStream.close(); } + /** + * The method that handles starting of the thread, which should load the accounts in. + */ public static void loadAccounts() { if (!accountFile.exists()) return; @@ -64,11 +78,20 @@ public static void loadAccounts() { accountLoaderThread.start(); } + /** + * The getter for the list of Linked Accounts. + * @return The linked Accounts list, currently used. + */ public static List getLinkedAccounts() { return linkedAccounts; } - public static List setLinkedAccounts(List set) { + /** + * The setter for the list of Linked Accounts. This should only be used by this package! + * @param set The List to set the linked accounts to. + * @return the list, this method has set, aka. the input list. + */ + protected static List setLinkedAccounts(List set) { linkedAccounts = set; return linkedAccounts; } From b2a2b1217147c8d5c4170c34cbd25d5caad5014a Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 21 Apr 2021 22:25:08 +0200 Subject: [PATCH 003/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20for=20?= =?UTF-8?q?the=20newly=20implemented=20Accounts=20System.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/accounts/Account.java | 6 ++++++ src/main/java/com/github/mafelp/accounts/AccountLoader.java | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index 8cab020..e907a58 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -82,12 +82,18 @@ public String getUsername() { /** * The setter for the {@link Account#username}. + * @param username the username to set. * @return The {@link Account#username} field. */ public Account setUsername(String username) { this.username = username; return this; } + + /** + * The getter for the {@link Account#mentionTag}. + * @return The {@link Account#mentionTag} field. + */ public String getMentionTag() { return mentionTag; } diff --git a/src/main/java/com/github/mafelp/accounts/AccountLoader.java b/src/main/java/com/github/mafelp/accounts/AccountLoader.java index a810173..edb9333 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountLoader.java +++ b/src/main/java/com/github/mafelp/accounts/AccountLoader.java @@ -19,7 +19,10 @@ * The thread, which loads the accounts into AccountManager.linkedAccounts. */ public class AccountLoader extends Thread{ - JsonParser jsonParser = new JsonParser(); + /** + * The Json Parser used to parse Json from the Accounts File. + */ + private static final JsonParser jsonParser = new JsonParser(); /** * The file in which all the accounts are stored. From 5905c5c7f14222f59c514091875a00b84708ac76 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 22 Apr 2021 14:12:00 +0200 Subject: [PATCH 004/158] =?UTF-8?q?=E2=9E=95=20Added=20loading=20of=20acco?= =?UTF-8?q?unts=20to=20the=20startup=20routine.=20=E2=9E=95=20Added=20savi?= =?UTF-8?q?ng=20of=20the=20current=20state=20of=20the=20accounts=20on=20sh?= =?UTF-8?q?utdown.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/accounts/AccountLoader.java | 8 ++++++ .../mafelp/accounts/AccountManager.java | 14 ++++++++-- .../com/github/mafelp/minecraft/Main.java | 28 +++++++++++++++---- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/AccountLoader.java b/src/main/java/com/github/mafelp/accounts/AccountLoader.java index edb9333..fbde71d 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountLoader.java +++ b/src/main/java/com/github/mafelp/accounts/AccountLoader.java @@ -42,6 +42,8 @@ public void run() { return; } + Logging.debug("Start: Reading Accounts file in."); + StringBuilder fileInput = new StringBuilder(); while (scanner.hasNextLine()) { @@ -50,12 +52,16 @@ public void run() { String input = fileInput.toString(); + Logging.debug("Trying to parse the accounts file input..."); + JsonElement jsonInput = jsonParser.parse(input); JsonArray accounts = jsonInput.getAsJsonArray(); List linkedAccounts = new ArrayList<>(); for (JsonElement jsonElement : accounts) { + Logging.debug("In Accounts parsing loop."); + JsonObject jsonObject = jsonElement.getAsJsonObject(); final long discordID = jsonObject.get("discordID").getAsLong(); @@ -71,6 +77,8 @@ public void run() { linkedAccounts.add(new Account(user, player).setUsername(username)); } + Logging.debug("Done parsing accounts. Setting the list."); + AccountManager.setLinkedAccounts(linkedAccounts); } } diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 3f0be76..4b801bb 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -69,9 +69,9 @@ public static void saveAccounts() throws FileNotFoundException { /** * The method that handles starting of the thread, which should load the accounts in. */ - public static void loadAccounts() { + public static void loadAccounts() throws IOException{ if (!accountFile.exists()) - return; + createAccountsFile(); Thread accountLoaderThread = new AccountLoader(); accountLoaderThread.setName("AccountLoader"); @@ -95,4 +95,14 @@ protected static List setLinkedAccounts(List set) { linkedAccounts = set; return linkedAccounts; } + + /** + * Adds an Account to the list of linked accounts. + * @param account The account to add + * @return the list of all linked Accounts. + */ + public static List addAccount (Account account) { + linkedAccounts.add(account); + return linkedAccounts; + } } diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 1feb0df..88b0b0a 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -1,5 +1,6 @@ package com.github.mafelp.minecraft; +import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.utils.CheckPermission; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Permissions; @@ -15,6 +16,8 @@ import static com.github.mafelp.utils.Logging.debug; import static com.github.mafelp.utils.Settings.prefix; +import java.io.FileNotFoundException; +import java.io.IOException; import java.util.Objects; /** @@ -29,12 +32,12 @@ public final class Main extends JavaPlugin { */ @Override public void onEnable() { - // Logs greeting and version to the console - Bukkit.getLogger().fine("Plugin MCDC version " + Settings.version + " is being loaded..."); - // Setting minecraftServer for use in other methods that are not in a plugin class. Settings.minecraftServer = this.getServer(); + // Logs greeting and version to the console + Logging.info("Plugin MCDC version " + Settings.version + " is being loaded..."); + // Initializing settings and loading (default) configuration for further use. Settings.init(); @@ -48,6 +51,13 @@ public void onEnable() { Thread discordInitThread = new DiscordMain(); discordInitThread.setName("Initializing the Discord instance."); discordInitThread.start(); + + // Loads all the Accounts to memory + try { + AccountManager.loadAccounts(); + } catch (IOException e) { + Logging.logIOException(e, "Could not load the Accounts in. The Account file is not present and it could not be created."); + } } /** @@ -56,14 +66,22 @@ public void onEnable() { @Override public void onDisable() { // Print thank you message to the console - Bukkit.getLogger().fine(prefix + "Plugin MCDC version " + Settings.version + " is being unloaded..."); - Bukkit.getLogger().fine(prefix + "Thanks for using it!"); + Logging.info("Plugin MCDC version " + Settings.version + " is being unloaded..."); + Logging.info("Thanks for using it!"); // Safely shut down the Discord bot instance DiscordMain.shutdown(); // Save the configuration Settings.saveConfiguration(); + + // Saves the current state of the accounts to the file. + try { + AccountManager.createAccountsFile(); + AccountManager.saveAccounts(); + } catch (IOException e) { + Logging.logIOException(e, "Error saving the Accounts file. ALL LINKS WILL BE LOST!"); + } } /** From aa546f7ee70df9cbaec4cb957f954bc43cc4f219 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 22 Apr 2021 14:14:25 +0200 Subject: [PATCH 005/158] =?UTF-8?q?=E2=9E=95=20Started=20the=20linking=20o?= =?UTF-8?q?f=20accounts,=20as=20requested=20in=20#33?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/accounts/MinecraftLinker.java | 47 +++++++++++++++++++ .../mafelp/minecraft/commands/Link.java | 33 +++++++++++-- 2 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/github/mafelp/accounts/MinecraftLinker.java diff --git a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java new file mode 100644 index 0000000..b2e6b1c --- /dev/null +++ b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java @@ -0,0 +1,47 @@ +package com.github.mafelp.accounts; + +import org.bukkit.entity.Player; +import org.javacord.api.entity.user.User; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +public class MinecraftLinker { + public static Map linkableAccounts = new HashMap<>(); + + public static int getLinkToken(Player player) { + if (linkableAccounts.containsKey(player)) + return linkableAccounts.get(player); + else { + int linkID = randomLinkToken(); + linkableAccounts.put(player, linkID); + return linkID; + } + } + + public static int randomLinkToken() { + Random random = new Random(); + int r; + do { + r = random.nextInt(899_999) + 100_000; + } while (linkableAccounts.containsValue(r)); + + return r; + } + + public static Optional linkToDiscord(User user, int linkID) { + for (Player p: linkableAccounts.keySet()) { + if (linkableAccounts.get(p) == linkID) { + Account account = new Account(user, p); + + AccountManager.addAccount(account); + + return Optional.of(account); + } + } + + return Optional.empty(); + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index d39ada5..0b41370 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -1,9 +1,13 @@ package com.github.mafelp.minecraft.commands; +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.DiscordLinker; +import com.github.mafelp.accounts.MinecraftLinker; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import static com.github.mafelp.utils.Settings.prefix; @@ -28,7 +32,30 @@ public boolean onCommand(CommandSender sender, @NotNull Command command, @NotNul // Sending the player a message that this command is currently not available sender.sendMessage(prefix + ChatColor.RED + "This command is currently not available!"); - // returning a successful command execution - return true; + if (sender instanceof Player) { + Player player = ((Player) sender).getPlayer(); + + if (args == null || args[0] == null) { + MinecraftLinker.getLinkToken(player); + + return true; + } + + try { + final int linkID = Integer.parseUnsignedInt(args[0]); + + // Account linkedAccount = DiscordLinker.linkToMinecraft(player, linkID); + // sender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.getUsername()); + + return true; + } catch (NumberFormatException exception) { + sender.sendMessage(prefix + ChatColor.RED + "Error parsing your link Token! Please try again."); + return false; + } + + } else { + sender.sendMessage(prefix + ChatColor.RED + "This command can only be executed as a Player!"); + return true; + } } -} \ No newline at end of file +} From bc7b0713612d49a3c4a7f50ef31176797967868e Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 22 Apr 2021 14:23:56 +0200 Subject: [PATCH 006/158] =?UTF-8?q?=E2=9E=95=20Added=20a=20DiscordLinker?= =?UTF-8?q?=20class=20that=20handles=20linking=20from=20Discord=20to=20Min?= =?UTF-8?q?ecraft.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/accounts/DiscordLinker.java | 47 +++++++++++++++++++ .../mafelp/minecraft/commands/Link.java | 7 +-- 2 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/github/mafelp/accounts/DiscordLinker.java diff --git a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java new file mode 100644 index 0000000..69bf099 --- /dev/null +++ b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java @@ -0,0 +1,47 @@ +package com.github.mafelp.accounts; + +import org.bukkit.entity.Player; +import org.javacord.api.entity.user.User; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +public class DiscordLinker { + public static Map linkableAccounts = new HashMap<>(); + + public static int getLinkToken(User user) { + if (linkableAccounts.containsKey(user)) + return linkableAccounts.get(user); + else { + int linkID = randomLinkToken(); + linkableAccounts.put(user, linkID); + return linkID; + } + } + + public static Optional linkToDiscord(Player player, int linkID) { + for (User u: linkableAccounts.keySet()) { + if (linkableAccounts.get(u) == linkID) { + Account account = new Account(u, player); + + AccountManager.addAccount(account); + + return Optional.of(account); + } + } + + return Optional.empty(); + } + + public static int randomLinkToken() { + Random random = new Random(); + int r; + do { + r = random.nextInt(899_999) + 100_000; + } while (linkableAccounts.containsValue(r)); + + return r; + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index 0b41370..a814c9a 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -1,8 +1,7 @@ package com.github.mafelp.minecraft.commands; -import com.github.mafelp.accounts.Account; -import com.github.mafelp.accounts.DiscordLinker; import com.github.mafelp.accounts.MinecraftLinker; +import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -36,7 +35,9 @@ public boolean onCommand(CommandSender sender, @NotNull Command command, @NotNul Player player = ((Player) sender).getPlayer(); if (args == null || args[0] == null) { - MinecraftLinker.getLinkToken(player); + int discordLinkToken = MinecraftLinker.getLinkToken(player); + + sender.sendMessage(prefix + ChatColor.RESET + "You link token is: " + ChatColor.GRAY + discordLinkToken + ChatColor.RESET + ". Use the command \"" + ChatColor.GRAY + Settings.discordCommandPrefix +"link " + discordLinkToken + ChatColor.RESET + "\" to link this minecraft account ot your discord account."); return true; } From 0487be82470ec2b32025bbb61af1340f2ba915b1 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 22 Apr 2021 20:40:09 +0200 Subject: [PATCH 007/158] =?UTF-8?q?=E2=9E=95=20Added=20account=20linking,?= =?UTF-8?q?=20as=20requested=20in=20#33?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/accounts/DiscordLinker.java | 2 +- .../github/mafelp/discord/DiscordMain.java | 2 + .../mafelp/discord/commands/LinkListener.java | 125 ++++++++++++++++++ .../mafelp/minecraft/commands/Link.java | 35 +++-- .../java/com/github/mafelp/utils/Command.java | 16 +++ 5 files changed, 169 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/github/mafelp/discord/commands/LinkListener.java diff --git a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java index 69bf099..55fdd27 100644 --- a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java +++ b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java @@ -21,7 +21,7 @@ public static int getLinkToken(User user) { } } - public static Optional linkToDiscord(Player player, int linkID) { + public static Optional linkToMinecraft(Player player, int linkID) { for (User u: linkableAccounts.keySet()) { if (linkableAccounts.get(u) == linkID) { Account account = new Account(u, player); diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 8f3270d..0faf27a 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -1,6 +1,7 @@ package com.github.mafelp.discord; import com.github.mafelp.discord.commands.CreateRoleListener; +import com.github.mafelp.discord.commands.LinkListener; import com.github.mafelp.discord.commands.SetupListener; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; @@ -65,6 +66,7 @@ public void run() { .addListener(CreateChannelListener::new) .addListener(CreateRoleListener::new) .addListener(SetupListener::new) + .addListener(LinkListener::new) // log the bot in and join the servers .login().join(); // TODO Add: activity diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java new file mode 100644 index 0000000..f7b2884 --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -0,0 +1,125 @@ +package com.github.mafelp.discord.commands; + +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.DiscordLinker; +import com.github.mafelp.accounts.MinecraftLinker; +import com.github.mafelp.utils.Command; +import com.github.mafelp.utils.CommandParser; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; +import com.github.mafelp.utils.exceptions.CommandNotFinishedException; +import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.message.MessageCreateEvent; +import org.javacord.api.listener.message.MessageCreateListener; + +import java.awt.*; +import java.util.Optional; + +import static com.github.mafelp.utils.Settings.discordCommandPrefix; + +public class LinkListener implements MessageCreateListener { + @Override + public void onMessageCreate(MessageCreateEvent event) { + // If the message is sent by the bot, return + if (event.getMessageAuthor().isYourself()) { + return; + } + + // If message does not start with the command prefix, return + // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || + // event.getReadableMessageContent() == null) + // return; + + // Gets the content of the message as strings (prints it, if debug is enabled) + String content = event.getReadableMessageContent(); + + Command command; + + try { + command = CommandParser.parseFromString(content); + } catch (CommandNotFinishedException | NoCommandGivenException e) { + // Logging.logException(e, "Error parsing the command from the string..."); + return; + } + + if (!command.getCommand().equalsIgnoreCase(Settings.discordCommandPrefix + "link")) { + // Logging.debug("Not the link command: \"" + command.getCommand() + "\" != \"" + discordCommandPrefix + "link" + "\""); + return; + } + + // Tries to parse the message author into a user. If this fails, don't execute this command. + if (event.getMessageAuthor().asUser().isEmpty()) { + Logging.debug("Could not parse user, while trying to execute link command. Aborting..."); + event.getMessage().reply( + new EmbedBuilder() + .setTitle("Error!") + .setDescription("Could not parse the sender of this message into a discord user. We therefore cannot execute the command \"link\", as requested. See https://mafelp.github.io/MCDC/errors/ for more information.") + .setColor(Color.RED) + .setAuthor(Settings.discordApi.getYourself()) + ); + + return; + } + + Logging.debug("Executing link command for user " + event.getMessageAuthor().asUser().get().getName()); + + // help message for wrong usage + EmbedBuilder helpMessage = new EmbedBuilder() + .setAuthor(event.getMessageAuthor()) + .setTitle("Error") + .addField("Usage", discordCommandPrefix + "link []") + .addField("Functionality", "Links your discord account to a minecraft account..") + .setColor(new Color(0xFFB500)) + .setFooter("Help message for command \"link\"") + ; + + // Embed sent on successful account linking + EmbedBuilder successEmbed = new EmbedBuilder() + .setAuthor(event.getMessageAuthor()) + .setColor(Color.GREEN) + .setTitle("Success!") + .setFooter("More information on linking here: https://mafelp.github.io/MCDC/linking") + ; + + if (command.getStringArgument(1).isPresent()) { + Logging.debug("User \"" + event.getMessageAuthor().getDisplayName() + "\" used the command 'link' wrong. Sending help embed..."); + event.getMessage().reply(helpMessage); + return; + } + + if (command.getIntegerArgument(0).isEmpty()) { + Logging.debug("No Integer Argument given in link command. Sending LinkTokenEmbed..."); + sendLinkToken(event.getMessageAuthor().asUser().get()); + } else { + Logging.debug("LinkToken found. Checking it..."); + Optional linkedAccount = MinecraftLinker.linkToDiscord(event.getMessageAuthor().asUser().get(), command.getIntegerArgument(0).get()); + + if (linkedAccount.isEmpty()) { + Logging.debug("LinkToken is invalid. Sending new Link Token"); + sendLinkToken(event.getMessageAuthor().asUser().get()); + return; + } + + Logging.debug("LinkToken valid. sending success Embed."); + event.getMessageAuthor().asUser().get().sendMessage(successEmbed.addInlineField("Minecraft Account", linkedAccount.get().getPlayer().getDisplayName()) + .addInlineField("Discord Account", linkedAccount.get().getUsername() + " : " + linkedAccount.get().getMentionTag())); + } + } + + private void sendLinkToken(final User user) { + int minecraftLinkToken = DiscordLinker.getLinkToken(user); + + EmbedBuilder reply = new EmbedBuilder() + .setColor(Color.MAGENTA) + .setTitle("Your Link Token") + .setAuthor(user) + .addField("Token","" + minecraftLinkToken) + .addField("Usage", "To finish linking of your accounts, please log into the minecraft server, and use \"/link " + minecraftLinkToken + "\" to link this discord account to your minecraft account.") + .setFooter("MCDC made by MaFeLP (https://mafelp.github.io/MCDC/") + ; + + user.sendMessage(reply); + } +} \ No newline at end of file diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index a814c9a..dbb0e98 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -1,5 +1,7 @@ package com.github.mafelp.minecraft.commands; +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.DiscordLinker; import com.github.mafelp.accounts.MinecraftLinker; import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; @@ -9,6 +11,8 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.Optional; + import static com.github.mafelp.utils.Settings.prefix; /** @@ -27,26 +31,31 @@ public class Link implements CommandExecutor { * @return command success */ @Override - public boolean onCommand(CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - // Sending the player a message that this command is currently not available - sender.sendMessage(prefix + ChatColor.RED + "This command is currently not available!"); - + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (sender instanceof Player) { Player player = ((Player) sender).getPlayer(); - if (args == null || args[0] == null) { - int discordLinkToken = MinecraftLinker.getLinkToken(player); - - sender.sendMessage(prefix + ChatColor.RESET + "You link token is: " + ChatColor.GRAY + discordLinkToken + ChatColor.RESET + ". Use the command \"" + ChatColor.GRAY + Settings.discordCommandPrefix +"link " + discordLinkToken + ChatColor.RESET + "\" to link this minecraft account ot your discord account."); + if (args == null) { + sendLinkToken(player); + return true; + } + if (args.length < 1) { + sendLinkToken(player); return true; } try { final int linkID = Integer.parseUnsignedInt(args[0]); - // Account linkedAccount = DiscordLinker.linkToMinecraft(player, linkID); - // sender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.getUsername()); + Optional linkedAccount = DiscordLinker.linkToMinecraft(player, linkID); + + if (linkedAccount.isEmpty()) { + sendLinkToken(player); + return true; + } + + sender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.get().getUsername()); return true; } catch (NumberFormatException exception) { @@ -59,4 +68,10 @@ public boolean onCommand(CommandSender sender, @NotNull Command command, @NotNul return true; } } + + private void sendLinkToken(Player player) { + int discordLinkToken = MinecraftLinker.getLinkToken(player); + + player.sendMessage(prefix + ChatColor.RESET + "You link token is: " + ChatColor.GRAY + discordLinkToken + ChatColor.RESET + ". Use the command \"" + ChatColor.GRAY + Settings.discordCommandPrefix + "link " + discordLinkToken + ChatColor.RESET + "\" to link this minecraft account ot your discord account."); + } } diff --git a/src/main/java/com/github/mafelp/utils/Command.java b/src/main/java/com/github/mafelp/utils/Command.java index 2e1a8ec..a964389 100644 --- a/src/main/java/com/github/mafelp/utils/Command.java +++ b/src/main/java/com/github/mafelp/utils/Command.java @@ -73,6 +73,22 @@ public Optional getLongArgument(int index) { return Optional.empty(); } + /** + * Gets the argument at the index as an int. + * @param index index of the argument. + * @return the value. + */ + public Optional getIntegerArgument(int index) { + if (argumentIsAvailable(index)) + // Prevents an abort when not a long was passed. + try { + return Optional.of(Integer.parseInt(arguments[index])); + } catch (NumberFormatException numberFormatException) { + return Optional.empty(); + } + return Optional.empty(); + } + /** * Gets the argument array. * @return the arguments as a string array From 9a770a36a4b6122cba6ee4a912e5f811d811d0d5 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 22 Apr 2021 21:35:12 +0200 Subject: [PATCH 008/158] =?UTF-8?q?=E2=9E=95=20Added=20account=20saving=20?= =?UTF-8?q?to=20the=20accounts.json=20file.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/accounts/Account.java | 9 ++++--- .../github/mafelp/accounts/AccountLoader.java | 21 ++++++++++----- .../github/mafelp/discord/DiscordMain.java | 26 +++++++++++++++++-- .../mafelp/discord/commands/LinkListener.java | 2 +- .../com/github/mafelp/minecraft/Main.java | 8 +----- 5 files changed, 45 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index e907a58..d322bae 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -1,5 +1,6 @@ package com.github.mafelp.accounts; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.javacord.api.entity.user.User; @@ -31,9 +32,9 @@ public class Account { private final String mentionTag; /** - * The minecraft {@link Player} to link the discord {@link User} to. + * The minecraft {@link OfflinePlayer} to link the discord {@link User} to. */ - private final Player player; + private final OfflinePlayer player; /** * The UUID of the minecraft {@link Account#player}. @@ -46,7 +47,7 @@ public class Account { * @param user The discord {@link User} to link this account to. * @param player The minecraft {@link Player} to link this account to. */ - public Account(User user, Player player) { + public Account(User user, OfflinePlayer player) { this.user = user; this.userID = user.getId(); this.username = user.getName(); @@ -102,7 +103,7 @@ public String getMentionTag() { * The getter for the {@link Account#player}. * @return The {@link Account#player} field. */ - public Player getPlayer() { + public OfflinePlayer getPlayer() { return player; } diff --git a/src/main/java/com/github/mafelp/accounts/AccountLoader.java b/src/main/java/com/github/mafelp/accounts/AccountLoader.java index fbde71d..a03d568 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountLoader.java +++ b/src/main/java/com/github/mafelp/accounts/AccountLoader.java @@ -6,14 +6,13 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.javacord.api.entity.user.User; import java.io.File; import java.io.FileNotFoundException; -import java.util.ArrayList; -import java.util.List; -import java.util.Scanner; +import java.util.*; /** * The thread, which loads the accounts into AccountManager.linkedAccounts. @@ -52,6 +51,7 @@ public void run() { String input = fileInput.toString(); + Logging.debug("accounts.json File input: " + input); Logging.debug("Trying to parse the accounts file input..."); JsonElement jsonInput = jsonParser.parse(input); @@ -66,18 +66,25 @@ public void run() { final long discordID = jsonObject.get("discordID").getAsLong(); final String username = jsonObject.get("username").getAsString(); - final String minecraftUUID = jsonObject.get("minecraftUUID").getAsString(); + final UUID minecraftUUID = UUID.fromString(jsonObject.get("minecraftUUID").getAsString()); - final Player player = Settings.minecraftServer.getPlayer(minecraftUUID); + Logging.debug("Getting player value for player with UUID: " + minecraftUUID); + final OfflinePlayer player = Settings.minecraftServer.getOfflinePlayer(minecraftUUID); + + Logging.debug("Getting Discord User from ID: " + discordID); final User user = Settings.discordApi.getUserById(discordID).join(); - if (player == null || user == null) + if (user == null) { + Logging.info("discord user not found. ignoring."); continue; + } + + Logging.debug("Adding user " + username + " to the list of accounts."); linkedAccounts.add(new Account(user, player).setUsername(username)); } - Logging.debug("Done parsing accounts. Setting the list."); + Logging.debug("Done parsing accounts. Setting the list to: " + Arrays.toString(linkedAccounts.toArray())); AccountManager.setLinkedAccounts(linkedAccounts); } diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 0faf27a..00629fd 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -1,5 +1,6 @@ package com.github.mafelp.discord; +import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.discord.commands.CreateRoleListener; import com.github.mafelp.discord.commands.LinkListener; import com.github.mafelp.discord.commands.SetupListener; @@ -12,6 +13,7 @@ import org.javacord.api.entity.permission.Permissions; import org.javacord.api.entity.permission.PermissionsBuilder; +import java.io.IOException; import java.util.concurrent.CompletionException; import static com.github.mafelp.utils.Settings.discordApi; @@ -21,6 +23,16 @@ * The class that handles initiation and destruction of the discord bot instance(s) */ public class DiscordMain extends Thread { + private final boolean loadAccounts; + + public DiscordMain(boolean loadAccounts) { + this.loadAccounts = loadAccounts; + } + + public DiscordMain() { + this.loadAccounts = false; + } + /** * Method used to create the bot instance and log it in */ @@ -69,15 +81,25 @@ public void run() { .addListener(LinkListener::new) // log the bot in and join the servers .login().join(); - // TODO Add: activity + // TODO Add: activity Logging.info(ChatColor.GREEN + "Successfully started the discord instance!"); Logging.info(ChatColor.RESET + "The bot invitation token is: " + discordApi.createBotInvite(botPermissions)); } catch (IllegalStateException | CompletionException exception) { // If the API creation fails, // log an error to the console. - Logging.logException(exception, ChatColor.RED + + Logging.logException(exception, ChatColor.RED + "An error occurred whilst trying to create the discord instance! Error: " + exception.getMessage()); + return; + } + + if (this.loadAccounts) { + // Loads all the Accounts to memory + try { + AccountManager.loadAccounts(); + } catch (IOException e) { + Logging.logIOException(e, "Could not load the Accounts in. The Account file is not present and it could not be created."); + } } } diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index f7b2884..4c5cf7e 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -103,7 +103,7 @@ public void onMessageCreate(MessageCreateEvent event) { } Logging.debug("LinkToken valid. sending success Embed."); - event.getMessageAuthor().asUser().get().sendMessage(successEmbed.addInlineField("Minecraft Account", linkedAccount.get().getPlayer().getDisplayName()) + event.getMessageAuthor().asUser().get().sendMessage(successEmbed.addInlineField("Minecraft Account", linkedAccount.get().getPlayer().getName()) .addInlineField("Discord Account", linkedAccount.get().getUsername() + " : " + linkedAccount.get().getMentionTag())); } } diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 88b0b0a..62512b6 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -48,16 +48,10 @@ public void onEnable() { commandRegistration(); // Initialize and try starting up the discord bot. - Thread discordInitThread = new DiscordMain(); + Thread discordInitThread = new DiscordMain(true); discordInitThread.setName("Initializing the Discord instance."); discordInitThread.start(); - // Loads all the Accounts to memory - try { - AccountManager.loadAccounts(); - } catch (IOException e) { - Logging.logIOException(e, "Could not load the Accounts in. The Account file is not present and it could not be created."); - } } /** From 33b4909443064e516735a55053e1fa0398c7d046 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 22 Apr 2021 22:06:59 +0200 Subject: [PATCH 009/158] =?UTF-8?q?=F0=9F=93=97=20Updated=20Javadoc=20to?= =?UTF-8?q?=20represent=20the=20newest=20Linking=20features.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/accounts/AccountManager.java | 1 + .../github/mafelp/accounts/DiscordLinker.java | 29 +++++++++++++++++-- .../mafelp/accounts/MinecraftLinker.java | 29 +++++++++++++++++-- .../github/mafelp/discord/DiscordMain.java | 10 +++++++ .../mafelp/discord/commands/LinkListener.java | 14 +++++++++ .../mafelp/minecraft/commands/Link.java | 4 +++ 6 files changed, 83 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 4b801bb..00169af 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -68,6 +68,7 @@ public static void saveAccounts() throws FileNotFoundException { /** * The method that handles starting of the thread, which should load the accounts in. + * @throws IOException The exception that is being thrown, if the accounts.json File does not exists or the {@link AccountLoader} encounters an {@link IOException}. */ public static void loadAccounts() throws IOException{ if (!accountFile.exists()) diff --git a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java index 55fdd27..f84e32a 100644 --- a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java +++ b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java @@ -8,9 +8,23 @@ import java.util.Optional; import java.util.Random; +/** + * The class that handles linking on the Discord side of things. + */ public class DiscordLinker { - public static Map linkableAccounts = new HashMap<>(); + /** + * The Map that contains as key the {@link Player} that created the link token and as the Value an {@link Integer} + * between 100,000 and 999,999. + */ + private static final Map linkableAccounts = new HashMap<>(); + /** + * Checks the {@link DiscordLinker#linkableAccounts} list, if the {@link User} already has a linking token and + * if so, it returns the token from this map. If the user does not have a token yet, it creates one and + * adds it to the {@link DiscordLinker#linkableAccounts} map, associated with the user. + * @param user The user to get the Linking Token from. + * @return The Token used to link the account in minecraft. + */ public static int getLinkToken(User user) { if (linkableAccounts.containsKey(user)) return linkableAccounts.get(user); @@ -21,6 +35,13 @@ public static int getLinkToken(User user) { } } + /** + * The method used to create a linked {@link Account} with a discord user and the linking ID of a minecraft Player. + * @param player The minecraft {@link Player} to link the discord {@link User} to. + * @param linkID The ID used for finding the correct discord {@link User}. + * @return If the ID is a valid token, it returns the newly {@link Account}, which was added to the list of accounts. + * If the ID is invalid, it returns an empty account. + */ public static Optional linkToMinecraft(Player player, int linkID) { for (User u: linkableAccounts.keySet()) { if (linkableAccounts.get(u) == linkID) { @@ -35,7 +56,11 @@ public static Optional linkToMinecraft(Player player, int linkID) { return Optional.empty(); } - public static int randomLinkToken() { + /** + * The method used to create a new Linking token, aka a {@link Random}, 6-Digit number. + * @return a random linking token. + */ + private static int randomLinkToken() { Random random = new Random(); int r; do { diff --git a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java index b2e6b1c..8f693bf 100644 --- a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java +++ b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java @@ -8,9 +8,23 @@ import java.util.Optional; import java.util.Random; +/** + * The class that handles linking on the minecraft side of things. + */ public class MinecraftLinker { - public static Map linkableAccounts = new HashMap<>(); + /** + * The Map that contains as key the {@link Player} that created the link token and as the Value an {@link Integer} + * between 100,000 and 999,999. + */ + private static final Map linkableAccounts = new HashMap<>(); + /** + * Checks the {@link MinecraftLinker#linkableAccounts} list, if the {@link Player} already has a linking token and + * if so, it returns the token from this map. If the player does not have a token yet, it creates one and + * adds it to the {@link MinecraftLinker#linkableAccounts} map, associated with the player. + * @param player The player to get the Linking Token from. + * @return The Token used to link the account in discord. + */ public static int getLinkToken(Player player) { if (linkableAccounts.containsKey(player)) return linkableAccounts.get(player); @@ -21,7 +35,11 @@ public static int getLinkToken(Player player) { } } - public static int randomLinkToken() { + /** + * The method used to create a new Linking token, aka a {@link Random}, 6-Digit number. + * @return a random linking token. + */ + private static int randomLinkToken() { Random random = new Random(); int r; do { @@ -31,6 +49,13 @@ public static int randomLinkToken() { return r; } + /** + * The method used to create a linked {@link Account} with a discord user and the linking ID of a minecraft Player. + * @param user The discord {@link User} to link the minecraft {@link Player} to. + * @param linkID The ID used for finding the correct minecraft {@link Player}. + * @return If the ID is a valid token, it returns the newly {@link Account}, which was added to the list of accounts. + * If the ID is invalid, it returns an empty account. + */ public static Optional linkToDiscord(User user, int linkID) { for (Player p: linkableAccounts.keySet()) { if (linkableAccounts.get(p) == linkID) { diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 00629fd..d95eb1a 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -23,12 +23,22 @@ * The class that handles initiation and destruction of the discord bot instance(s) */ public class DiscordMain extends Thread { + /** + * The switch that decides, if the Accounts should be loaded after the login of the Bot instance. + */ private final boolean loadAccounts; + /** + * Constructor to set the {@link DiscordMain#loadAccounts} switch. + * @param loadAccounts if the accounts should be loaded after bot startup. + */ public DiscordMain(boolean loadAccounts) { this.loadAccounts = loadAccounts; } + /** + * Constructor for normal discord instance startup. Does not load the Accounts in. + */ public DiscordMain() { this.loadAccounts = false; } diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index 4c5cf7e..2f07895 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -19,7 +19,16 @@ import static com.github.mafelp.utils.Settings.discordCommandPrefix; +/** + * The class that handles discord messages and test, if they are the link command. If so, it starts the linking process. + */ public class LinkListener implements MessageCreateListener { + /** + * The method that handles messages, that are sent, tests if they are the link command. + * If so, this method starts the linking process. + * @param event The event sent from the Discord API, containing important information about the message, + * such as the channel it has been sent to and the {@link User} who has sent it. + */ @Override public void onMessageCreate(MessageCreateEvent event) { // If the message is sent by the bot, return @@ -108,6 +117,11 @@ public void onMessageCreate(MessageCreateEvent event) { } } + /** + * This method sends the user a token, that it can use in {@link com.github.mafelp.minecraft.commands.Link} to + * links its accounts together. + * @param user The user to create the linking token from. + */ private void sendLinkToken(final User user) { int minecraftLinkToken = DiscordLinker.getLinkToken(user); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index dbb0e98..0f6176b 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -69,6 +69,10 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } } + /** + * The method that sends the link token in a nice message to the {@link Player} that executed this command. + * @param player The player to send its token to. + */ private void sendLinkToken(Player player) { int discordLinkToken = MinecraftLinker.getLinkToken(player); From 5617859e67e413a9ac88e74ed49d5e81fabee900 Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 21:07:46 +0200 Subject: [PATCH 010/158] =?UTF-8?q?=F0=9F=93=97=20Added=20more=20commentar?= =?UTF-8?q?y=20to=20better=20understand=20the=20code.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/accounts/AccountLoader.java | 7 ++++++- .../github/mafelp/accounts/AccountManager.java | 4 ++++ .../github/mafelp/accounts/DiscordLinker.java | 8 +++++++- .../mafelp/accounts/MinecraftLinker.java | 6 +++++- .../github/mafelp/discord/DiscordListener.java | 4 ---- .../com/github/mafelp/discord/DiscordMain.java | 1 - .../discord/DiscordMessageBroadcast.java | 1 - .../com/github/mafelp/discord/RoleAdmin.java | 3 +++ .../commands/CreateChannelListener.java | 11 +++++------ .../discord/commands/CreateRoleListener.java | 11 +++++++++-- .../mafelp/discord/commands/LinkListener.java | 5 ++++- .../mafelp/discord/commands/SetupListener.java | 18 ++++++++++++------ .../mafelp/minecraft/commands/Config.java | 4 +--- .../github/mafelp/minecraft/commands/Link.java | 9 +++++++-- .../mafelp/minecraft/commands/Token.java | 1 - 15 files changed, 63 insertions(+), 30 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/AccountLoader.java b/src/main/java/com/github/mafelp/accounts/AccountLoader.java index a03d568..2d048da 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountLoader.java +++ b/src/main/java/com/github/mafelp/accounts/AccountLoader.java @@ -7,7 +7,6 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; import org.javacord.api.entity.user.User; import java.io.File; @@ -33,6 +32,7 @@ public class AccountLoader extends Thread{ */ @Override public void run() { + // Loads the accounts.json file in. Scanner scanner; try { scanner = new Scanner(accountFile); @@ -41,6 +41,7 @@ public void run() { return; } + // Reads the contents of the accounts.json file Logging.debug("Start: Reading Accounts file in."); StringBuilder fileInput = new StringBuilder(); @@ -54,11 +55,14 @@ public void run() { Logging.debug("accounts.json File input: " + input); Logging.debug("Trying to parse the accounts file input..."); + // Parses the file into a JSON Object JsonElement jsonInput = jsonParser.parse(input); JsonArray accounts = jsonInput.getAsJsonArray(); List linkedAccounts = new ArrayList<>(); + // Parses all the JSON objects in the accounts array, stored in the accounts.json file + // and then adds them to the list of linked accounts. for (JsonElement jsonElement : accounts) { Logging.debug("In Accounts parsing loop."); @@ -86,6 +90,7 @@ public void run() { Logging.debug("Done parsing accounts. Setting the list to: " + Arrays.toString(linkedAccounts.toArray())); + // Sets the global list of linked accounts to the array list 'linkedAccounts' so other processes can access them. AccountManager.setLinkedAccounts(linkedAccounts); } } diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 00169af..5290e1d 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -28,8 +28,10 @@ public class AccountManager { */ public static void createAccountsFile() throws IOException { if (accountFile.exists()) { + // If the file already exists, don't do anything. Logging.info("accounts file " + accountFile.getAbsolutePath() + " already exists. Not overwriting it."); } else { + // If the file does not exist, try to create the file and set its contents to '[]' boolean fileCreationSuccess = accountFile.createNewFile(); Logging.info("Accounts file creation... Success: " + fileCreationSuccess); @@ -49,6 +51,7 @@ public static void createAccountsFile() throws IOException { public static void saveAccounts() throws FileNotFoundException { JsonArray accounts = new JsonArray(); + // Creates a JSON Array with all the accounts from the global linkedAccounts list. for (Account account: linkedAccounts) { JsonObject accountInfo = new JsonObject(); @@ -61,6 +64,7 @@ public static void saveAccounts() throws FileNotFoundException { accounts.add(accountInfo); } + // Prints the accounts array to the accounts file. PrintStream printStream = new PrintStream(new FileOutputStream(accountFile)); printStream.print(accounts); printStream.close(); diff --git a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java index f84e32a..c657deb 100644 --- a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java +++ b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java @@ -37,13 +37,17 @@ public static int getLinkToken(User user) { /** * The method used to create a linked {@link Account} with a discord user and the linking ID of a minecraft Player. + * The linkID has to be generated by {@link DiscordLinker#getLinkToken(User)}. * @param player The minecraft {@link Player} to link the discord {@link User} to. * @param linkID The ID used for finding the correct discord {@link User}. * @return If the ID is a valid token, it returns the newly {@link Account}, which was added to the list of accounts. * If the ID is invalid, it returns an empty account. */ public static Optional linkToMinecraft(Player player, int linkID) { + // Iterates over all the discord accounts for (User u: linkableAccounts.keySet()) { + // if the linkID passed in matches the id generated in the DiscordLinker#getLinkToken function, + // it would create a new Account with the player and the User and adds this account. if (linkableAccounts.get(u) == linkID) { Account account = new Account(u, player); @@ -53,11 +57,13 @@ public static Optional linkToMinecraft(Player player, int linkID) { } } + // If the linkID matches none of the ID in the linkableAccounts ID, return noting. return Optional.empty(); } /** - * The method used to create a new Linking token, aka a {@link Random}, 6-Digit number. + * The method used to create a new Linking token, aka a {@link Random}, 6-Digit number, that is not already + * in the linkableAccounts list. This prevents two users from having the same linking token. * @return a random linking token. */ private static int randomLinkToken() { diff --git a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java index 8f693bf..8ca0d90 100644 --- a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java +++ b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java @@ -36,7 +36,8 @@ public static int getLinkToken(Player player) { } /** - * The method used to create a new Linking token, aka a {@link Random}, 6-Digit number. + * The method used to create a new Linking token, aka a {@link Random}, 6-Digit number, that is not already + * in the linkableAccounts list. This prevents two users from having the same linking token. * @return a random linking token. */ private static int randomLinkToken() { @@ -57,7 +58,10 @@ private static int randomLinkToken() { * If the ID is invalid, it returns an empty account. */ public static Optional linkToDiscord(User user, int linkID) { + // Iterates over all the discord accounts for (Player p: linkableAccounts.keySet()) { + // if the linkID passed in matches the id generated in the DiscordLinker#getLinkToken function, + // it would create a new Account with the player and the User and adds this account. if (linkableAccounts.get(p) == linkID) { Account account = new Account(user, p); diff --git a/src/main/java/com/github/mafelp/discord/DiscordListener.java b/src/main/java/com/github/mafelp/discord/DiscordListener.java index 2104886..8fcf724 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordListener.java +++ b/src/main/java/com/github/mafelp/discord/DiscordListener.java @@ -44,10 +44,6 @@ public void onMessageCreate(MessageCreateEvent event) { // Send the readable content of the message into the minecraft chat // for everyone to read. - // TODO broadcast version of message WITHOUT line break to the console and messages with line breaks to the players if Settings.shortMsg == true - // Settings.minecraftServer.broadcastMessage( - // msgPrefix(event) + event.getReadableMessageContent() - //); for (Player p : Settings.minecraftServer.getOnlinePlayers()) { p.sendMessage(msgPrefix(event) + event.getReadableMessageContent()); diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index d95eb1a..5fbaea4 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -74,7 +74,6 @@ public void run() { .setAllowed(PermissionType.ADD_REACTIONS) .build(); - // TODO Change: make this function a thread / use bukkit scheduler // Log that the instance is being started Logging.info(ChatColor.DARK_GRAY + "Starting Discord Instance..."); // try to log the instance in and set it in the settings diff --git a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java index 7fce737..ac3f5e3 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java @@ -48,7 +48,6 @@ public void run() { } // create an embed for the message - //TODO Add: show head of player as author picture EmbedBuilder embed = new EmbedBuilder() // .setAuthor(messageAuthor.getDisplayName()) .setAuthor(messageAuthor.getDisplayName(), "", new Skin(messageAuthor, false).getHead(), ".png") diff --git a/src/main/java/com/github/mafelp/discord/RoleAdmin.java b/src/main/java/com/github/mafelp/discord/RoleAdmin.java index 8fba134..933b001 100644 --- a/src/main/java/com/github/mafelp/discord/RoleAdmin.java +++ b/src/main/java/com/github/mafelp/discord/RoleAdmin.java @@ -27,6 +27,7 @@ public class RoleAdmin { */ public static Role createNewRole(Server server, String name, EmbedBuilder successEmbed, ServerTextChannel successChannel) throws CompletionException { + // Set the permissions the new role should have. Permissions permissions = new PermissionsBuilder() .setAllowed(PermissionType.ADD_REACTIONS) .setDenied(PermissionType.ADMINISTRATOR) @@ -61,6 +62,7 @@ public static Role createNewRole(Server server, String name, .build() ; + // Build the Role. This throws the CompletionException Role role = new RoleBuilder(server) .setColor(new Color(194, 98, 94)) .setAuditLogReason("MCDC: Minecraft Server Role creation") @@ -72,6 +74,7 @@ public static Role createNewRole(Server server, String name, info("Created new Role " + ChatColor.GRAY + role.getName() + ChatColor.RESET + " on server " + ChatColor.RESET + server.getName() + "!"); + // Send the success embed, if one exists. if (successEmbed != null) successChannel.sendMessage(successEmbed.addField("New Role", "The new role is: " + role.getMentionTag() + "!") .addField("Usage:", "Give the role to any members that should be allowed to view and write to the minecraft channel. Later this will get added automatically with linking!")); diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index e6a75f8..392e366 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -45,12 +45,12 @@ public void onMessageCreate(MessageCreateEvent event) { info("Readable Message content is: " + content); + // Tris to parse the command. Command command; - try { command = CommandParser.parseFromString(content); } catch (CommandNotFinishedException | NoCommandGivenException e) { - Logging.logException(e, ""); + Logging.logException(e, "Error parsing the command from the string..."); return; } @@ -111,6 +111,7 @@ public void onMessageCreate(MessageCreateEvent event) { return; } + // get the first channel argument and checks, if it 'empty', but it exists. if (command.getStringArgument(0).isPresent()) { if (command.getStringArgument(0).get().equalsIgnoreCase("")) { Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); @@ -119,16 +120,14 @@ public void onMessageCreate(MessageCreateEvent event) { } } + // If the command has a wrong number of arguments, send the help message and exit. if (command.getArguments().length != 1) { event.getChannel().sendMessage(helpMessage); return; } - // Saves the states of the channel creation - boolean success = false; - + // Try getting the first argument. If it does not exist, send the help message and exit. String name; - if (command.getStringArgument(0).isPresent()) name = command.getStringArgument(0).get(); else { diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index 661e208..98ccc32 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -42,8 +42,8 @@ public void onMessageCreate(MessageCreateEvent event) { // Gets the content of the message as strings (prints it, if debug is enabled) String content = event.getReadableMessageContent(); + // Tries parsing the command. If it fails, exit. The error handling is being done by the CreateChannelListener. Command command; - try { command = CommandParser.parseFromString(content); } catch (CommandNotFinishedException | NoCommandGivenException e) { @@ -102,20 +102,24 @@ public void onMessageCreate(MessageCreateEvent event) { return; } + // If the user passed a wrong number of arguments, send the help message and exit. if (command.getStringArgument(0).isEmpty() || command.getStringArgument(1).isPresent()) { info("Person " + ChatColor.GRAY + event.getMessageAuthor().getDisplayName() + ChatColor.RESET + " used the command createRole wrong. Sending help embed."); event.getChannel().sendMessage(helpMessage); return; } + // If the server could not be found, send an error message and exit. if (event.getServer().isEmpty()) { event.getChannel().sendMessage(serverNotPresentError); Logging.info("Could not create the new Server Role: Server is not present. Sending Error Reply."); return; } - // TODO add linking and automatic linking of roles. + // add linking and automatic linking of roles. + // Comment of the author: The current version of the Discord API cannot handle adding roles to a channel. + // Try creating the new Role try { if (event.getChannel().asServerTextChannel().isPresent()) { Role role = RoleAdmin.createNewRole(event.getServer().get(), command.getStringArgument(0).get(), successEmbed, event.getChannel().asServerTextChannel().get()); @@ -133,6 +137,9 @@ public void onMessageCreate(MessageCreateEvent event) { .addField("ServerTextChannelNotPresentError", "Could not get this Channel as a server text channel. Maybe you sent this message in private message?") ); } + + // If this exception is thrown, the bot either does not have the permission to create a new channel or + // the connection to the discord servers has been lost. } catch (CompletionException exception) { event.getChannel().sendMessage(noPermissionEmbed); Logging.info(ChatColor.RED + "Could not execute createRole command. Do not have the required permissions."); diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index 2f07895..3663e6a 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -44,8 +44,8 @@ public void onMessageCreate(MessageCreateEvent event) { // Gets the content of the message as strings (prints it, if debug is enabled) String content = event.getReadableMessageContent(); + // Tries parsing the command. The error handling is being done by the CreateChannelListener. Command command; - try { command = CommandParser.parseFromString(content); } catch (CommandNotFinishedException | NoCommandGivenException e) { @@ -53,6 +53,7 @@ public void onMessageCreate(MessageCreateEvent event) { return; } + // If the command does not equal link, exit. if (!command.getCommand().equalsIgnoreCase(Settings.discordCommandPrefix + "link")) { // Logging.debug("Not the link command: \"" + command.getCommand() + "\" != \"" + discordCommandPrefix + "link" + "\""); return; @@ -98,9 +99,11 @@ public void onMessageCreate(MessageCreateEvent event) { return; } + // Checks if a number is given as the first argument. If not, send the user a new Link token. if (command.getIntegerArgument(0).isEmpty()) { Logging.debug("No Integer Argument given in link command. Sending LinkTokenEmbed..."); sendLinkToken(event.getMessageAuthor().asUser().get()); + // If a number is being found at the first argument, try to link it to a minecraft account. } else { Logging.debug("LinkToken found. Checking it..."); Optional linkedAccount = MinecraftLinker.linkToDiscord(event.getMessageAuthor().asUser().get(), command.getIntegerArgument(0).get()); diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index 6685e40..ac981c7 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -46,8 +46,8 @@ public void onMessageCreate(MessageCreateEvent event) { // Gets the content of the message as strings (prints it, if debug is enabled) String content = event.getReadableMessageContent(); + // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. Command command; - try { command = CommandParser.parseFromString(content); } catch (CommandNotFinishedException | NoCommandGivenException e) { @@ -75,12 +75,14 @@ public void onMessageCreate(MessageCreateEvent event) { .setFooter("Error while trying to create a channel") ; + // the embed sent on successful execution of the command. EmbedBuilder successEmbed = new EmbedBuilder() .setAuthor(event.getMessageAuthor()) .setTitle("Success!") .setColor(Color.GREEN) ; + // The embed sent to the new channel. EmbedBuilder welcomeEmbed = new EmbedBuilder() .setAuthor(discordApi.getYourself()) .setTitle("Welcome!") @@ -105,6 +107,7 @@ public void onMessageCreate(MessageCreateEvent event) { if (command.getCommand() == null) return; + // If the command is not equal to setup, do nothing and return. if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "setup")) return; @@ -115,24 +118,28 @@ public void onMessageCreate(MessageCreateEvent event) { return; } + // If the command has a wrong number of arguments, send the help embed and exit. if (command.getStringArgument(0).isEmpty() || command.getStringArgument(1).isPresent()) { info("Person " + ChatColor.GRAY + event.getMessageAuthor().getDisplayName() + ChatColor.RESET + " used the command setup wrong. Sending help embed."); event.getChannel().sendMessage(helpMessage); return; } + // If the first argument is empty, send the help message and exit. if (command.getStringArgument(0).get().equalsIgnoreCase("")) { info("Person " + ChatColor.GRAY + event.getMessageAuthor().getDisplayName() + ChatColor.RESET + " used the command setup wrong. Sending help embed."); event.getChannel().sendMessage(helpMessage); return; } + // If no server could be found, send an error message and exit. if (event.getServer().isEmpty()) { event.getChannel().sendMessage(serverNotPresentError); Logging.info("Could not setup the server: Server is not present. Sending Error Reply."); return; } + // If the channel you sent your message to is not a TextChannel, send as error message and exit. if (event.getChannel().asServerTextChannel().isEmpty()) { minecraftServer.getLogger().warning(prefix + "Could not get the ServerTextChannel. Sending error embed."); event.getChannel().sendMessage( @@ -148,6 +155,7 @@ public void onMessageCreate(MessageCreateEvent event) { String name = command.getStringArgument(0).get(); + // try to create the role. try { Role role = RoleAdmin.createNewRole(event.getServer().get(), name, null, event.getChannel().asServerTextChannel().get()); @@ -164,12 +172,10 @@ public void onMessageCreate(MessageCreateEvent event) { ServerTextChannel serverTextChannel = ChannelAdmin.createChannel(name, event.getServer().get(), "Minecraft Cross platform communication.", successEmbed, event.getServerTextChannel().get(), welcomeEmbed); - if (serverTextChannel == null) { - minecraftServer.getLogger().warning("Could not create the server Text channel. Unknown error!"); - return; - } - Logging.info("Added channel \"" + serverTextChannel.getName() + "\" and role \"" + role.getName() + "\" to server \"" + event.getServer().get().getName() + "\"!"); + + // If this exception is thrown, the bot either does not have the correct permissions to create channels and Roles, + // send the user an embed explaining the issue. } catch (CompletionException exception) { event.getChannel().sendMessage(noPermissionEmbed); Logging.info(ChatColor.RED + "Could not execute Setup command. Do not have the required permissions."); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Config.java b/src/main/java/com/github/mafelp/minecraft/commands/Config.java index fee5178..be03d4c 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Config.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Config.java @@ -7,15 +7,12 @@ import org.bukkit.ChatColor; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Objects; import static com.github.mafelp.utils.Settings.*; @@ -102,6 +99,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk } }); + // Prompt the user to confirm his/her choices. if (subCommand.getArguments().length == 0) commandSender.sendMessage(prefix + "Please type " + ChatColor.GRAY + "config default confirm" + ChatColor.RESET + " to confirm your actions!"); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index 0f6176b..9f28c53 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -32,19 +32,22 @@ public class Link implements CommandExecutor { */ @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { + // Check if the command Sender is a player. if (sender instanceof Player) { - Player player = ((Player) sender).getPlayer(); + // If the CommandSender is a player, we can safely cast it to a player. + Player player = (Player) sender; + // If no arguments are given, return and send the user a token. if (args == null) { sendLinkToken(player); return true; } - if (args.length < 1) { sendLinkToken(player); return true; } + // Try to link the ID, which was given as the argument, to a ID made with the discord link command. try { final int linkID = Integer.parseUnsignedInt(args[0]); @@ -58,11 +61,13 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command sender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.get().getUsername()); return true; + // This exception is thrown, when the first argument is not an integer. } catch (NumberFormatException exception) { sender.sendMessage(prefix + ChatColor.RED + "Error parsing your link Token! Please try again."); return false; } + // If the command is not executed by a player (e.g. a console), send an error message and exit. } else { sender.sendMessage(prefix + ChatColor.RED + "This command can only be executed as a Player!"); return true; diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Token.java b/src/main/java/com/github/mafelp/minecraft/commands/Token.java index d8f6d52..74a544e 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Token.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Token.java @@ -5,7 +5,6 @@ import com.github.mafelp.utils.Permissions; import com.github.mafelp.utils.Settings; import com.github.mafelp.discord.DiscordMain; -import jdk.jshell.spi.SPIResolutionException; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; From aa063f02e7fb3ee5be35039c4fe07f5e3379302d Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 21:30:32 +0200 Subject: [PATCH 011/158] =?UTF-8?q?=E2=9E=95=20Created=20AccountCommand=20?= =?UTF-8?q?framework=20for=20the=20minecraft=20command=20"account"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java new file mode 100644 index 0000000..af28087 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -0,0 +1,44 @@ +package com.github.mafelp.minecraft.commands; + +import com.github.mafelp.utils.Command; +import com.github.mafelp.utils.CommandParser; +import com.github.mafelp.utils.exceptions.CommandNotFinishedException; +import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; + +import static com.github.mafelp.utils.Settings.prefix; + +public class AccountCommand implements CommandExecutor { + @Override + public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukkit.command.Command command, @NotNull String label, String[] args) { + if (args == null) + return false; + + Command cmd; + try { + cmd = CommandParser.parseFromArray(args); + } catch (NoCommandGivenException exception) { + return false; + } catch (CommandNotFinishedException exception) { + commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); + return true; + } + + switch (cmd.getCommand().toLowerCase()) { + case "link" -> { + + } + case "name", "username" -> { + + } + default -> { + return false; + } + } + + return false; + } +} From 71dd182829a201bb1f7e065143e54a67bd329a83 Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 22:00:50 +0200 Subject: [PATCH 012/158] =?UTF-8?q?=E2=9E=95=20Created=20Account=20command?= =?UTF-8?q?=20in=20minecraft.=20Subcommands=20are:=20link,=20name,=20usern?= =?UTF-8?q?ame.=20=E2=9E=A1=EF=B8=8FMoved=20to=20version=200.9.0-beta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- .../com/github/mafelp/accounts/Account.java | 21 +++++ .../com/github/mafelp/minecraft/Main.java | 3 + .../minecraft/commands/AccountCommand.java | 94 +++++++++++++++---- .../mafelp/minecraft/commands/Link.java | 2 +- .../com/github/mafelp/utils/Settings.java | 2 +- src/main/resources/plugin.yml | 5 +- 7 files changed, 106 insertions(+), 23 deletions(-) diff --git a/pom.xml b/pom.xml index a05bd9e..32a1bb8 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.github.mafelp mcdc - 0.8.4-beta + 0.9.0-beta jar Mcdc diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index d322bae..f03e1e9 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -4,6 +4,7 @@ import org.bukkit.entity.Player; import org.javacord.api.entity.user.User; +import java.util.Optional; import java.util.UUID; /** @@ -114,4 +115,24 @@ public OfflinePlayer getPlayer() { public UUID getPlayerUUID() { return playerUUID; } + + public static Optional getByPlayer(OfflinePlayer player) { + for (Account account : AccountManager.getLinkedAccounts()) { + if (account.player.equals(player)) { + return Optional.of(account); + } + } + + return Optional.empty(); + } + + public static Optional getByDiscordUser(User user) { + for (Account account : AccountManager.getLinkedAccounts()) { + if (account.user.equals(user)) { + return Optional.of(account); + } + } + + return Optional.empty(); + } } diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 62512b6..c42ddd7 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -1,6 +1,7 @@ package com.github.mafelp.minecraft; import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.minecraft.commands.AccountCommand; import com.github.mafelp.utils.CheckPermission; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Permissions; @@ -103,5 +104,7 @@ private void commandRegistration() { Logging.info("Command \"token\" has been enabled."); Objects.requireNonNull(getCommand("config")).setExecutor(new Config()); Logging.info("Command \"config\" has been enabled."); + Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); + Logging.info("Command \"account\" has been enabled."); } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index af28087..af387a5 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -1,5 +1,8 @@ package com.github.mafelp.minecraft.commands; +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.accounts.DiscordLinker; import com.github.mafelp.utils.Command; import com.github.mafelp.utils.CommandParser; import com.github.mafelp.utils.exceptions.CommandNotFinishedException; @@ -7,38 +10,91 @@ import org.bukkit.ChatColor; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.Optional; + import static com.github.mafelp.utils.Settings.prefix; public class AccountCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukkit.command.Command command, @NotNull String label, String[] args) { - if (args == null) - return false; - - Command cmd; - try { - cmd = CommandParser.parseFromArray(args); - } catch (NoCommandGivenException exception) { - return false; - } catch (CommandNotFinishedException exception) { - commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); - return true; - } + if (commandSender instanceof Player) { - switch (cmd.getCommand().toLowerCase()) { - case "link" -> { + Player player = (Player) commandSender; + if (args == null) + return false; + + Command cmd; + try { + cmd = CommandParser.parseFromArray(args); + } catch (NoCommandGivenException exception) { + return false; + } catch (CommandNotFinishedException exception) { + commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); + return true; } - case "name", "username" -> { + if (cmd.getArguments() == null) { + commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); + return true; } - default -> { - return false; + + if (cmd.getArguments().length == 0) { + commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); + return true; } - } - return false; + switch (cmd.getCommand().toLowerCase()) { + case "link" -> { + Optional optionalLinkID = cmd.getIntegerArgument(0); + + if (optionalLinkID.isEmpty()) { + Link.sendLinkToken(player); + return true; + } + + Optional linkedAccount = DiscordLinker.linkToMinecraft(player, optionalLinkID.get()); + + if (linkedAccount.isEmpty()) { + Link.sendLinkToken(player); + return true; + } + + commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.get().getUsername()); + + return true; + + } + case "name", "username" -> { + if (Account.getByPlayer(player).isEmpty()) { + commandSender.sendMessage(prefix + ChatColor.RED + "No discord account account if linked to you. Use " + ChatColor.GRAY + "/link" + ChatColor.RED + " to get a link token and link your minecraft account to your discord account."); + return true; + } + + if (cmd.getStringArgument(0).isEmpty()) { + commandSender.sendMessage(prefix + "Your account name is: " + Account.getByPlayer(player).get().getUsername()); + return true; + } + + String nameToSet = cmd.getStringArgument(0).get(); + + Account account = Account.getByPlayer(player).get(); + + account.setUsername(nameToSet); + + commandSender.sendMessage(prefix + "Your username has been set to " + Account.getByPlayer(player).get().getUsername()); + + return true; + } + default -> { + return false; + } + } + } else { + return true; + } } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index 9f28c53..e4eeb48 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -78,7 +78,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command * The method that sends the link token in a nice message to the {@link Player} that executed this command. * @param player The player to send its token to. */ - private void sendLinkToken(Player player) { + protected static void sendLinkToken(Player player) { int discordLinkToken = MinecraftLinker.getLinkToken(player); player.sendMessage(prefix + ChatColor.RESET + "You link token is: " + ChatColor.GRAY + discordLinkToken + ChatColor.RESET + ". Use the command \"" + ChatColor.GRAY + Settings.discordCommandPrefix + "link " + discordLinkToken + ChatColor.RESET + "\" to link this minecraft account ot your discord account."); diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index a8df3b7..96b0d84 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -34,7 +34,7 @@ public class Settings { /** * version number of the plugin - displayed to users */ - public static final String version = "v0.8.4-beta"; + public static final String version = "v0.9.0-beta"; /** * enables more information being displayed while executing events diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 43b7db7..23676a3 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -17,4 +17,7 @@ commands: config: description: Configuration Admin tools usage: /config - permission-message: Only administrators can run this command. Sorry \ No newline at end of file + permission-message: Only administrators can run this command. Sorry + account: + description: The command to manage your linked account. + usage: /account [] From 7029b7f1f54b2cd0509c17ca7750197d17f4ba3e Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 22:17:33 +0200 Subject: [PATCH 013/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8FMoved=20username=20cr?= =?UTF-8?q?eation=20on=20account=20creation=20from=20discord=20username=20?= =?UTF-8?q?to=20minecraft=20username.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/accounts/Account.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index f03e1e9..8412653 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -51,10 +51,10 @@ public class Account { public Account(User user, OfflinePlayer player) { this.user = user; this.userID = user.getId(); - this.username = user.getName(); this.mentionTag = user.getMentionTag(); this.player = player; + this.username = player.getName(); this.playerUUID = player.getUniqueId(); } From 08aff872d80cf9643b8ae904f46a4ae38bbfce34 Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 22:25:47 +0200 Subject: [PATCH 014/158] =?UTF-8?q?=E2=9E=95=20Added=20changeable=20userna?= =?UTF-8?q?mes=20in=20the=20account=20command.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 45 ++++++++++++------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index af387a5..2d4ef32 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -5,6 +5,7 @@ import com.github.mafelp.accounts.DiscordLinker; import com.github.mafelp.utils.Command; import com.github.mafelp.utils.CommandParser; +import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.exceptions.CommandNotFinishedException; import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.bukkit.ChatColor; @@ -13,6 +14,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.Arrays; import java.util.Optional; import static com.github.mafelp.utils.Settings.prefix; @@ -37,16 +39,6 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } - if (cmd.getArguments() == null) { - commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); - return true; - } - - if (cmd.getArguments().length == 0) { - commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); - return true; - } - switch (cmd.getCommand().toLowerCase()) { case "link" -> { Optional optionalLinkID = cmd.getIntegerArgument(0); @@ -59,7 +51,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk Optional linkedAccount = DiscordLinker.linkToMinecraft(player, optionalLinkID.get()); if (linkedAccount.isEmpty()) { - Link.sendLinkToken(player); + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, your Link token is invalid. Please try again or use " + ChatColor.GRAY + "/link" + ChatColor.RESET + " to get a link token and instructions."); return true; } @@ -69,24 +61,47 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk } case "name", "username" -> { + Logging.debug("Minecraft user " + player.getName() + " used the command \"/account " + cmd.getCommand() + " " + Arrays.toString(cmd.getArguments())); if (Account.getByPlayer(player).isEmpty()) { commandSender.sendMessage(prefix + ChatColor.RED + "No discord account account if linked to you. Use " + ChatColor.GRAY + "/link" + ChatColor.RED + " to get a link token and link your minecraft account to your discord account."); return true; } if (cmd.getStringArgument(0).isEmpty()) { + Logging.info(ChatColor.GRAY + player.getName() + ChatColor.RESET + " requested his account name."); commandSender.sendMessage(prefix + "Your account name is: " + Account.getByPlayer(player).get().getUsername()); return true; } - String nameToSet = cmd.getStringArgument(0).get(); + // Validate the inputted string + String inputName = cmd.getStringArgument(0).get(); + + char[] chars = inputName.toCharArray(); + + int i = 0; + for (char c : chars) { + if (c == '@' && i != 0) { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are not allowed to have \"@\" in your name!"); + return true; + } + if (c == ' ') { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are not allowed to have spaces in your name!"); + return true; + } + i++; + } - Account account = Account.getByPlayer(player).get(); + // If the first character is an @, do not add one to the start of the name. + String nameToSet; + if (chars[0] == '@') + nameToSet = inputName; + else + nameToSet = '@' + inputName; + // Gets the account and sets its username. + Account account = Account.getByPlayer(player).get(); account.setUsername(nameToSet); - commandSender.sendMessage(prefix + "Your username has been set to " + Account.getByPlayer(player).get().getUsername()); - return true; } default -> { From 8f154fdea1b0e83ab98a77d779fe47d0cd4e1e8d Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 22:58:26 +0200 Subject: [PATCH 015/158] =?UTF-8?q?=E2=9E=95=20Added=20subcommand=20'get'?= =?UTF-8?q?=20to=20the=20accounts=20command,=20to=20get=20the=20username?= =?UTF-8?q?=20of=20a=20players=20account.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 2d4ef32..70eeaf2 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -6,15 +6,18 @@ import com.github.mafelp.utils.Command; import com.github.mafelp.utils.CommandParser; import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; import com.github.mafelp.utils.exceptions.CommandNotFinishedException; import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.Arrays; +import java.util.Objects; import java.util.Optional; import static com.github.mafelp.utils.Settings.prefix; @@ -104,6 +107,44 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk commandSender.sendMessage(prefix + "Your username has been set to " + Account.getByPlayer(player).get().getUsername()); return true; } + case "get" -> { + // If no additional arguments were passed, give the player his/her account name. + if (cmd.getStringArgument(0).isEmpty()) { + if (Account.getByPlayer(player).isEmpty()) { + Logging.debug("Player " + ChatColor.GRAY + player.getName() + ChatColor.RESET + " has requested his account name: He/She doesn't have one. Sending help message."); + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you do not have an account. Use " + ChatColor.GRAY + "/link" +ChatColor.RED + " to get one."); + return true; + } + Logging.debug("Player " + ChatColor.GRAY + player.getName() + ChatColor.RESET + " has requested his account name."); + commandSender.sendMessage(prefix + ChatColor.GREEN + "Your account name is: " + ChatColor.GRAY + Account.getByPlayer(player).get().getUsername()); + // If additional Arguments are passed, get the name of the accounts. + } else { + Logging.debug("Offline Players:"); + // Checks all players that were online at least once and if they have an account. + for (OfflinePlayer p : Settings.minecraftServer.getOfflinePlayers()) { + Logging.debug("`--> " + p.getName()); + // Check if the name of the player equals the requested name. + if (Objects.equals(p.getName(), cmd.getStringArgument(0).get())) { + // Get the account for the requested Player. + Optional requestedAccount = Account.getByPlayer(p); + + // If the player does not have an account, send an error message. + if (requestedAccount.isEmpty()) { + commandSender.sendMessage(prefix + ChatColor.RED + "Player " + p.getName() + " doesn't have an account."); + Logging.debug("Player " + player.getName() + " tried to get the account name for " + cmd.getStringArgument(0).get() + ", but he/she does not have an account!"); + } else { + Logging.debug("Player " + player.getName() + " got the account name for player " + cmd.getStringArgument(0).get() + ". It is: " + requestedAccount.get().getUsername()); + commandSender.sendMessage(prefix + ChatColor.GREEN + "The account name for player " + ChatColor.GRAY + p.getName() + ChatColor.GREEN + " is: " + ChatColor.GRAY + requestedAccount.get().getUsername()); + } + return true; + } + } + + // If no player could be found, send the player an error message and exit. + commandSender.sendMessage(prefix + ChatColor.RED + "Player with the name " + ChatColor.GRAY + cmd.getStringArgument(0).get() + ChatColor.GRAY + " does not exist!"); + } + return true; + } default -> { return false; } From 10673d1637ce7c1621e3d1691518b221a0341d23 Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 24 Apr 2021 23:05:43 +0200 Subject: [PATCH 016/158] =?UTF-8?q?=F0=9F=93=97=20Added=20additional=20com?= =?UTF-8?q?mentary.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 70eeaf2..1b66098 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -1,7 +1,6 @@ package com.github.mafelp.minecraft.commands; import com.github.mafelp.accounts.Account; -import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.accounts.DiscordLinker; import com.github.mafelp.utils.Command; import com.github.mafelp.utils.CommandParser; @@ -22,11 +21,23 @@ import static com.github.mafelp.utils.Settings.prefix; +/** + * The class that is being called on the execution of the command /account, executed as a minecraft player. + */ public class AccountCommand implements CommandExecutor { + /** + * The method that handles the execution of the command. + * @param commandSender The Player (or console) who executed this command. + * @param command The command that the Player (or console) executed. In this case: account + * @param label The label of the command. + * @param args Additional arguments passed into the command. + * @return If the command was executed successfully and if not displays the usage message. + */ @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukkit.command.Command command, @NotNull String label, String[] args) { + // Only allows players to execute this command. if (commandSender instanceof Player) { - + // If a player executed this command, we can cast the commandSender to a player. Player player = (Player) commandSender; if (args == null) @@ -44,24 +55,27 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk switch (cmd.getCommand().toLowerCase()) { case "link" -> { + // Initiates the linking process. Optional optionalLinkID = cmd.getIntegerArgument(0); + // If no link token was given, create one and send it to the player. if (optionalLinkID.isEmpty()) { Link.sendLinkToken(player); return true; } + // If a link token was given, try to link the accounts with the token. Optional linkedAccount = DiscordLinker.linkToMinecraft(player, optionalLinkID.get()); + // If the account is empty, the linkToken was invalid. Inform the user. if (linkedAccount.isEmpty()) { commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, your Link token is invalid. Please try again or use " + ChatColor.GRAY + "/link" + ChatColor.RESET + " to get a link token and instructions."); return true; } + // If the account isPresent, the token was valid and an account was being created. commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.get().getUsername()); - return true; - } case "name", "username" -> { Logging.debug("Minecraft user " + player.getName() + " used the command \"/account " + cmd.getCommand() + " " + Arrays.toString(cmd.getArguments())); @@ -145,11 +159,14 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk } return true; } + // If no subcommand was specified. default -> { return false; } } + // If the command was not executed by a player. } else { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, this command can only be executed by a player."); return true; } } From bdc7d6849f94799dcc10176278e51bc932c274ad Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 16:09:56 +0200 Subject: [PATCH 017/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20subcommand=20?= =?UTF-8?q?'account=20remove=20'=20to=20allow=20account=20a?= =?UTF-8?q?dministrators,=20specified=20in=20the=20config=20file,=20to=20r?= =?UTF-8?q?emove=20accounts.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defaultConfiguration.yml | 10 ++++ .../mafelp/accounts/AccountManager.java | 12 ++++- .../com/github/mafelp/minecraft/Main.java | 10 ++-- .../minecraft/commands/AccountCommand.java | 51 ++++++++++++++++--- .../github/mafelp/utils/CheckPermission.java | 23 +++++++++ .../com/github/mafelp/utils/Permissions.java | 5 ++ 6 files changed, 99 insertions(+), 12 deletions(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 4285e84..89c5472 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -29,9 +29,19 @@ discordCommandPrefix: '.' channelIDs: - 1234 +# Enables accounts and linking. +# Allowed values +enableLinking: true # Permission section for setting permission levels permission: + # The permissions on linking and editing accounts. + accountEdit: + # The OP level needed to remove accounts of players. + level: 3 + # A list of UUIDs of Players who have a wildcard to use this command. + allowedUserUUIDs: + - a unique ID # Permission for minecraft command /config configEdit: diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 5290e1d..0621196 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -106,8 +106,18 @@ protected static List setLinkedAccounts(List set) { * @param account The account to add * @return the list of all linked Accounts. */ - public static List addAccount (Account account) { + public static List addAccount(Account account) { linkedAccounts.add(account); return linkedAccounts; } + + /** + * Removes an account from the linked accounts. + * @param account The account link to be removed + * @return The now list of accounts. + */ + public static List removeAccount(Account account) { + linkedAccounts.removeAll(Collections.singleton(account)); + return linkedAccounts; + } } diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index c42ddd7..7731171 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -98,13 +98,15 @@ private void listenerRegistration() { private void commandRegistration() { // All commands // for more information read the Javadoc in the specific classes - Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); - Logging.info("Command \"link\" has been enabled."); Objects.requireNonNull(getCommand("token")).setExecutor(new Token()); Logging.info("Command \"token\" has been enabled."); Objects.requireNonNull(getCommand("config")).setExecutor(new Config()); Logging.info("Command \"config\" has been enabled."); - Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); - Logging.info("Command \"account\" has been enabled."); + if (Settings.getConfiguration().getBoolean("enableLinking")) { + Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); + Logging.info("Command \"link\" has been enabled."); + Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); + Logging.info("Command \"account\" has been enabled."); + } } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 1b66098..2a3ef66 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -1,11 +1,9 @@ package com.github.mafelp.minecraft.commands; import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.accounts.DiscordLinker; -import com.github.mafelp.utils.Command; -import com.github.mafelp.utils.CommandParser; -import com.github.mafelp.utils.Logging; -import com.github.mafelp.utils.Settings; +import com.github.mafelp.utils.*; import com.github.mafelp.utils.exceptions.CommandNotFinishedException; import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.bukkit.ChatColor; @@ -126,12 +124,12 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk if (cmd.getStringArgument(0).isEmpty()) { if (Account.getByPlayer(player).isEmpty()) { Logging.debug("Player " + ChatColor.GRAY + player.getName() + ChatColor.RESET + " has requested his account name: He/She doesn't have one. Sending help message."); - commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you do not have an account. Use " + ChatColor.GRAY + "/link" +ChatColor.RED + " to get one."); + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you do not have an account. Use " + ChatColor.GRAY + "/link" + ChatColor.RED + " to get one."); return true; } Logging.debug("Player " + ChatColor.GRAY + player.getName() + ChatColor.RESET + " has requested his account name."); commandSender.sendMessage(prefix + ChatColor.GREEN + "Your account name is: " + ChatColor.GRAY + Account.getByPlayer(player).get().getUsername()); - // If additional Arguments are passed, get the name of the accounts. + // If additional Arguments are passed, get the name of the accounts. } else { Logging.debug("Offline Players:"); // Checks all players that were online at least once and if they have an account. @@ -159,12 +157,51 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk } return true; } + // Removes an account, if the player has the required permissions. + case "remove" -> { + // If the user does not have te required permissions, exit. + if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + + prefix + "This incident will be reported!"); + Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); + return true; + } + + // Checks if enough arguments were passed. + if (cmd.getStringArgument(0).isEmpty()) { + commandSender.sendMessage(prefix + ChatColor.RED + "Not enough arguments given!"); + Logging.debug("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! The command did not have enough/too much arguments!"); + return false; + } + + // Iterates over all players to find the one that matches the name given as the first argument to + // the subcommand. If the names match, it removes the account. If no account could be found it + // returns an error. + OfflinePlayer[] players = Settings.minecraftServer.getOfflinePlayers(); + for (OfflinePlayer p : players) { + if (Objects.equals(p.getName(), cmd.getStringArgument(0).get())) { + if (Account.getByPlayer(p).isPresent()) { + String username = Account.getByPlayer(p).get().getUsername(); + AccountManager.removeAccount(Account.getByPlayer(p).get()); + commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully removed account with username: " + username); + Logging.info("Player " + commandSender.getName() + "remove the account with the name " + ChatColor.GRAY + username + ChatColor.RESET + "."); + } else { + commandSender.sendMessage(prefix + ChatColor.RED + "Account with the Minecraft name: " + ChatColor.GRAY + cmd.getStringArgument(0).get() + ChatColor.RED + " does not exist!"); + } + return true; + } + } + + // If the player whose name was passed, does not exist, return an error. + commandSender.sendMessage(prefix + ChatColor.RED + "Player with the name " + ChatColor.GRAY + cmd.getStringArgument(0).get() + ChatColor.RED + " was never on this server!"); + return true; + } // If no subcommand was specified. default -> { return false; } } - // If the command was not executed by a player. + // If the command was not executed by a player. } else { commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, this command can only be executed by a player."); return true; diff --git a/src/main/java/com/github/mafelp/utils/CheckPermission.java b/src/main/java/com/github/mafelp/utils/CheckPermission.java index 972dc30..d1dd8d6 100644 --- a/src/main/java/com/github/mafelp/utils/CheckPermission.java +++ b/src/main/java/com/github/mafelp/utils/CheckPermission.java @@ -207,4 +207,27 @@ public static boolean checkPermission(final Permissions permission, final Comman return false; } } + + public static boolean checkPermission(final Permissions permission, final MessageAuthor messageAuthor) { + if (messageAuthor.isBotOwner()) { + + return true; + } + + if (messageAuthor.isServerAdmin()) { + + return true; + } + + String permissionToCheck = permission.toString(); + + for (final long id : Settings.getConfiguration().getLongList("permission." + permissionToCheck + ".allowedUserIDs")) { + if (id == messageAuthor.getId()) { + + return true; + } + } + + return false; + } } \ No newline at end of file diff --git a/src/main/java/com/github/mafelp/utils/Permissions.java b/src/main/java/com/github/mafelp/utils/Permissions.java index f92000f..f176c79 100644 --- a/src/main/java/com/github/mafelp/utils/Permissions.java +++ b/src/main/java/com/github/mafelp/utils/Permissions.java @@ -9,6 +9,11 @@ public enum Permissions { */ configEdit, + /** + * The permission to edit and remove accounts from the command line. + */ + accountEdit, + /** * The permission to perform commands on teh discord servers. */ From e6c535403889b33ecc29cf5d2d16d7ce645d0e4f Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 16:18:36 +0200 Subject: [PATCH 018/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20subcommand=20?= =?UTF-8?q?'account=20save'=20to=20allow=20account=20administrators,=20spe?= =?UTF-8?q?cified=20in=20the=20config=20file,=20to=20save=20accounts=20the?= =?UTF-8?q?=20accounts=20file=20during=20the=20live=20running=20of=20the?= =?UTF-8?q?=20server.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 2a3ef66..f12cec3 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -13,6 +13,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -173,6 +174,11 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk Logging.debug("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! The command did not have enough/too much arguments!"); return false; } + if (cmd.getStringArgument(0).get().equals("")) { + commandSender.sendMessage(prefix + ChatColor.RED + "Not enough arguments given!"); + Logging.debug("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! The command did not have enough/too much arguments!"); + return false; + } // Iterates over all players to find the one that matches the name given as the first argument to // the subcommand. If the names match, it removes the account. If no account could be found it @@ -196,6 +202,28 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk commandSender.sendMessage(prefix + ChatColor.RED + "Player with the name " + ChatColor.GRAY + cmd.getStringArgument(0).get() + ChatColor.RED + " was never on this server!"); return true; } + // The subcommand used to save the accounts file. + case "save" -> { + // If the user does not have te required permissions, exit. + if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + + prefix + "This incident will be reported!"); + Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); + return true; + } + + try { + commandSender.sendMessage(prefix + ChatColor.YELLOW + "Saving accounts file..."); + Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " is saving the configuration file."); + AccountManager.saveAccounts(); + Logging.info(ChatColor.GREEN + "Successfully saved the accounts file!"); + commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully saved the accounts file!"); + } catch (FileNotFoundException e) { + Logging.logIOException(e, "Error saving the account file! (Author of this save: " + commandSender.getName()); + commandSender.sendMessage(prefix + ChatColor.RED + "A FileNotFoundException occurred! Please see the console for more details!"); + } + return true; + } // If no subcommand was specified. default -> { return false; From 5f26c06b3cd57f016dda18a48e847cfafb42cb05 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 16:55:51 +0200 Subject: [PATCH 019/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20subcommand=20?= =?UTF-8?q?'account=20reload'=20to=20allow=20account=20administrators,=20s?= =?UTF-8?q?pecified=20in=20the=20config=20file,=20to=20reload=20all=20acco?= =?UTF-8?q?unts=20from=20the=20accounts=20file.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index f12cec3..321b00f 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -14,6 +14,7 @@ import org.jetbrains.annotations.NotNull; import java.io.FileNotFoundException; +import java.io.IOException; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -224,6 +225,29 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk } return true; } + // The subcommand used to reload the accounts file into memory. + case "reload" -> { + // If the user does not have te required permissions, exit. + if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + + prefix + "This incident will be reported!"); + Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); + return true; + } + + // Try to reload the accounts + try { + commandSender.sendMessage(prefix + ChatColor.YELLOW + "Reloading the accounts file... Warning! Only edit the file, if you know what you are doing!"); + AccountManager.loadAccounts(); + commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully reloaded the accounts file!"); + } catch (IOException e) { + Logging.logIOException(e, "Error reloading the accounts file (Author of this command: " + commandSender.getName() + ")."); + commandSender.sendMessage(prefix + ChatColor.RED + "adf"); + } + + return true; + } + // If no subcommand was specified. default -> { return false; From 49982422af4f561e19d557bfe0ed4932164ec331 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 17:26:00 +0200 Subject: [PATCH 020/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20subcommand=20?= =?UTF-8?q?'account=20list'=20to=20allow=20allow=20users=20to=20list=20all?= =?UTF-8?q?=20the=20currently=20linked=20accounts.=20This=20can=20be=20tog?= =?UTF-8?q?gled=20in=20the=20configuration=20with=20the=20entry:=20'allowL?= =?UTF-8?q?istAllAccounts'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defaultConfiguration.yml | 4 +++ .../minecraft/commands/AccountCommand.java | 26 +++++++++++++++++++ .../com/github/mafelp/utils/Settings.java | 11 +++++--- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 89c5472..1cd555e 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -33,6 +33,10 @@ channelIDs: # Allowed values enableLinking: true +# Allow players to list all the accounts. +# Allowed values +allowListAllAccounts: true + # Permission section for setting permission levels permission: # The permissions on linking and editing accounts. diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 321b00f..66fcbdf 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -247,7 +247,33 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } + // The subcommand that lists all currently linked accounts + case "list" -> { + boolean allowed = Settings.getConfiguration().getBoolean("allowListAllAccounts"); + if (CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) + allowed = true; + + if (allowed) { + String sb = ""; + + sb += prefix + ChatColor.GREEN + "---Linked Accounts---\n" + ChatColor.RESET; + sb += ChatColor.DARK_GRAY + "+===========================+\n" + ChatColor.RESET; + sb += ChatColor.YELLOW + "Minecraft Name; Discord Username; Discord Ping Tag\n" + ChatColor.RESET; + sb += ChatColor.DARK_GRAY + "+===========================+\n" + ChatColor.RESET; + + for (Account a : AccountManager.getLinkedAccounts()) + sb += ChatColor.AQUA + a.getPlayer().getName() + "; " + a.getUser().getName() + "; " + a.getUsername() + "\n"; + + sb += ChatColor.DARK_GRAY + "+===========================+" + ChatColor.RESET; + + commandSender.sendMessage(sb); + } else { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, the Server administrator has disabled the listing of accounts!"); + } + + return true; + } // If no subcommand was specified. default -> { return false; diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 96b0d84..52eaaa9 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -7,6 +7,8 @@ import org.javacord.api.event.message.MessageCreateEvent; import java.io.*; +import java.util.ArrayList; +import java.util.UUID; import static com.github.mafelp.utils.Logging.info; import static com.github.mafelp.utils.Logging.logIOException; @@ -247,10 +249,13 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("serverName", "A Minecraft Server"); defaultConfiguration.set("debug", false); defaultConfiguration.set("discordCommandPrefix", "."); + defaultConfiguration.set("allowListAllAccounts", true); + defaultConfiguration.set("permission.accountEdit.level", 3); + defaultConfiguration.set("permission.accountEdit.allowedUserUUIDs", new ArrayList()); defaultConfiguration.set("permission.configEdit.level", 3); - defaultConfiguration.set("permission.configEdit.allowedUserUUIDs", null); - defaultConfiguration.set("permission.discordServerAdmin.allowedUserIDs", null); - defaultConfiguration.set("permission.discordBotAdmin.allowedUserIDs", null); + defaultConfiguration.set("permission.configEdit.allowedUserUUIDs", new ArrayList()); + defaultConfiguration.set("permission.discordServerAdmin.allowedUserIDs", new ArrayList()); + defaultConfiguration.set("permission.discordBotAdmin.allowedUserIDs", new ArrayList()); defaultConfiguration.set("saveEscapeCharacterInConfig", true); return defaultConfiguration; From d1ea0d2cfaa16f2e91875736cfe2cf607bdfa68d Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 17:27:12 +0200 Subject: [PATCH 021/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20the=20account=20creation=20would=20not=20add=20the=20@=20in?= =?UTF-8?q?=20front=20of=20the=20username.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/accounts/Account.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index 8412653..784900e 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -54,7 +54,7 @@ public Account(User user, OfflinePlayer player) { this.mentionTag = user.getMentionTag(); this.player = player; - this.username = player.getName(); + this.username = "@" + player.getName(); this.playerUUID = player.getUniqueId(); } From 09b17f549bd223d766973065432fe11b1fa0e04a Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 17:38:05 +0200 Subject: [PATCH 022/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20method=20to?= =?UTF-8?q?=20get=20an=20Account=20by=20its=20username,=20starting=20with?= =?UTF-8?q?=20'@'.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/accounts/Account.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index 784900e..e1c88b7 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -135,4 +135,14 @@ public static Optional getByDiscordUser(User user) { return Optional.empty(); } + + public static Optional getByUsername(String username) { + for (Account account : AccountManager.getLinkedAccounts()) { + if (account.getUsername().equals(username)) { + return Optional.of(account); + } + } + + return Optional.empty(); + } } From 518700efa1801e465a1091c387d5ae4a45ad192c Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 17:40:01 +0200 Subject: [PATCH 023/158] =?UTF-8?q?=E2=9E=95=20Added=20pinging=20of=20Acco?= =?UTF-8?q?unts:=20=E2=86=B3=20When=20you=20type=20the=20'Discord=20Ping?= =?UTF-8?q?=20Tag'=20of=20an=20account,=20it=20will=20be=20replaced=20with?= =?UTF-8?q?=20the=20MentionTag=20of=20the=20Discord=20User=20so=20that=20h?= =?UTF-8?q?e/she=20will=20be=20clickable=20in=20the=20message=20embed.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/minecraft/MinecraftChatListener.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java b/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java index f0eb549..21c8e34 100644 --- a/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java +++ b/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java @@ -1,11 +1,14 @@ package com.github.mafelp.minecraft; +import com.github.mafelp.accounts.Account; import com.github.mafelp.discord.ChannelAdmin; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; +import java.util.Optional; + /** * Class that reacts to chat messages sent on the minecraft server. */ @@ -21,6 +24,17 @@ public void onChatMessage(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String message = event.getMessage(); + // Replaces Account usernames with their matching MentionTag so the user will be pinged in the Message. + String[] messageParts = message.split(" "); + message = ""; + for (String s : messageParts) { + Optional a = Account.getByUsername(s); + if (a.isPresent()) + message += a.get().getMentionTag() + " "; + else + message = s + " "; + } + // Hand the sending of the message to the dedicated method. ChannelAdmin.broadcastMessage(player, message); } From 4c509716da33de9e541df5f2de9ce82edc84d815 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 17:47:52 +0200 Subject: [PATCH 024/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20toggle,=20so?= =?UTF-8?q?=20you=20can=20change,=20if=20the=20footer=20of=20a=20message?= =?UTF-8?q?=20should=20be=20displayed.=20=E2=9E=A1=EF=B8=8F=20Moved=20the?= =?UTF-8?q?=20Message=20contents=20from=20an=20inline=20field=20to=20the?= =?UTF-8?q?=20description.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defaultConfiguration.yml | 4 ++++ .../com/github/mafelp/discord/DiscordMessageBroadcast.java | 5 +++-- src/main/java/com/github/mafelp/utils/Settings.java | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 1cd555e..0e5dcc4 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -37,6 +37,10 @@ enableLinking: true # Allowed values allowListAllAccounts: true +# Decides, if the config value 'serverName' should be displayed in the footer of discord messages. +# Allowed values +showFooterInMessages: true + # Permission section for setting permission levels permission: # The permissions on linking and editing accounts. diff --git a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java index ac3f5e3..f0554d7 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java @@ -52,9 +52,10 @@ public void run() { // .setAuthor(messageAuthor.getDisplayName()) .setAuthor(messageAuthor.getDisplayName(), "", new Skin(messageAuthor, false).getHead(), ".png") .setColor(Color.YELLOW) - .setFooter("On " + Settings.serverName) - .addInlineField("Message:", message); + .setDescription(message); + if (Settings.getConfiguration().getBoolean("showFooterInMessages", true)) + embed.setFooter("On " + Settings.serverName); // send the embed to all channels in the list for (Channel channel : channels) { // only send the embed, if the channel is present, to avoid exceptions diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 52eaaa9..ba5b201 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -250,6 +250,7 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("debug", false); defaultConfiguration.set("discordCommandPrefix", "."); defaultConfiguration.set("allowListAllAccounts", true); + defaultConfiguration.set("showFooterInMessages", true); defaultConfiguration.set("permission.accountEdit.level", 3); defaultConfiguration.set("permission.accountEdit.allowedUserUUIDs", new ArrayList()); defaultConfiguration.set("permission.configEdit.level", 3); From 86552707aaf1e0bd40cf87ec410c124202de4e77 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 18:03:22 +0200 Subject: [PATCH 025/158] =?UTF-8?q?=E2=9E=95=20Added=20new=20toggle:=20Com?= =?UTF-8?q?mand=20messages=20can=20now=20be=20deleted=20by=20the=20bot.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defaultConfiguration.yml | 4 ++++ .../java/com/github/mafelp/discord/DiscordMain.java | 1 + .../discord/commands/CreateChannelListener.java | 8 ++++++++ .../mafelp/discord/commands/CreateRoleListener.java | 8 ++++++++ .../mafelp/discord/commands/LinkListener.java | 8 ++++++++ .../mafelp/discord/commands/SetupListener.java | 13 +++++++++---- src/main/java/com/github/mafelp/utils/Settings.java | 1 + 7 files changed, 39 insertions(+), 4 deletions(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 0e5dcc4..484f4be 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -25,6 +25,10 @@ apiToken: 'Your API Token goes here!' # Allowed values: any String discordCommandPrefix: '.' +# Selects if messages that are commands should be deleted after execution. +# Allowed values: +deleteDiscordCommandMessages: false + # Discord Channel IDs to broadcast messages to. channelIDs: - 1234 diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 5fbaea4..1c5d4af 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -72,6 +72,7 @@ public void run() { .setAllowed(PermissionType.MENTION_EVERYONE) .setAllowed(PermissionType.USE_EXTERNAL_EMOJIS) .setAllowed(PermissionType.ADD_REACTIONS) + .setAllowed(PermissionType.MANAGE_MESSAGES) .build(); // Log that the instance is being started diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index 392e366..203df24 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -104,6 +104,14 @@ public void onMessageCreate(MessageCreateEvent event) { if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "createChannel")) return; + // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( + void_ -> Logging.debug("Deleted the original command message.") + ); + } + // Checks the permission of the message author. if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index 98ccc32..37ff627 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -95,6 +95,14 @@ public void onMessageCreate(MessageCreateEvent event) { if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "createRole")) return; + // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( + void_ -> Logging.debug("Deleted the original command message.") + ); + } + // Checks the permission of the message author. if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index 3663e6a..54de9ae 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -59,6 +59,14 @@ public void onMessageCreate(MessageCreateEvent event) { return; } + // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( + void_ -> Logging.debug("Deleted the original command message.") + ); + } + // Tries to parse the message author into a user. If this fails, don't execute this command. if (event.getMessageAuthor().asUser().isEmpty()) { Logging.debug("Could not parse user, while trying to execute link command. Aborting..."); diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index ac981c7..c0d1ce2 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -2,10 +2,7 @@ import com.github.mafelp.discord.ChannelAdmin; import com.github.mafelp.discord.RoleAdmin; -import com.github.mafelp.utils.CheckPermission; -import com.github.mafelp.utils.Command; -import com.github.mafelp.utils.CommandParser; -import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.*; import com.github.mafelp.utils.exceptions.CommandNotFinishedException; import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.bukkit.ChatColor; @@ -111,6 +108,14 @@ public void onMessageCreate(MessageCreateEvent event) { if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "setup")) return; + // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( + void_ -> Logging.debug("Deleted the original command message.") + ); + } + // Checks the permission of the message author. if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"setup\"!"); diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index ba5b201..3018983 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -249,6 +249,7 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("serverName", "A Minecraft Server"); defaultConfiguration.set("debug", false); defaultConfiguration.set("discordCommandPrefix", "."); + defaultConfiguration.set("deleteDiscordCommandMessages", false); defaultConfiguration.set("allowListAllAccounts", true); defaultConfiguration.set("showFooterInMessages", true); defaultConfiguration.set("permission.accountEdit.level", 3); From 42f8bdac53a6bcd1aa981915118023ec4a0d2327 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 18:15:45 +0200 Subject: [PATCH 026/158] =?UTF-8?q?=F0=9F=93=97=20Updated=20JavaDoc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/accounts/Account.java | 15 +++++++++++++++ .../com/github/mafelp/utils/CheckPermission.java | 15 +++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/Account.java b/src/main/java/com/github/mafelp/accounts/Account.java index e1c88b7..a68fa2b 100644 --- a/src/main/java/com/github/mafelp/accounts/Account.java +++ b/src/main/java/com/github/mafelp/accounts/Account.java @@ -116,6 +116,11 @@ public UUID getPlayerUUID() { return playerUUID; } + /** + * The method to get an {@link Account} by the {@link OfflinePlayer} it belongs to. + * @param player the {@link OfflinePlayer} to get the {@link Account} of. + * @return the Optional of an {@link Account}: If this account does not exists, it is empty. + */ public static Optional getByPlayer(OfflinePlayer player) { for (Account account : AccountManager.getLinkedAccounts()) { if (account.player.equals(player)) { @@ -126,6 +131,11 @@ public static Optional getByPlayer(OfflinePlayer player) { return Optional.empty(); } + /** + * The method to get an {@link Account} by the {@link User} it belongs to. + * @param user the {@link User} to get the {@link Account} of. + * @return the Optional of an {@link Account}: If this account does not exists, it is empty. + */ public static Optional getByDiscordUser(User user) { for (Account account : AccountManager.getLinkedAccounts()) { if (account.user.equals(user)) { @@ -136,6 +146,11 @@ public static Optional getByDiscordUser(User user) { return Optional.empty(); } + /** + * The method to get an {@link Account} by the {@link Account#username} it belongs to. + * @param username the {@link Account#username} to get the {@link Account} of. + * @return the Optional of an {@link Account}: If this account does not exists, it is empty. + */ public static Optional getByUsername(String username) { for (Account account : AccountManager.getLinkedAccounts()) { if (account.getUsername().equals(username)) { diff --git a/src/main/java/com/github/mafelp/utils/CheckPermission.java b/src/main/java/com/github/mafelp/utils/CheckPermission.java index d1dd8d6..0c75b35 100644 --- a/src/main/java/com/github/mafelp/utils/CheckPermission.java +++ b/src/main/java/com/github/mafelp/utils/CheckPermission.java @@ -208,26 +208,33 @@ public static boolean checkPermission(final Permissions permission, final Comman } } + /** + * Checks the configuration if a command executor has a specific permission or has a specific level. + * @param permission The permission to check the level of. + * @param messageAuthor the discord {@link org.javacord.api.entity.user.User} of a command to check the permission of. + * @return if the command sender has the permission. + */ public static boolean checkPermission(final Permissions permission, final MessageAuthor messageAuthor) { if (messageAuthor.isBotOwner()) { - + Logging.debug("Granting permission " + permission + " to " + messageAuthor.getDisplayName() + ": is the bot Owner."); return true; } if (messageAuthor.isServerAdmin()) { - + Logging.debug("Granting permission " + permission + " to " + messageAuthor.getDisplayName() + ": is a Server Administrator"); return true; } + Logging.debug("Checking permission " + permission + " for player " + messageAuthor.getDisplayName() + "..."); String permissionToCheck = permission.toString(); for (final long id : Settings.getConfiguration().getLongList("permission." + permissionToCheck + ".allowedUserIDs")) { if (id == messageAuthor.getId()) { - + Logging.debug("Granting permission " + permission + " for player " + messageAuthor.getDisplayName() + "..."); return true; } } - + Logging.debug("Denying permission " + permission + " for player " + messageAuthor.getDisplayName() + "..."); return false; } } \ No newline at end of file From d4cfbc5a6830507fe597aa8f8fe07a79d856f7d4 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 21:19:16 +0200 Subject: [PATCH 027/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20only=20the=20last=20word=20of=20the=20message=20would=20be?= =?UTF-8?q?=20broadcast=20to=20the=20discord=20channels.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/minecraft/MinecraftChatListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java b/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java index 21c8e34..608ee98 100644 --- a/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java +++ b/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java @@ -32,7 +32,7 @@ public void onChatMessage(AsyncPlayerChatEvent event) { if (a.isPresent()) message += a.get().getMentionTag() + " "; else - message = s + " "; + message += s + " "; } // Hand the sending of the message to the dedicated method. From 8de9b5e3b3e2f68ee8cfe358b3e8e09000dce253 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 21:23:25 +0200 Subject: [PATCH 028/158] =?UTF-8?q?=E2=9E=95=20Added=20link=20freeing=20af?= =?UTF-8?q?ter=20an=20account=20has=20been=20linked.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/accounts/DiscordLinker.java | 3 +++ src/main/java/com/github/mafelp/accounts/MinecraftLinker.java | 3 +++ 2 files changed, 6 insertions(+) diff --git a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java index c657deb..6d6936e 100644 --- a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java +++ b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java @@ -53,6 +53,9 @@ public static Optional linkToMinecraft(Player player, int linkID) { AccountManager.addAccount(account); + //removes the current linkID from the map, so the link id would be freed again. + linkableAccounts.remove(u); + return Optional.of(account); } } diff --git a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java index 8ca0d90..0a92e36 100644 --- a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java +++ b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java @@ -67,6 +67,9 @@ public static Optional linkToDiscord(User user, int linkID) { AccountManager.addAccount(account); + //removes the current linkID from the map, so the link id would be freed again. + linkableAccounts.remove(p); + return Optional.of(account); } } From a57f477211a6c158d5c4b6d08417bc0541992fa6 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 21:46:14 +0200 Subject: [PATCH 029/158] =?UTF-8?q?=E2=9E=95=20Added=20unlinking=20of=20ac?= =?UTF-8?q?counts=20from=20the=20minecraft=20side=20of=20things.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 7 +-- .../minecraft/commands/AccountCommand.java | 25 +++++++++ .../mafelp/minecraft/commands/Unlink.java | 56 +++++++++++++++++++ src/main/resources/plugin.yml | 5 +- 4 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/commands/Unlink.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 7731171..ace2d57 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -1,15 +1,12 @@ package com.github.mafelp.minecraft; import com.github.mafelp.accounts.AccountManager; -import com.github.mafelp.minecraft.commands.AccountCommand; +import com.github.mafelp.minecraft.commands.*; import com.github.mafelp.utils.CheckPermission; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Permissions; import com.github.mafelp.utils.Settings; import com.github.mafelp.discord.DiscordMain; -import com.github.mafelp.minecraft.commands.Config; -import com.github.mafelp.minecraft.commands.Link; -import com.github.mafelp.minecraft.commands.Token; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -107,6 +104,8 @@ private void commandRegistration() { Logging.info("Command \"link\" has been enabled."); Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); Logging.info("Command \"account\" has been enabled."); + Objects.requireNonNull(getCommand("account")).setExecutor(new Unlink()); + Logging.info("Command \"unlink\" has been enabled."); } } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 66fcbdf..61cf2d7 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -20,6 +20,8 @@ import java.util.Optional; import static com.github.mafelp.utils.Settings.prefix; +import static org.bukkit.ChatColor.*; +import static org.bukkit.ChatColor.GREEN; /** * The class that is being called on the execution of the command /account, executed as a minecraft player. @@ -77,6 +79,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.get().getUsername()); return true; } + // Sets you username case "name", "username" -> { Logging.debug("Minecraft user " + player.getName() + " used the command \"/account " + cmd.getCommand() + " " + Arrays.toString(cmd.getArguments())); if (Account.getByPlayer(player).isEmpty()) { @@ -121,6 +124,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk commandSender.sendMessage(prefix + "Your username has been set to " + Account.getByPlayer(player).get().getUsername()); return true; } + // The subcommand used to get your/another players account name. case "get" -> { // If no additional arguments were passed, give the player his/her account name. if (cmd.getStringArgument(0).isEmpty()) { @@ -274,6 +278,27 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } + // The subcommand that unlinks your account. + case "unlink" -> { + Optional accountOptional = Account.getByPlayer(player); + + if (accountOptional.isEmpty()) { + commandSender.sendMessage(prefix + RED + "You don't have an account ot unlink! Use " + GRAY + "/link" + RED + " to create one."); + return true; + } + + Account account = accountOptional.get(); + + if (cmd.getStringArgument(0).isEmpty()) { + Logging.info("Removing account " + account.getUsername()); + commandSender.sendMessage(prefix + YELLOW + "Removing the account" + GRAY + account.getUsername() + YELLOW + "..."); + AccountManager.removeAccount(account); + commandSender.sendMessage(prefix + GREEN + "Successfully removed your account!"); + return true; + } + + return false; + } // If no subcommand was specified. default -> { return false; diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java b/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java new file mode 100644 index 0000000..0126af1 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java @@ -0,0 +1,56 @@ +package com.github.mafelp.minecraft.commands; + +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.utils.Logging; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +import static com.github.mafelp.utils.Settings.prefix; +import static org.bukkit.ChatColor.*; + +public class Unlink implements CommandExecutor { + @Override + public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, String[] args) { + // Only players can have accounts. + if (commandSender instanceof Player) { + Player player = (Player) commandSender; + + Optional accountOptional = Account.getByPlayer(player); + + if (accountOptional.isEmpty()) { + commandSender.sendMessage(prefix + RED + "You don't have an account ot unlink! Use " + GRAY + "/link" + RED + " to create one."); + return true; + } + + Account account = accountOptional.get(); + + if (args == null) { + Logging.info("Removing account " + account.getUsername()); + commandSender.sendMessage(prefix + YELLOW + "Removing the account" + GRAY + account.getUsername() + YELLOW + "..."); + AccountManager.removeAccount(account); + commandSender.sendMessage(prefix + GREEN + "Successfully removed your account!"); + return true; + } + + if (args.length == 0) { + Logging.info("Removing account " + account.getUsername()); + commandSender.sendMessage(prefix + YELLOW + "Removing the account" + GRAY + account.getUsername() + YELLOW + "..."); + AccountManager.removeAccount(account); + commandSender.sendMessage(prefix + GREEN + "Successfully removed your account!"); + return true; + } + + return false; + } else { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you can only execute this command as a player!"); + return true; + } + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 23676a3..504d6ab 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -20,4 +20,7 @@ commands: permission-message: Only administrators can run this command. Sorry account: description: The command to manage your linked account. - usage: /account [] + usage: /account [] + unlink: + description: The command used to remove your account. + usage: /unlink \ No newline at end of file From 9785bb6827fc4cff6a662e6e8813a740d5482c34 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 26 Apr 2021 22:03:07 +0200 Subject: [PATCH 030/158] =?UTF-8?q?=E2=9E=95=20Added=20unlinking=20of=20ac?= =?UTF-8?q?counts=20on=20the=20discord=20side=20of=20things.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 6 +- .../discord/commands/UnlinkListener.java | 122 ++++++++++++++++++ 2 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 1c5d4af..2b09f96 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -1,12 +1,9 @@ package com.github.mafelp.discord; import com.github.mafelp.accounts.AccountManager; -import com.github.mafelp.discord.commands.CreateRoleListener; -import com.github.mafelp.discord.commands.LinkListener; -import com.github.mafelp.discord.commands.SetupListener; +import com.github.mafelp.discord.commands.*; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; -import com.github.mafelp.discord.commands.CreateChannelListener; import org.bukkit.ChatColor; import org.javacord.api.DiscordApiBuilder; import org.javacord.api.entity.permission.PermissionType; @@ -89,6 +86,7 @@ public void run() { .addListener(CreateRoleListener::new) .addListener(SetupListener::new) .addListener(LinkListener::new) + .addListener(UnlinkListener::new) // log the bot in and join the servers .login().join(); // TODO Add: activity diff --git a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java new file mode 100644 index 0000000..218d138 --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java @@ -0,0 +1,122 @@ +package com.github.mafelp.discord.commands; + +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.utils.Command; +import com.github.mafelp.utils.CommandParser; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; +import com.github.mafelp.utils.exceptions.CommandNotFinishedException; +import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.message.MessageCreateEvent; +import org.javacord.api.listener.message.MessageCreateListener; + +import java.awt.*; +import java.util.Optional; + +import static com.github.mafelp.utils.Settings.*; + +public class UnlinkListener implements MessageCreateListener { + @Override + public void onMessageCreate(MessageCreateEvent messageCreateEvent) { + // If the message is sent by the bot, return + if (messageCreateEvent.getMessageAuthor().isYourself()) { + return; + } + + // If message does not start with the command prefix, return + // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || + // event.getReadableMessageContent() == null) + // return; + + + // Gets the content of the message as strings (prints it, if debug is enabled) + String content = messageCreateEvent.getReadableMessageContent(); + + // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. + Command command; + try { + command = CommandParser.parseFromString(content); + } catch (CommandNotFinishedException | NoCommandGivenException e) { + // Logging.logException(e, "Error parsing hte command from the string..."); + return; + } + + // help message for wrong usage + EmbedBuilder helpMessage = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("Error") + .addField("Usage", discordCommandPrefix + "unlink") + .addField("Functionality", "Unlinks your discord account from your minecraft account.") + .setColor(new Color(0xFFB500)) + .setFooter("Help message for command \"unlink\"") + ; + + // the embed sent on successful execution of the command. + EmbedBuilder successEmbed = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("Success!") + .setColor(Color.GREEN) + ; + + // Embed to send, when the bot does not have the required Permissions. + EmbedBuilder noAccountEmbed = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("Error!") + .addField("NoAccountError","Sorry, you don't have an account to unlink! Use \"" + discordCommandPrefix + "link\" to create one!") + .setColor(Color.RED) + ; + + // If the message is empty/if the arguments are none, return + if (command.getCommand() == null) + return; + + // If the command is not equal to setup, do nothing and return. + if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "unlink")) + return; + + // On wrong usage, aka. when you pass arguments. + if (command.getStringArgument(0).isPresent()) { + messageCreateEvent.getChannel().sendMessage(helpMessage); + return; + } + + // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + Logging.debug("Deleting original command message with ID: " + messageCreateEvent.getMessage().getIdAsString()); + messageCreateEvent.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( + void_ -> Logging.debug("Deleted the original command message.") + ); + } + + if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { + User user = messageCreateEvent.getMessageAuthor().asUser().get(); + + Optional optionalAccount = Account.getByDiscordUser(user); + + if (optionalAccount.isEmpty()) { + messageCreateEvent.getChannel().sendMessage(noAccountEmbed); + return; + } + + Account account = optionalAccount.get(); + + String minecraftName = account.getPlayer().getName(); + String mentionTag = account.getMentionTag(); + + AccountManager.removeAccount(account); + + successEmbed.addField("Successful Unlinking","Successfully unlinked your minecraft account \"" + minecraftName + "\" from user discord account " + mentionTag); + } else { + messageCreateEvent.getChannel().sendMessage( + new EmbedBuilder() + .setAuthor(discordApi.getYourself()) + .setTitle("Error!") + .setColor(Color.RED) + .addField("UserParsingError","You are not a user, so you can't have an account!") + ); + } + } +} From 4e965aca66a528bc92e3ff87f6b54f810e4f6c15 Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 3 May 2021 20:37:13 +0200 Subject: [PATCH 031/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20typo=20=E2=9E=95?= =?UTF-8?q?=20Added=20commentary=20to=20UnlinkListener?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/discord/commands/UnlinkListener.java | 11 +++++++++++ src/main/java/com/github/mafelp/minecraft/Main.java | 2 +- .../mafelp/minecraft/commands/AccountCommand.java | 8 ++++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java index 218d138..58085a1 100644 --- a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java @@ -18,7 +18,14 @@ import static com.github.mafelp.utils.Settings.*; +/** + * The class used to listen in discord and unlinks your account. + */ public class UnlinkListener implements MessageCreateListener { + /** + * The method that initializes the unlinking. + * @param messageCreateEvent The + */ @Override public void onMessageCreate(MessageCreateEvent messageCreateEvent) { // If the message is sent by the bot, return @@ -91,21 +98,25 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { ); } + // Only execute if te message Author is a user and not a webhook. if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { User user = messageCreateEvent.getMessageAuthor().asUser().get(); Optional optionalAccount = Account.getByDiscordUser(user); + // If the user does not have an account. if (optionalAccount.isEmpty()) { messageCreateEvent.getChannel().sendMessage(noAccountEmbed); return; } + // Get the account and some information about it. Account account = optionalAccount.get(); String minecraftName = account.getPlayer().getName(); String mentionTag = account.getMentionTag(); + // Then remove the account. AccountManager.removeAccount(account); successEmbed.addField("Successful Unlinking","Successfully unlinked your minecraft account \"" + minecraftName + "\" from user discord account " + mentionTag); diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index ace2d57..280ec6e 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -104,7 +104,7 @@ private void commandRegistration() { Logging.info("Command \"link\" has been enabled."); Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); Logging.info("Command \"account\" has been enabled."); - Objects.requireNonNull(getCommand("account")).setExecutor(new Unlink()); + Objects.requireNonNull(getCommand("unlink")).setExecutor(new Unlink()); Logging.info("Command \"unlink\" has been enabled."); } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 61cf2d7..32a349e 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -16,6 +16,7 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; +import java.util.Locale; import java.util.Objects; import java.util.Optional; @@ -42,20 +43,23 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk // If a player executed this command, we can cast the commandSender to a player. Player player = (Player) commandSender; - if (args == null) + if (args == null) { + commandSender.sendMessage(prefix + ChatColor.RED + "No arguments given into the command! Please use the following syntax."); return false; + } Command cmd; try { cmd = CommandParser.parseFromArray(args); } catch (NoCommandGivenException exception) { + commandSender.sendMessage(prefix + ChatColor.RED + "No Command given! Please use the following syntax!"); return false; } catch (CommandNotFinishedException exception) { commandSender.sendMessage(prefix + ChatColor.RED + "Could not parse your command. There is an uneven number of quotation marks. Maybe try escaping them with \\"); return true; } - switch (cmd.getCommand().toLowerCase()) { + switch (cmd.getCommand().toLowerCase(Locale.ROOT)) { case "link" -> { // Initiates the linking process. Optional optionalLinkID = cmd.getIntegerArgument(0); From d258b8af69a275ef8cc9673a80cae87b98f529fb Mon Sep 17 00:00:00 2001 From: GitHub Date: Mon, 3 May 2021 21:43:59 +0200 Subject: [PATCH 032/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20bug,=20where=20n?= =?UTF-8?q?o=20embed=20would=20be=20sent=20in=20a=20private=20channel.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/discord/commands/CreateChannelListener.java | 8 ++++---- .../mafelp/discord/commands/CreateRoleListener.java | 7 +++---- .../com/github/mafelp/discord/commands/LinkListener.java | 7 +++---- .../github/mafelp/discord/commands/SetupListener.java | 7 +++---- .../github/mafelp/discord/commands/UnlinkListener.java | 9 +++++---- 5 files changed, 18 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index 203df24..865ecbc 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -105,13 +105,13 @@ public void onMessageCreate(MessageCreateEvent event) { return; // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( - void_ -> Logging.debug("Deleted the original command message.") - ); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); + Logging.debug("Deleted the original command message."); } + // Checks the permission of the message author. if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index 37ff627..bf9052b 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -96,11 +96,10 @@ public void onMessageCreate(MessageCreateEvent event) { return; // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( - void_ -> Logging.debug("Deleted the original command message.") - ); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); + Logging.debug("Deleted the original command message."); } // Checks the permission of the message author. diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index 54de9ae..3784e2f 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -60,11 +60,10 @@ public void onMessageCreate(MessageCreateEvent event) { } // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( - void_ -> Logging.debug("Deleted the original command message.") - ); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); + Logging.debug("Deleted the original command message."); } // Tries to parse the message author into a user. If this fails, don't execute this command. diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index c0d1ce2..e6f4188 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -109,11 +109,10 @@ public void onMessageCreate(MessageCreateEvent event) { return; // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( - void_ -> Logging.debug("Deleted the original command message.") - ); + event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); + Logging.debug("Deleted the original command message."); } // Checks the permission of the message author. diff --git a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java index 58085a1..08ef744 100644 --- a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java @@ -91,11 +91,10 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { } // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages")) { + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && messageCreateEvent.isServerMessage()) { Logging.debug("Deleting original command message with ID: " + messageCreateEvent.getMessage().getIdAsString()); - messageCreateEvent.getMessage().delete("Specified in MCDC configuration: Was a command message.").thenAcceptAsync( - void_ -> Logging.debug("Deleted the original command message.") - ); + messageCreateEvent.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); + Logging.debug("Deleted the original command message."); } // Only execute if te message Author is a user and not a webhook. @@ -120,6 +119,8 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { AccountManager.removeAccount(account); successEmbed.addField("Successful Unlinking","Successfully unlinked your minecraft account \"" + minecraftName + "\" from user discord account " + mentionTag); + + messageCreateEvent.getChannel().sendMessage(successEmbed); } else { messageCreateEvent.getChannel().sendMessage( new EmbedBuilder() From 6c6bcfe8ad0e2eb3deea18fb3b3d1931055fa861 Mon Sep 17 00:00:00 2001 From: GitHub Date: Tue, 4 May 2021 22:05:18 +0200 Subject: [PATCH 033/158] =?UTF-8?q?=E2=9E=95=20Added=20more=20debug=20and?= =?UTF-8?q?=20info=20statements=20into=20the=20console=20output.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/commands/UnlinkListener.java | 7 +++++++ .../github/mafelp/minecraft/commands/AccountCommand.java | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java index 08ef744..77dcab3 100644 --- a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java @@ -99,29 +99,36 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { // Only execute if te message Author is a user and not a webhook. if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { + Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" executed command \"unlink\". Parsing User..."); User user = messageCreateEvent.getMessageAuthor().asUser().get(); Optional optionalAccount = Account.getByDiscordUser(user); // If the user does not have an account. if (optionalAccount.isEmpty()) { + Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" does not have an account to unlink... Sending noAccountEmbed..."); messageCreateEvent.getChannel().sendMessage(noAccountEmbed); return; } + Logging.debug("Getting the account for user \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\"..."); // Get the account and some information about it. Account account = optionalAccount.get(); String minecraftName = account.getPlayer().getName(); String mentionTag = account.getMentionTag(); + String username = account.getUsername(); + Logging.info("Removing account \"" + username + "\"..."); // Then remove the account. AccountManager.removeAccount(account); successEmbed.addField("Successful Unlinking","Successfully unlinked your minecraft account \"" + minecraftName + "\" from user discord account " + mentionTag); + Logging.info("Removed account \"" + username + "\"... Sending success embed..."); messageCreateEvent.getChannel().sendMessage(successEmbed); } else { + Logging.debug("MessageAuthor \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" is not a User! Sending Error embed..."); messageCreateEvent.getChannel().sendMessage( new EmbedBuilder() .setAuthor(discordApi.getYourself()) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 32a349e..668e262 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -48,6 +48,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return false; } + Logging.info("Player " + player.getDisplayName() + " has executed command \"/account\"... Parsing subcommands..."); Command cmd; try { cmd = CommandParser.parseFromArray(args); @@ -61,26 +62,31 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk switch (cmd.getCommand().toLowerCase(Locale.ROOT)) { case "link" -> { + Logging.debug("Subcommand is link."); // Initiates the linking process. Optional optionalLinkID = cmd.getIntegerArgument(0); // If no link token was given, create one and send it to the player. if (optionalLinkID.isEmpty()) { + Logging.debug("Link ID is empty... Sending link token."); Link.sendLinkToken(player); return true; } + Logging.debug("Linking accounts..."); // If a link token was given, try to link the accounts with the token. Optional linkedAccount = DiscordLinker.linkToMinecraft(player, optionalLinkID.get()); // If the account is empty, the linkToken was invalid. Inform the user. if (linkedAccount.isEmpty()) { commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, your Link token is invalid. Please try again or use " + ChatColor.GRAY + "/link" + ChatColor.RESET + " to get a link token and instructions."); + Logging.info("Linking failed: Link token is invalid!"); return true; } // If the account isPresent, the token was valid and an account was being created. commandSender.sendMessage(prefix + ChatColor.GREEN + "Successfully linked this player account to the discord user " + linkedAccount.get().getUsername()); + Logging.info("Linked Minecraft account " + linkedAccount.get().getPlayer().getName() + " to Discord user " + linkedAccount.get().getUser().getName() + "\""); return true; } // Sets you username @@ -97,6 +103,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } + Logging.debug("Player " + player.getName() + " requested a name change."); // Validate the inputted string String inputName = cmd.getStringArgument(0).get(); @@ -124,12 +131,14 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk // Gets the account and sets its username. Account account = Account.getByPlayer(player).get(); + Logging.info("Player " + player.getName() + " changed its username from " + account.getUsername() + " to " + nameToSet + "."); account.setUsername(nameToSet); commandSender.sendMessage(prefix + "Your username has been set to " + Account.getByPlayer(player).get().getUsername()); return true; } // The subcommand used to get your/another players account name. case "get" -> { + Logging.debug("Player " + commandSender.getName() + " executed subcommand \"get\"."); // If no additional arguments were passed, give the player his/her account name. if (cmd.getStringArgument(0).isEmpty()) { if (Account.getByPlayer(player).isEmpty()) { From f5fb39dbbd9acf2e9f2ced5e107e62d4e3c981d9 Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 8 May 2021 21:54:34 +0200 Subject: [PATCH 034/158] =?UTF-8?q?=E2=9E=95=20Added=20showing=20of=20acti?= =?UTF-8?q?vities=20in=20the=20discord=20interface.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defaultConfiguration.yml | 10 ++++++++++ .../com/github/mafelp/discord/DiscordMain.java | 15 +++++++++++++-- .../java/com/github/mafelp/utils/Settings.java | 3 +++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 484f4be..7fbb4f8 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -45,6 +45,16 @@ allowListAllAccounts: true # Allowed values showFooterInMessages: true +# The value that should be displayed below the name +activity: + # If the bot should have an activity. + enabled: true + # The type of the message, aka. the first word: + # can be set to custom, competing, listening, watching, streaming or playing + type: listening + # The text that should be displayed. + message: "your messages 👀" + # Permission section for setting permission levels permission: # The permissions on linking and editing accounts. diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 2b09f96..27e9442 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -6,11 +6,14 @@ import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; import org.javacord.api.DiscordApiBuilder; +import org.javacord.api.entity.activity.ActivityType; import org.javacord.api.entity.permission.PermissionType; import org.javacord.api.entity.permission.Permissions; import org.javacord.api.entity.permission.PermissionsBuilder; -import java.io.IOException; +import java.io.*; +import java.util.Locale; +import java.util.Objects; import java.util.concurrent.CompletionException; import static com.github.mafelp.utils.Settings.discordApi; @@ -89,7 +92,6 @@ public void run() { .addListener(UnlinkListener::new) // log the bot in and join the servers .login().join(); - // TODO Add: activity Logging.info(ChatColor.GREEN + "Successfully started the discord instance!"); Logging.info(ChatColor.RESET + "The bot invitation token is: " + discordApi.createBotInvite(botPermissions)); @@ -101,6 +103,15 @@ public void run() { return; } + // Checks the configuration and sets the according activity. + if (Settings.getConfiguration().getBoolean("activity.enabled", true)) { + String activityMessage = Objects.requireNonNull(Settings.getConfiguration().getString("activity.message", "to your messages 👀")); + String activityType = Objects.requireNonNull(Settings.getConfiguration().getString("activity.type", "listening")).toUpperCase(Locale.ROOT); + + discordApi.updateActivity(ActivityType.valueOf(activityType), activityMessage); + Logging.info("Set the activity to type " + ChatColor.GRAY + activityType + ChatColor.RESET + " and the text to " + ChatColor.GRAY + activityMessage + ChatColor.RESET + "."); + } + if (this.loadAccounts) { // Loads all the Accounts to memory try { diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 3018983..f1117d1 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -252,6 +252,9 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("deleteDiscordCommandMessages", false); defaultConfiguration.set("allowListAllAccounts", true); defaultConfiguration.set("showFooterInMessages", true); + defaultConfiguration.set("activity.enabled", true); + defaultConfiguration.set("activity.type", "listening"); + defaultConfiguration.set("activity.message", "to your messages 👀"); defaultConfiguration.set("permission.accountEdit.level", 3); defaultConfiguration.set("permission.accountEdit.allowedUserUUIDs", new ArrayList()); defaultConfiguration.set("permission.configEdit.level", 3); From 849265b483d91d65bc473aa45103b90e0e6103c5 Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 8 May 2021 22:29:52 +0200 Subject: [PATCH 035/158] =?UTF-8?q?=E2=96=B6=20Started=20adding=20whisper?= =?UTF-8?q?=20commands.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 1 + .../discord/commands/WhisperListener.java | 175 ++++++++++++++++++ .../com/github/mafelp/minecraft/Main.java | 2 + .../mafelp/minecraft/commands/Whisper.java | 16 ++ src/main/resources/plugin.yml | 7 +- 5 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/github/mafelp/discord/commands/WhisperListener.java create mode 100644 src/main/java/com/github/mafelp/minecraft/commands/Whisper.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 27e9442..eae6f0b 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -90,6 +90,7 @@ public void run() { .addListener(SetupListener::new) .addListener(LinkListener::new) .addListener(UnlinkListener::new) + .addListener(WhisperListener::new) // log the bot in and join the servers .login().join(); diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java new file mode 100644 index 0000000..2e971c5 --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -0,0 +1,175 @@ +package com.github.mafelp.discord.commands; + +import com.github.mafelp.accounts.Account; +import com.github.mafelp.utils.Command; +import com.github.mafelp.utils.CommandParser; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; +import com.github.mafelp.utils.exceptions.CommandNotFinishedException; +import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import org.bukkit.entity.Player; +import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.message.MessageCreateEvent; +import org.javacord.api.listener.message.MessageCreateListener; + +import java.awt.*; +import java.util.Optional; + +import static com.github.mafelp.utils.Settings.discordApi; +import static com.github.mafelp.utils.Settings.discordCommandPrefix; + +public class WhisperListener implements MessageCreateListener { + /** + * The method that initializes the unlinking. + * @param messageCreateEvent The + */ + @Override + public void onMessageCreate(MessageCreateEvent messageCreateEvent) { + // If the message is sent by the bot, return + if (messageCreateEvent.getMessageAuthor().isYourself()) { + return; + } + + // If message does not start with the command prefix, return + // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || + // event.getReadableMessageContent() == null) + // return; + + + // Gets the content of the message as strings (prints it, if debug is enabled) + String content = messageCreateEvent.getReadableMessageContent(); + + // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. + Command command; + try { + command = CommandParser.parseFromString(content); + } catch (CommandNotFinishedException | NoCommandGivenException e) { + // Logging.logException(e, "Error parsing hte command from the string..."); + return; + } + + // help message for wrong usage + EmbedBuilder helpMessage = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("Error") + .addField("Usage", discordCommandPrefix + "whisper") + .addField("Functionality", "Unlinks your discord account from your minecraft account.") + .setColor(new Color(0xFFB500)) + .setFooter("Help message for command \"unlink\"") + ; + + // Embed to send, when the bot does not have the required Permissions. + EmbedBuilder noAccountEmbed = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("Error!") + .setColor(Color.RED) + ; + + // If the message is empty/if the arguments are none, return + if (command.getCommand() == null) + return; + + // If the command is not equal to setup, do nothing and return. + if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "whisper") || !command.getCommand().equalsIgnoreCase(discordCommandPrefix + "mcmsg")) + return; + + // On wrong usage, aka. when you pass arguments. + if (command.getStringArgument(0).isEmpty()) { + messageCreateEvent.getChannel().sendMessage(helpMessage); + return; + } + + // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages + if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && messageCreateEvent.isServerMessage()) { + Logging.debug("Deleting original command message with ID: " + messageCreateEvent.getMessage().getIdAsString()); + messageCreateEvent.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); + Logging.debug("Deleted the original command message."); + } + + // Only execute if te message Author is a user and not a webhook. + if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { + // noAccountEmbed.addField("","Sorry, user with tag " + ); + Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" executed command \"unlink\". Parsing User..."); + User user = messageCreateEvent.getMessageAuthor().asUser().get(); + + Optional optionalSenderAccount = Account.getByDiscordUser(user); + + // If the user does not have an account. + if (optionalSenderAccount.isEmpty()) { + Logging.debug("User does not have an account. Sending no account Embed."); + noAccountEmbed.addField("You don't have account!", "You can only whisper, when you have an account! Use \"" + discordCommandPrefix + "link\" to create one!"); + messageCreateEvent.getChannel().sendMessage(noAccountEmbed); + return; + } + + StringBuilder userID = new StringBuilder(); + for (char c: command.getStringArgument(0).get().toCharArray()) { + if (c != '<' && c != '>' && c != '!' && c != '@') + userID.append(c); + } + + try { + User userReceiver = discordApi.getUserById(Long.getLong(userID.toString())).join(); + + if (userReceiver == null) { + Logging.debug("Could not get user by ID " + userID); + noAccountEmbed.addField("NoSuchUser","No Discord Account could be found for the user with ID " + userID); + return; + } + + Optional optionalReceiverAccount = Account.getByDiscordUser(userReceiver); + Logging.debug("Getting the account for user \"" + command.getStringArgument(0).get() + "\"..."); + // Get the account and some information about it. + if (optionalReceiverAccount.isEmpty()) { + Logging.debug("Discord User " + userReceiver.getName() + " does not have an account. Sending noAccountEmbed."); + noAccountEmbed.addField("No Account", "Discord user " + userReceiver.getName() + " does not have a linked minecraft account. They should use \"" + discordCommandPrefix + "link\" to get one!"); + return; + } + Account account = optionalReceiverAccount.get(); + + Player player = account.getPlayer().getPlayer(); + if (!account.getPlayer().isOnline() || player == null) { + EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("PlayerNotOnlineError") + .setColor(Color.RED) + .addField("Player Not Online","You cannot whisper to an offline player!") + ; + + messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); + Logging.debug("Player not online. Cannot whisper message."); + return; + } + + if (command.getStringArgument(1).isEmpty()) { + EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("notEnoughArguments") + .setColor(Color.RED) + .addField("","") + ; + + messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); + Logging.debug("Player not online. Cannot whisper message."); + return; + } + + player.sendMessage(command.getStringArgument(1).get()); + + } catch (NumberFormatException ex) { + messageCreateEvent.getChannel().sendMessage(helpMessage); + Logging.debug("Wrong usage of Discord Whisper command. Sending help embed..."); + } + } else { + Logging.debug("MessageAuthor \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" is not a User! Sending Error embed..."); + messageCreateEvent.getChannel().sendMessage( + new EmbedBuilder() + .setAuthor(discordApi.getYourself()) + .setTitle("Error!") + .setColor(Color.RED) + .addField("UserParsingError","You are not a user, so you can't have an account!") + ); + } + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 280ec6e..af8f86c 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -106,6 +106,8 @@ private void commandRegistration() { Logging.info("Command \"account\" has been enabled."); Objects.requireNonNull(getCommand("unlink")).setExecutor(new Unlink()); Logging.info("Command \"unlink\" has been enabled."); + Objects.requireNonNull(getCommand("whisper")).setExecutor(new Whisper()); + Logging.info("Command \"whisper\" has been enabled."); } } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java b/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java new file mode 100644 index 0000000..3696d42 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java @@ -0,0 +1,16 @@ +package com.github.mafelp.minecraft.commands; + +import com.github.mafelp.utils.Settings; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; + +public class Whisper implements CommandExecutor { + @Override + public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + commandSender.sendMessage(Settings.prefix + ChatColor.RED + "Sorry, this command is currently not available!"); + return true; + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 504d6ab..e67c8c3 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -23,4 +23,9 @@ commands: usage: /account [] unlink: description: The command used to remove your account. - usage: /unlink \ No newline at end of file + usage: /unlink + whisper: + description: The command to whisper to a discord user. + usage: /whisper @AccountTag "" + aliases: + - dcmsg \ No newline at end of file From 88f71d87c4e2df4ab97031a29f65e58b8f3c8b2a Mon Sep 17 00:00:00 2001 From: GitHub Date: Sat, 8 May 2021 22:42:27 +0200 Subject: [PATCH 036/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20the=20message=20would=20not=20be=20deleted=20on=20wrong=20us?= =?UTF-8?q?age.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/discord/commands/UnlinkListener.java | 11 ++++++----- .../mafelp/discord/commands/WhisperListener.java | 16 ++++++++-------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java index 77dcab3..126cca8 100644 --- a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java @@ -84,11 +84,6 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "unlink")) return; - // On wrong usage, aka. when you pass arguments. - if (command.getStringArgument(0).isPresent()) { - messageCreateEvent.getChannel().sendMessage(helpMessage); - return; - } // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && messageCreateEvent.isServerMessage()) { @@ -97,6 +92,12 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Logging.debug("Deleted the original command message."); } + // On wrong usage, aka. when you pass arguments. + if (command.getStringArgument(0).isPresent()) { + messageCreateEvent.getChannel().sendMessage(helpMessage); + return; + } + // Only execute if te message Author is a user and not a webhook. if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" executed command \"unlink\". Parsing User..."); diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index 2e971c5..1c8594a 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -54,7 +54,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { .setAuthor(messageCreateEvent.getMessageAuthor()) .setTitle("Error") .addField("Usage", discordCommandPrefix + "whisper") - .addField("Functionality", "Unlinks your discord account from your minecraft account.") + .addField("Functionality", "Whispers your message to the .") .setColor(new Color(0xFFB500)) .setFooter("Help message for command \"unlink\"") ; @@ -71,15 +71,9 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { return; // If the command is not equal to setup, do nothing and return. - if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "whisper") || !command.getCommand().equalsIgnoreCase(discordCommandPrefix + "mcmsg")) + if (!(command.getCommand().equalsIgnoreCase(discordCommandPrefix + "whisper") || command.getCommand().equalsIgnoreCase(discordCommandPrefix + "mcmsg"))) return; - // On wrong usage, aka. when you pass arguments. - if (command.getStringArgument(0).isEmpty()) { - messageCreateEvent.getChannel().sendMessage(helpMessage); - return; - } - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && messageCreateEvent.isServerMessage()) { Logging.debug("Deleting original command message with ID: " + messageCreateEvent.getMessage().getIdAsString()); @@ -87,6 +81,12 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Logging.debug("Deleted the original command message."); } + // On wrong usage, aka. when you pass arguments. + if (command.getStringArgument(0).isEmpty()) { + messageCreateEvent.getChannel().sendMessage(helpMessage); + return; + } + // Only execute if te message Author is a user and not a webhook. if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { // noAccountEmbed.addField("","Sorry, user with tag " + ); From 918029af0f810b5d29565e7a38c7b20baa59051c Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Wed, 12 May 2021 12:26:51 +0200 Subject: [PATCH 037/158] =?UTF-8?q?=E2=9E=95=20Added=20whispering=20from?= =?UTF-8?q?=20discord=20to=20minecraft.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../discord/commands/WhisperListener.java | 135 ++++++++++++------ 1 file changed, 89 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index 1c8594a..13f8ecf 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -7,6 +7,8 @@ import com.github.mafelp.utils.Settings; import com.github.mafelp.utils.exceptions.CommandNotFinishedException; import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.User; @@ -19,6 +21,9 @@ import static com.github.mafelp.utils.Settings.discordApi; import static com.github.mafelp.utils.Settings.discordCommandPrefix; +/** + * The class that handles whispering on the discord side of things. + */ public class WhisperListener implements MessageCreateListener { /** * The method that initializes the unlinking. @@ -53,10 +58,11 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { EmbedBuilder helpMessage = new EmbedBuilder() .setAuthor(messageCreateEvent.getMessageAuthor()) .setTitle("Error") - .addField("Usage", discordCommandPrefix + "whisper") - .addField("Functionality", "Whispers your message to the .") + .addField("Usage", discordCommandPrefix + "whisper <@account name> \"\"") + .addField("Alternative usage", discordCommandPrefix + "whister <@discord name> \"\"") + .addField("Functionality", "Whispers your message to the minecraft account of the receiver.") .setColor(new Color(0xFFB500)) - .setFooter("Help message for command \"unlink\"") + .setFooter("Help message for command \"whisper\"") ; // Embed to send, when the bot does not have the required Permissions. @@ -81,6 +87,19 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Logging.debug("Deleted the original command message."); } + // Only lets this command be executed with a private message or in a group of people. + if (messageCreateEvent.isPrivateMessage() || messageCreateEvent.isGroupMessage()) { + EmbedBuilder notAPrivateMessage = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("Error!") + .setColor(Color.RED) + .addField("Not a private message error", "This command can only be used via direct message or in group messages with this bot.") + ; + + messageCreateEvent.getChannel().sendMessage(notAPrivateMessage); + return; + } + // On wrong usage, aka. when you pass arguments. if (command.getStringArgument(0).isEmpty()) { messageCreateEvent.getChannel().sendMessage(helpMessage); @@ -109,58 +128,82 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { userID.append(c); } - try { - User userReceiver = discordApi.getUserById(Long.getLong(userID.toString())).join(); - - if (userReceiver == null) { - Logging.debug("Could not get user by ID " + userID); - noAccountEmbed.addField("NoSuchUser","No Discord Account could be found for the user with ID " + userID); + Account receiver; + Optional optionalAccount = Account.getByUsername(command.getStringArgument(0).get()); + + if (optionalAccount.isPresent()){ + receiver = optionalAccount.get(); + Logging.debug("Found Account with tag " + receiver.getUsername()); + } else { + try { + User userReceiver = discordApi.getUserById(Long.getLong(userID.toString())).join(); + + if (userReceiver == null) { + Logging.debug("Could not get user by ID " + userID); + noAccountEmbed.addField("NoSuchUser", "No Discord Account could be found for the user with ID " + userID); + return; + } + + Optional optionalReceiverAccount = Account.getByDiscordUser(userReceiver); + Logging.debug("Getting the account for user \"" + command.getStringArgument(0).get() + "\"..."); + // Get the account and some information about it. + if (optionalReceiverAccount.isEmpty()) { + Logging.debug("Discord User " + userReceiver.getName() + " does not have an account. Sending noAccountEmbed."); + noAccountEmbed.addField("No Account", "Discord user " + userReceiver.getName() + " does not have a linked minecraft account. They should use \"" + discordCommandPrefix + "link\" to get one!"); + return; + } + receiver = optionalReceiverAccount.get(); + + } catch (NumberFormatException ex) { + messageCreateEvent.getChannel().sendMessage(helpMessage); + Logging.debug("Wrong usage of Discord Whisper command. Sending help embed..."); return; } + } - Optional optionalReceiverAccount = Account.getByDiscordUser(userReceiver); - Logging.debug("Getting the account for user \"" + command.getStringArgument(0).get() + "\"..."); - // Get the account and some information about it. - if (optionalReceiverAccount.isEmpty()) { - Logging.debug("Discord User " + userReceiver.getName() + " does not have an account. Sending noAccountEmbed."); - noAccountEmbed.addField("No Account", "Discord user " + userReceiver.getName() + " does not have a linked minecraft account. They should use \"" + discordCommandPrefix + "link\" to get one!"); - return; - } - Account account = optionalReceiverAccount.get(); + EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() + .setAuthor(messageCreateEvent.getMessageAuthor()) + .setTitle("PlayerNotOnlineError") + .setColor(Color.RED) + .addField("Player Not Online", "You cannot whisper to an offline player!"); - Player player = account.getPlayer().getPlayer(); - if (!account.getPlayer().isOnline() || player == null) { - EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) - .setTitle("PlayerNotOnlineError") - .setColor(Color.RED) - .addField("Player Not Online","You cannot whisper to an offline player!") - ; + OfflinePlayer player = receiver.getPlayer(); + if (player == null || !receiver.getPlayer().isOnline()) { + messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); + Logging.debug("Player not online. Cannot whisper message."); + return; + } - messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); - Logging.debug("Player not online. Cannot whisper message."); - return; - } + Player onlinePlayer = player.getPlayer(); + if (onlinePlayer == null) { + messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); + Logging.debug("Player not online. Cannot whisper message."); + return; + } - if (command.getStringArgument(1).isEmpty()) { - EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) - .setTitle("notEnoughArguments") - .setColor(Color.RED) - .addField("","") - ; + if (command.getStringArgument(1).isEmpty()) { + messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); + Logging.debug("Player not online. Cannot whisper message."); + return; + } - messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); - Logging.debug("Player not online. Cannot whisper message."); - return; - } + Logging.debug("Building whisper message..."); + StringBuilder messageBuilder = new StringBuilder(); + for (int i = 1; i < command.getArguments().length; ++i) { + if (i != 1) + messageBuilder.append(' '); + Optional messagePart = command.getStringArgument(i); + if (messagePart.isPresent()) + messageBuilder.append(messagePart.get()); + else + break; + } - player.sendMessage(command.getStringArgument(1).get()); + String message = messageBuilder.toString(); - } catch (NumberFormatException ex) { - messageCreateEvent.getChannel().sendMessage(helpMessage); - Logging.debug("Wrong usage of Discord Whisper command. Sending help embed..."); - } + Logging.debug("Whisper message built! Sending it..."); + Logging.info("User " + ChatColor.GRAY + messageCreateEvent.getMessageAuthor().getDisplayName() + ChatColor.RESET + "whispered the following to minecraft user " + ChatColor.GRAY + onlinePlayer.getDisplayName() + ChatColor.RESET + ": " + ChatColor.AQUA + message); + onlinePlayer.sendMessage(message); } else { Logging.debug("MessageAuthor \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" is not a User! Sending Error embed..."); messageCreateEvent.getChannel().sendMessage( From 689a3859e6af8e794c5541a25aca18a207035d81 Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Thu, 13 May 2021 21:20:17 +0200 Subject: [PATCH 038/158] =?UTF-8?q?=E2=9E=95=20Added=20whispering=20from?= =?UTF-8?q?=20minecraft=20to=20discord.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/minecraft/commands/Whisper.java | 108 +++++++++++++++++- 1 file changed, 107 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java b/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java index 3696d42..08af2cc 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java @@ -1,16 +1,122 @@ package com.github.mafelp.minecraft.commands; +import com.github.mafelp.accounts.Account; +import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.javacord.api.entity.message.Message; +import org.javacord.api.entity.message.embed.EmbedBuilder; import org.jetbrains.annotations.NotNull; +import java.awt.*; +import java.util.Objects; +import java.util.Optional; + +import static com.github.mafelp.utils.Settings.prefix; + +/** + * The class that handles execution of the command /whisper + */ public class Whisper implements CommandExecutor { + /** + * The Method called when command /token is executed. + * + * @param commandSender The sender of the command + * @param command the command he/she used + * @param label the label of the command + * @param args additional arguments passed: Discord ID and unique identifier. + * @return command success + */ @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - commandSender.sendMessage(Settings.prefix + ChatColor.RED + "Sorry, this command is currently not available!"); + // Only lets players execute this command + if (!(commandSender instanceof Player)) { + Logging.debug("CommandSender " + commandSender.getName() + " is not a user and can therefore not whisper to accounts..."); + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you can only execute this command as a player!"); + return true; + } + + Player player = (Player) commandSender; + + // Checks if the command sender has an account. + if (Account.getByPlayer(player).isEmpty()) { + Logging.debug("Player " + commandSender.getName() + " does not have an account. They are not allowed to whisper!"); + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are only allowed to whisper, if you have an account. Use \"/link\" to get one!"); + return true; + } + + // Try to parse the first argument into an account name. + // All the other arguments are going to get parsed into an argument. + Logging.debug("Parsing whisper message..."); + boolean isReceiver = true; + boolean firstWord = true; + String receiverString = ""; + StringBuilder messageBuilder = new StringBuilder(); + for (String s : + args) { + if (isReceiver) { + isReceiver = false; + receiverString = s; + } else { + if (!firstWord) + messageBuilder.append(' '); + else + firstWord = false; + messageBuilder.append(s); + } + } + String message = messageBuilder.toString(); + + // Try to get the account. + Optional optionalAccount = Account.getByUsername(receiverString); + Account receiver; + Logging.debug("Trying to parse the receiver account."); + if (optionalAccount.isPresent()) { + Logging.debug("Account parsing complete! Found an Account tag."); + receiver = optionalAccount.get(); + } else { + Logging.debug("Not an account tag. Trying to parse from minecraft name."); + StringBuilder receiverBuilder = new StringBuilder(); + for (char c : receiverString.toCharArray()) { + if (c != '@') + receiverBuilder.append(c); + else + Logging.debug("Removed leading @"); + } + String receiverBuilt = receiverBuilder.toString(); + + Logging.debug("Scanning offline players..."); + for (OfflinePlayer p : Settings.minecraftServer.getOfflinePlayers()) { + if (Objects.equals(p.getName(), receiverBuilt)) + optionalAccount = Account.getByPlayer(p); + } + + if (optionalAccount.isPresent()){ + receiver = optionalAccount.get(); + } else { + Logging.debug("Account " + receiverString + " is not a minecraft, nor an account name."); + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, no account with account tag \"" + receiverString + "\" found!"); + return true; + } + } + + EmbedBuilder messageEmbed = new EmbedBuilder() + .setAuthor(Account.getByPlayer(player).get().getUser()) + .setColor(Color.YELLOW) + .setTitle("Whisper Message from " + commandSender.getName()) + .setDescription(message) + .setFooter("On " + Settings.serverName); + + Logging.debug("Sending whisper message to " + receiver.getUsername() + "..."); + Message messageSent = receiver.getUser().sendMessage(messageEmbed).join(); + + Logging.info(ChatColor.GRAY + player.getName() + ChatColor.RESET + " has whispered to account " + ChatColor.GRAY + receiver.getUsername() + ChatColor.RESET + ": " + ChatColor.GRAY + message); + Logging.debug("This message has the id: " + messageSent.getId()); return true; } } From bb8e2f08b1114bb2333a517cf57ecdb8b9de9c33 Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Thu, 13 May 2021 21:22:12 +0200 Subject: [PATCH 039/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20t?= =?UTF-8?q?he=20unlink=20command.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/commands/Unlink.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java b/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java index 0126af1..b8fd7da 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java @@ -15,7 +15,19 @@ import static com.github.mafelp.utils.Settings.prefix; import static org.bukkit.ChatColor.*; +/** + * The class that handles execution of the command /unlink + */ public class Unlink implements CommandExecutor { + /** + * The Method called when command /unlink is executed. + * + * @param commandSender The sender of the command + * @param command the command he/she used + * @param label the label of the command + * @param args additional arguments passed: Discord ID and unique identifier. + * @return command success + */ @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, String[] args) { // Only players can have accounts. From 52a81f90f39f53f0a43929cd733119172642012c Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Thu, 13 May 2021 21:23:32 +0200 Subject: [PATCH 040/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20an=20IntelliJ=20?= =?UTF-8?q?error=20with=20the=20annotations=20dependency.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 32a1bb8..dc685ac 100644 --- a/pom.xml +++ b/pom.xml @@ -94,7 +94,7 @@ org.jetbrains annotations - RELEASE + 20.1.0 compile From fc4592d3ee1e9b88db8b6383516110d405de3bcc Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Thu, 13 May 2021 22:01:13 +0200 Subject: [PATCH 041/158] =?UTF-8?q?=E2=9E=95=20Added=20character=20and=20l?= =?UTF-8?q?ength=20check=20to=20the=20account=20name=20changing.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 67 ++++++++++++------- 1 file changed, 42 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 668e262..58de8fb 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -90,6 +90,8 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } // Sets you username + // TODO add checking of username to not be used by anybody else. + // TODO add checking of username to not be a minecraft username. case "name", "username" -> { Logging.debug("Minecraft user " + player.getName() + " used the command \"/account " + cmd.getCommand() + " " + Arrays.toString(cmd.getArguments())); if (Account.getByPlayer(player).isEmpty()) { @@ -107,7 +109,9 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk // Validate the inputted string String inputName = cmd.getStringArgument(0).get(); + Logging.debug("Checking for wrong characters in requested name."); char[] chars = inputName.toCharArray(); + char[] forbiddenCharacters = {'\\', ' ', '"', '\'', '<', '>', '#', '!', '$', '%', '^', '&', '*', '(', ')', '+', '=', '[', ']', '{', '}', ';', ':', '?', '/'}; int i = 0; for (char c : chars) { @@ -115,12 +119,16 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are not allowed to have \"@\" in your name!"); return true; } - if (c == ' ') { - commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are not allowed to have spaces in your name!"); - return true; + + for (char forbidden : forbiddenCharacters) { + if (forbidden == c) { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are not allowed to have these characters in your name: \\ \"'<>#!@$%^&*()_/+=[]{}|"); + } } + i++; } + Logging.debug("The requested name for " + player.getName() + " has passed the character check!"); // If the first character is an @, do not add one to the start of the name. String nameToSet; @@ -129,6 +137,14 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk else nameToSet = '@' + inputName; + // Checks if the input name meets the specific requirements. + Logging.debug("Checking for name length..."); + if (nameToSet.length() >= 33) { + Logging.debug("Name did not pass the length check!"); + commandSender.sendMessage(prefix + ChatColor.RED + "Your name is too long! The limit is 32 characters!"); + return true; + } + // Gets the account and sets its username. Account account = Account.getByPlayer(player).get(); Logging.info("Player " + player.getName() + " changed its username from " + account.getUsername() + " to " + nameToSet + "."); @@ -179,12 +195,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk // Removes an account, if the player has the required permissions. case "remove" -> { // If the user does not have te required permissions, exit. - if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { - commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + - prefix + "This incident will be reported!"); - Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); - return true; - } + if (incidentReport(commandSender, cmd)) return true; // Checks if enough arguments were passed. if (cmd.getStringArgument(0).isEmpty()) { @@ -223,12 +234,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk // The subcommand used to save the accounts file. case "save" -> { // If the user does not have te required permissions, exit. - if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { - commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + - prefix + "This incident will be reported!"); - Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); - return true; - } + if (incidentReport(commandSender, cmd)) return true; try { commandSender.sendMessage(prefix + ChatColor.YELLOW + "Saving accounts file..."); @@ -245,12 +251,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk // The subcommand used to reload the accounts file into memory. case "reload" -> { // If the user does not have te required permissions, exit. - if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { - commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + - prefix + "This incident will be reported!"); - Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); - return true; - } + if (incidentReport(commandSender, cmd)) return true; // Try to reload the accounts try { @@ -274,15 +275,15 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk if (allowed) { String sb = ""; - sb += prefix + ChatColor.GREEN + "---Linked Accounts---\n" + ChatColor.RESET; - sb += ChatColor.DARK_GRAY + "+===========================+\n" + ChatColor.RESET; + sb += prefix + ChatColor.GREEN + "--------Linked Accounts--------\n" + ChatColor.RESET; + sb += ChatColor.DARK_GRAY + "+================================================+\n" + ChatColor.RESET; sb += ChatColor.YELLOW + "Minecraft Name; Discord Username; Discord Ping Tag\n" + ChatColor.RESET; - sb += ChatColor.DARK_GRAY + "+===========================+\n" + ChatColor.RESET; + sb += ChatColor.DARK_GRAY + "+================================================+\n" + ChatColor.RESET; for (Account a : AccountManager.getLinkedAccounts()) sb += ChatColor.AQUA + a.getPlayer().getName() + "; " + a.getUser().getName() + "; " + a.getUsername() + "\n"; - sb += ChatColor.DARK_GRAY + "+===========================+" + ChatColor.RESET; + sb += ChatColor.DARK_GRAY + "+================================================+" + ChatColor.RESET; commandSender.sendMessage(sb); } else { @@ -323,4 +324,20 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } } + + /** + * The method used to check the {@link com.github.mafelp.utils.Permissions}: {@code accountEdit} of a command Sender. + * @param commandSender The command sender to check the permission of. + * @param cmd The command that will be shown into the console, if the permission is denied. + * @return If the permission was granted. + */ + private static boolean incidentReport(@NotNull CommandSender commandSender, Command cmd) { + if (!CheckPermission.checkPermission(Permissions.accountEdit, commandSender)) { + commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you don't have the required permissions, to execute this command!\n" + + prefix + "This incident will be reported!"); + Logging.info("Player " + ChatColor.DARK_GRAY + commandSender.getName() + ChatColor.RESET + " tried to execute the command " + ChatColor.DARK_GRAY + "account remove " + Arrays.toString(cmd.getArguments()) + ChatColor.RESET + "! This action was denied due to missing permission!"); + return true; + } + return false; + } } From 6c3b21bf1f4bf312d47311ff27b5a6f4871cea12 Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Thu, 13 May 2021 22:16:54 +0200 Subject: [PATCH 042/158] =?UTF-8?q?=E2=9E=95=20Added=20name=20availability?= =?UTF-8?q?=20check.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/commands/AccountCommand.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 58de8fb..1010e35 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -90,8 +90,6 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } // Sets you username - // TODO add checking of username to not be used by anybody else. - // TODO add checking of username to not be a minecraft username. case "name", "username" -> { Logging.debug("Minecraft user " + player.getName() + " used the command \"/account " + cmd.getCommand() + " " + Arrays.toString(cmd.getArguments())); if (Account.getByPlayer(player).isEmpty()) { @@ -145,6 +143,28 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk return true; } + // Checks if the name is taken by anybody else + Logging.debug("Checking if the name is a duplicate of another name."); + for (Account a : AccountManager.getLinkedAccounts()) { + if (a.getUsername().equalsIgnoreCase(nameToSet)) { + Logging.debug("Name failed the duplicate name check!"); + commandSender.sendMessage(prefix + ChatColor.RED + "Could not set name: Name is already taken!"); + return true; + } + } + Logging.debug("Name has passed the duplicate name check!"); + + // Checks if the name is a minecraft name, of a player, who already was online. + Logging.debug("Checking if the name is a minecraft user."); + for (OfflinePlayer offlinePlayer : Settings.minecraftServer.getOfflinePlayers()) { + if (nameToSet.equalsIgnoreCase("@" + offlinePlayer.getName())) { + Logging.debug("Name failed the minecraft name check!"); + commandSender.sendMessage(prefix + ChatColor.RED + "Could not set name: Name is a minecraft name!"); + return true; + } + } + Logging.debug("Name passed the minecraft username check!"); + // Gets the account and sets its username. Account account = Account.getByPlayer(player).get(); Logging.info("Player " + player.getName() + " changed its username from " + account.getUsername() + " to " + nameToSet + "."); From 9fad5c0f66fffeadf1e392c34c790f5327059ad6 Mon Sep 17 00:00:00 2001 From: MaFeLP Date: Thu, 13 May 2021 22:34:44 +0200 Subject: [PATCH 043/158] =?UTF-8?q?=E2=9E=95=20Added=20a=20check=20on=20th?= =?UTF-8?q?e=20player=20join,=20where=20all=20account=20usernames=20would?= =?UTF-8?q?=20be=20checked,=20if=20one=20of=20them=20is=20a=20minecraft=20?= =?UTF-8?q?username=20to=20not=20get=20duplicates.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/minecraft/JoinListener.java | 42 +++++++++++++------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/JoinListener.java b/src/main/java/com/github/mafelp/minecraft/JoinListener.java index afc6587..72f8d2f 100644 --- a/src/main/java/com/github/mafelp/minecraft/JoinListener.java +++ b/src/main/java/com/github/mafelp/minecraft/JoinListener.java @@ -1,6 +1,8 @@ package com.github.mafelp.minecraft; +import com.github.mafelp.accounts.Account; import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Permissions; import com.github.mafelp.utils.Settings; import com.github.mafelp.minecraft.skins.Skin; @@ -24,23 +26,39 @@ public class JoinListener implements Listener { @EventHandler public void onJoin(PlayerJoinEvent playerJoinEvent) { /* - * Send a welcome message to the joined player + * Send a welcome message to the joined player if he/she does not have an account. * * This message informs the player about this plugin and * informs him/her, that every messages he/she sends are * being transmitted to a discord channel. */ - playerJoinEvent.getPlayer().sendMessage( - // Adding the plugin prefix in front of the message - prefix + ChatColor.AQUA + - // Greeting the player with his/her name - "Hello " + ChatColor.GREEN + playerJoinEvent.getPlayer().getDisplayName() + ChatColor.AQUA + "!\n" + - // Adding the warning - ChatColor.RED + - " This server is using MCDC version " + Settings.version + "!\n" + - " Be aware that any chat messages that you send are going to be send to a discord channel!" + - ChatColor.RESET - ); + if (Account.getByPlayer(playerJoinEvent.getPlayer()).isEmpty()) { + playerJoinEvent.getPlayer().sendMessage( + // Adding the plugin prefix in front of the message + prefix + ChatColor.AQUA + + // Greeting the player with his/her name + "Hello " + ChatColor.GREEN + playerJoinEvent.getPlayer().getDisplayName() + ChatColor.AQUA + "!\n" + + // Adding the warning + ChatColor.RED + + " This server is using MCDC version " + Settings.version + "!\n" + + " Be aware that any chat messages that you send are going to be send to a discord channel!" + + " To create a link with your discord account, use " + ChatColor.GRAY + "/link" + + ChatColor.RESET + ); + + // This check must only be performed, when a new player has joined. New Players cannot have an account, + // so it would be useless to perform this check on players with an account. + String usernameToCheck = "@" + playerJoinEvent.getPlayer().getName(); + if (Account.getByUsername(usernameToCheck).isPresent()) { + String usernameToSet = "@" + Account.getByUsername(usernameToCheck).get().getPlayer().getName(); + Account accountToResetTheNameOf = Account.getByUsername(usernameToCheck).get(); + Account.getByUsername(usernameToCheck).get().setUsername(usernameToSet); + Logging.info("Due to a new player having joined the server with the same name as an account had, the name of the old account " + usernameToCheck + "has been reset to " + ChatColor.GRAY + usernameToSet); + if (accountToResetTheNameOf.getPlayer().getPlayer() != null && accountToResetTheNameOf.getPlayer().isOnline()) { + accountToResetTheNameOf.getPlayer().getPlayer().sendMessage(prefix + ChatColor.YELLOW + "Your account name has been reset, due to a player with the same name joining the server."); + } + } + } // Downloads the skin from Mojang new Skin(playerJoinEvent.getPlayer(), true); From 37414ee526b680d049c6cf24b5007259ae3f9f76 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 18:26:09 +0200 Subject: [PATCH 044/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20whispering=20would=20result=20in=20nothing.=20The=20cause=20?= =?UTF-8?q?was=20an=20error=20in=20parsing=20the=20Sender's=20Discord=20ID?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/discord/commands/WhisperListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index 13f8ecf..07d0b83 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -136,7 +136,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Logging.debug("Found Account with tag " + receiver.getUsername()); } else { try { - User userReceiver = discordApi.getUserById(Long.getLong(userID.toString())).join(); + User userReceiver = discordApi.getUserById(Long.parseLong(userID.toString())).join(); if (userReceiver == null) { Logging.debug("Could not get user by ID " + userID); From c88cd93c69dfd1f2c691abee7aa1ff4cbb4c6c58 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 18:27:24 +0200 Subject: [PATCH 045/158] =?UTF-8?q?=E2=9E=95=20Added=20a=20success=20messa?= =?UTF-8?q?ge=20when=20whispering=20from=20minecraft=20to=20discord.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/minecraft/commands/Whisper.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java b/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java index 08af2cc..dba1d6c 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Whisper.java @@ -115,6 +115,9 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command Logging.debug("Sending whisper message to " + receiver.getUsername() + "..."); Message messageSent = receiver.getUser().sendMessage(messageEmbed).join(); + commandSender.sendMessage(prefix + ChatColor.GREEN + "You whispered to " + ChatColor.GRAY + receiver.getUsername() + ChatColor.GREEN + ":" + + ChatColor.GRAY + "\n\u255A\u25B6" + ChatColor.RESET + message); + Logging.info(ChatColor.GRAY + player.getName() + ChatColor.RESET + " has whispered to account " + ChatColor.GRAY + receiver.getUsername() + ChatColor.RESET + ": " + ChatColor.GRAY + message); Logging.debug("This message has the id: " + messageSent.getId()); return true; From 062f69991b15557af18d032defc9c72b5567de99 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 18:42:07 +0200 Subject: [PATCH 046/158] =?UTF-8?q?=E2=9E=95=20Added=20a=20Prefix=20for=20?= =?UTF-8?q?the=20whispered=20messages=20from=20discord=20to=20minecraft.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../discord/commands/WhisperListener.java | 57 +++++++++++++++---- 1 file changed, 47 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index 07d0b83..8c926c6 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -27,6 +27,7 @@ public class WhisperListener implements MessageCreateListener { /** * The method that initializes the unlinking. + * * @param messageCreateEvent The */ @Override @@ -62,15 +63,13 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { .addField("Alternative usage", discordCommandPrefix + "whister <@discord name> \"\"") .addField("Functionality", "Whispers your message to the minecraft account of the receiver.") .setColor(new Color(0xFFB500)) - .setFooter("Help message for command \"whisper\"") - ; + .setFooter("Help message for command \"whisper\""); // Embed to send, when the bot does not have the required Permissions. EmbedBuilder noAccountEmbed = new EmbedBuilder() .setAuthor(messageCreateEvent.getMessageAuthor()) .setTitle("Error!") - .setColor(Color.RED) - ; + .setColor(Color.RED); // If the message is empty/if the arguments are none, return if (command.getCommand() == null) @@ -93,8 +92,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { .setAuthor(messageCreateEvent.getMessageAuthor()) .setTitle("Error!") .setColor(Color.RED) - .addField("Not a private message error", "This command can only be used via direct message or in group messages with this bot.") - ; + .addField("Not a private message error", "This command can only be used via direct message or in group messages with this bot."); messageCreateEvent.getChannel().sendMessage(notAPrivateMessage); return; @@ -123,7 +121,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { } StringBuilder userID = new StringBuilder(); - for (char c: command.getStringArgument(0).get().toCharArray()) { + for (char c : command.getStringArgument(0).get().toCharArray()) { if (c != '<' && c != '>' && c != '!' && c != '@') userID.append(c); } @@ -131,7 +129,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Account receiver; Optional optionalAccount = Account.getByUsername(command.getStringArgument(0).get()); - if (optionalAccount.isPresent()){ + if (optionalAccount.isPresent()) { receiver = optionalAccount.get(); Logging.debug("Found Account with tag " + receiver.getUsername()); } else { @@ -189,6 +187,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Logging.debug("Building whisper message..."); StringBuilder messageBuilder = new StringBuilder(); + messageBuilder.append(whisperPrefix(messageCreateEvent)); for (int i = 1; i < command.getArguments().length; ++i) { if (i != 1) messageBuilder.append(' '); @@ -211,8 +210,46 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { .setAuthor(discordApi.getYourself()) .setTitle("Error!") .setColor(Color.RED) - .addField("UserParsingError","You are not a user, so you can't have an account!") + .addField("UserParsingError", "You are not a user, so you can't have an account!") ); } } -} + + /** + * The method that creates a prefix for whispered messages, according to the settings.
+ * This prefix can either be a one-liner or a two-liner. + * @param messageCreateEvent The event that stores all the information about the whisper message sender. + * @return The prefix to add to the message. + */ + private static String whisperPrefix(MessageCreateEvent messageCreateEvent) { + String first; + String last; + if (Settings.shortMsg) { + first = ChatColor.DARK_GRAY + "[" + + ChatColor.LIGHT_PURPLE + "DC" + + ChatColor.DARK_GRAY + "/" + + ChatColor.GOLD; + last = ChatColor.DARK_GRAY + "]" + + ChatColor.BLACK + ": " + + ChatColor.RESET; + + } else { + first = ChatColor.GRAY + "\u2554" + + ChatColor.DARK_GRAY + "[" + + ChatColor.LIGHT_PURPLE + "DC" + + ChatColor.DARK_GRAY + "/" + + ChatColor.GOLD; + last = ChatColor.DARK_GRAY + " as " + + ChatColor.DARK_AQUA + + "Private Message" + + ChatColor.DARK_GRAY + "]" + + ChatColor.BLACK + ": " + + ChatColor.GRAY + "\n\u255A\u25B6" + + ChatColor.RESET; + + } + return first + + messageCreateEvent.getMessageAuthor().getDisplayName() + + last; + } +} \ No newline at end of file From 4d61883e67b498aeb467c72ef11e733ac31b72ee Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 19:13:58 +0200 Subject: [PATCH 047/158] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Visual=20Bug=20?= =?UTF-8?q?fix=20on=20how=20the=20private=20messages=20are=20being=20logge?= =?UTF-8?q?d.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../discord/commands/WhisperListener.java | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index 8c926c6..fa09028 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -44,7 +44,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { // Gets the content of the message as strings (prints it, if debug is enabled) - String content = messageCreateEvent.getReadableMessageContent(); + String content = messageCreateEvent.getMessageContent(); // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. Command command; @@ -187,7 +187,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { Logging.debug("Building whisper message..."); StringBuilder messageBuilder = new StringBuilder(); - messageBuilder.append(whisperPrefix(messageCreateEvent)); + for (int i = 1; i < command.getArguments().length; ++i) { if (i != 1) messageBuilder.append(' '); @@ -197,12 +197,12 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { else break; } - String message = messageBuilder.toString(); Logging.debug("Whisper message built! Sending it..."); - Logging.info("User " + ChatColor.GRAY + messageCreateEvent.getMessageAuthor().getDisplayName() + ChatColor.RESET + "whispered the following to minecraft user " + ChatColor.GRAY + onlinePlayer.getDisplayName() + ChatColor.RESET + ": " + ChatColor.AQUA + message); - onlinePlayer.sendMessage(message); + //Logging.info("User " + ChatColor.GRAY + messageCreateEvent.getMessageAuthor().getDisplayName() + ChatColor.RESET + "whispered the following to minecraft user " + ChatColor.GRAY + onlinePlayer.getDisplayName() + ChatColor.RESET + ": " + ChatColor.AQUA + message); + Settings.minecraftServer.getConsoleSender().sendMessage(whisperPrefix(messageCreateEvent, false, receiver.getUsername()) + message); + onlinePlayer.sendMessage(whisperPrefix(messageCreateEvent, true, "") + message); } else { Logging.debug("MessageAuthor \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" is not a User! Sending Error embed..."); messageCreateEvent.getChannel().sendMessage( @@ -221,8 +221,8 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { * @param messageCreateEvent The event that stores all the information about the whisper message sender. * @return The prefix to add to the message. */ - private static String whisperPrefix(MessageCreateEvent messageCreateEvent) { - String first; + private static String whisperPrefix(MessageCreateEvent messageCreateEvent, boolean playerIsReceiver, String receiver) { + String first = ""; String last; if (Settings.shortMsg) { first = ChatColor.DARK_GRAY + "[" + @@ -234,18 +234,23 @@ private static String whisperPrefix(MessageCreateEvent messageCreateEvent) { ChatColor.RESET; } else { - first = ChatColor.GRAY + "\u2554" + - ChatColor.DARK_GRAY + "[" + + if (playerIsReceiver) + first = ChatColor.GRAY + "\u2554"; + first += ChatColor.DARK_GRAY + "[" + ChatColor.LIGHT_PURPLE + "DC" + ChatColor.DARK_GRAY + "/" + ChatColor.GOLD; last = ChatColor.DARK_GRAY + " as " + ChatColor.DARK_AQUA + - "Private Message" + - ChatColor.DARK_GRAY + "]" + - ChatColor.BLACK + ": " + - ChatColor.GRAY + "\n\u255A\u25B6" + - ChatColor.RESET; + "Private Message"; + if (!playerIsReceiver) + last += ChatColor.DARK_GRAY + " to " + + ChatColor.DARK_AQUA + receiver; + last += ChatColor.DARK_GRAY + "]" + + ChatColor.BLACK + ": "; + if (playerIsReceiver) + last += ChatColor.GRAY + "\n\u255A\u25B6"; + last += ChatColor.RESET; } return first + From 2d5342e32c435860ef5d446fdfb9636bf51c2d00 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 19:18:25 +0200 Subject: [PATCH 048/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20the=20user=20would=20get=20a=20message,=20that=20his=20name?= =?UTF-8?q?=20is=20invalid=20and=20it=20was=20changed,=20even=20though=20i?= =?UTF-8?q?t=20was=20invalid.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/commands/AccountCommand.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java index 1010e35..641645a 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/AccountCommand.java @@ -121,6 +121,7 @@ public boolean onCommand(@NotNull CommandSender commandSender, @NotNull org.bukk for (char forbidden : forbiddenCharacters) { if (forbidden == c) { commandSender.sendMessage(prefix + ChatColor.RED + "Sorry, you are not allowed to have these characters in your name: \\ \"'<>#!@$%^&*()_/+=[]{}|"); + return true; } } From bef1e307a5f22c3e76d4692a6f92606598226e6c Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 19:26:50 +0200 Subject: [PATCH 049/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20the=20noAccountEmbed=20would=20not=20be=20sent=20to=20the=20?= =?UTF-8?q?channel.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/discord/commands/WhisperListener.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index fa09028..0a50ec2 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -139,6 +139,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { if (userReceiver == null) { Logging.debug("Could not get user by ID " + userID); noAccountEmbed.addField("NoSuchUser", "No Discord Account could be found for the user with ID " + userID); + messageCreateEvent.getChannel().sendMessage(noAccountEmbed); return; } @@ -148,6 +149,7 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { if (optionalReceiverAccount.isEmpty()) { Logging.debug("Discord User " + userReceiver.getName() + " does not have an account. Sending noAccountEmbed."); noAccountEmbed.addField("No Account", "Discord user " + userReceiver.getName() + " does not have a linked minecraft account. They should use \"" + discordCommandPrefix + "link\" to get one!"); + messageCreateEvent.getChannel().sendMessage(noAccountEmbed); return; } receiver = optionalReceiverAccount.get(); From 848cb875dbf52e4446c78fefb6388883d7d9a262 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 19:30:17 +0200 Subject: [PATCH 050/158] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Visual=20Bug=20?= =?UTF-8?q?fix=20in=20the=20welcome=20message.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/minecraft/JoinListener.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/JoinListener.java b/src/main/java/com/github/mafelp/minecraft/JoinListener.java index 72f8d2f..c3cc9d1 100644 --- a/src/main/java/com/github/mafelp/minecraft/JoinListener.java +++ b/src/main/java/com/github/mafelp/minecraft/JoinListener.java @@ -39,9 +39,11 @@ public void onJoin(PlayerJoinEvent playerJoinEvent) { // Greeting the player with his/her name "Hello " + ChatColor.GREEN + playerJoinEvent.getPlayer().getDisplayName() + ChatColor.AQUA + "!\n" + // Adding the warning - ChatColor.RED + + ChatColor.GOLD + " This server is using MCDC version " + Settings.version + "!\n" + - " Be aware that any chat messages that you send are going to be send to a discord channel!" + + ChatColor.RED + + " Be aware that any chat messages that you send are going to be send to a discord channel!\n" + + ChatColor.AQUA + " To create a link with your discord account, use " + ChatColor.GRAY + "/link" + ChatColor.RESET ); From 135e7a6e0c9ac7342a68aeda376a99ad9d81e9f7 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 14 May 2021 21:55:48 +0200 Subject: [PATCH 051/158] =?UTF-8?q?=E2=9E=95=20Added=20the=20showing=20of?= =?UTF-8?q?=20the=20discord=20profile=20picture,=20if=20the=20user=20has?= =?UTF-8?q?=20an=20account.=20If=20now,=20make=20a=20link=20to=20namemc=20?= =?UTF-8?q?with=20the=20minecraft=20user's=20profile.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/discord/DiscordMessageBroadcast.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java index f0554d7..d9f265a 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java @@ -1,5 +1,6 @@ package com.github.mafelp.discord; +import com.github.mafelp.accounts.Account; import com.github.mafelp.minecraft.skins.Skin; import com.github.mafelp.utils.Settings; import org.bukkit.entity.Player; @@ -50,10 +51,13 @@ public void run() { // create an embed for the message EmbedBuilder embed = new EmbedBuilder() // .setAuthor(messageAuthor.getDisplayName()) - .setAuthor(messageAuthor.getDisplayName(), "", new Skin(messageAuthor, false).getHead(), ".png") .setColor(Color.YELLOW) .setDescription(message); + if (Account.getByPlayer(messageAuthor).isPresent()) + embed.setAuthor(Account.getByPlayer(messageAuthor).get().getUser()); + else + embed.setAuthor(messageAuthor.getDisplayName(), "https://namemc.com/profile/" + messageAuthor.getName(), new Skin(messageAuthor, false).getHead(), ".png"); if (Settings.getConfiguration().getBoolean("showFooterInMessages", true)) embed.setFooter("On " + Settings.serverName); // send the embed to all channels in the list From 1646f073d0bfc500cd9df68c82384f848f4f1082 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 17 Jun 2021 14:25:12 +0200 Subject: [PATCH 052/158] =?UTF-8?q?=E2=9E=95=20Added=20CommandListener:=20?= =?UTF-8?q?If=20enabled,=20sends=20a=20message=20to=20the=20discord=20chan?= =?UTF-8?q?nels,=20when=20the=20server=20or=20a=20player=20executes=20a=20?= =?UTF-8?q?command.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../discord/DiscordMessageBroadcast.java | 127 ++++++++++++++++-- .../mafelp/minecraft/CommandListener.java | 39 ++++++ .../com/github/mafelp/minecraft/Main.java | 1 + .../com/github/mafelp/utils/Settings.java | 2 + 4 files changed, 159 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/CommandListener.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java index d9f265a..ff7ad3f 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java @@ -2,7 +2,9 @@ import com.github.mafelp.accounts.Account; import com.github.mafelp.minecraft.skins.Skin; +import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; +import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.javacord.api.entity.channel.Channel; import org.javacord.api.entity.message.embed.EmbedBuilder; @@ -19,19 +21,57 @@ public class DiscordMessageBroadcast extends Thread { */ private final Player messageAuthor; + /** + * The command that is being executed. + */ + private final String command; + /** * What the player has sent. */ private final String message; + private final BroadcastType broadcastType; + /** - * Constructor to give the function all needed information. + * Constructor to define this thread as a message broadcast. * @param messageAuthor The person, who sent the message. * @param message The message, the messageAuthor has sent. */ public DiscordMessageBroadcast(Player messageAuthor, String message) { this.messageAuthor = messageAuthor; this.message = message; + + this.broadcastType = BroadcastType.chatMessageBroadcast; + + this.command = null; + } + + /** + * Constructor to define this thread as a command-info broadcast by the server. + * @param command The command that was executed. + */ + public DiscordMessageBroadcast(String command) { + this.command = command; + + this.broadcastType = BroadcastType.serverCommandBroadcast; + + this.messageAuthor = null; + this.message = null; + } + + /** + * The constructor to define this thread as a command-info broadcast by a player. + * @param command The command the player executed. + * @param player The player who executed the command. + */ + public DiscordMessageBroadcast(String command, Player player) { + this.command = command; + this.messageAuthor = player; + + this.broadcastType = BroadcastType.playerCommandBroadcast; + + this.message = null; } /** @@ -39,6 +79,18 @@ public DiscordMessageBroadcast(Player messageAuthor, String message) { */ @Override public void run() { + switch (this.broadcastType) { + case chatMessageBroadcast -> messageBroadcast(); + case playerCommandBroadcast -> playerCommandBroadcast(); + case serverCommandBroadcast -> serverCommandBroadcast(); + } + } + + /** + * Sends the give embed to all configured channels. + * @param embed The embed to send to the different channels. + */ + private void sendMessages(EmbedBuilder embed) { // get all channels, where the message should be send to List channels = ChannelAdmin.getMessageChannels(); @@ -48,24 +100,79 @@ public void run() { return; } + // Send the message to each channel, if it is a text channel. + channels.forEach(channel -> + channel.asTextChannel().ifPresent(textChannel -> + textChannel.sendMessage(embed) + ) + ); + } + + /** + * The method to send a chat message. + */ + private void messageBroadcast() { // create an embed for the message EmbedBuilder embed = new EmbedBuilder() - // .setAuthor(messageAuthor.getDisplayName()) .setColor(Color.YELLOW) .setDescription(message); + if (Account.getByPlayer(messageAuthor).isPresent()) + embed.setAuthor(Account.getByPlayer(messageAuthor).get().getUser()); + else { + assert messageAuthor != null; + embed.setAuthor(messageAuthor.getDisplayName(), "https://namemc.com/profile/" + messageAuthor.getName(), new Skin(messageAuthor, false).getHead(), ".png"); + } + if (Settings.getConfiguration().getBoolean("showFooterInMessages", true)) + embed.setFooter("On " + Settings.serverName); + + sendMessages(embed); + } + + /** + * The method to send a server command embed. + */ + private void serverCommandBroadcast() { + // create an embed for the message + EmbedBuilder embed = new EmbedBuilder() + .setColor(new Color(0xA245F3)) + .setAuthor(Settings.discordApi.getYourself()) + .setTitle("Server Command was executed!") + .setDescription(command); + + if (Settings.getConfiguration().getBoolean("showFooterInMessages", true)) + embed.setFooter("On " + Settings.serverName); + + sendMessages(embed); + } + + /** + * The method to send a player command embed. + */ + private void playerCommandBroadcast() { + assert messageAuthor != null; + + // create an embed for the message + EmbedBuilder embed = new EmbedBuilder() + .setColor(new Color(0x5645F3)) + .setAuthor(Settings.discordApi.getYourself()) + .setTitle("Player " + messageAuthor.getName() + " executed a command!") + .setDescription(command); + if (Account.getByPlayer(messageAuthor).isPresent()) embed.setAuthor(Account.getByPlayer(messageAuthor).get().getUser()); else embed.setAuthor(messageAuthor.getDisplayName(), "https://namemc.com/profile/" + messageAuthor.getName(), new Skin(messageAuthor, false).getHead(), ".png"); + if (Settings.getConfiguration().getBoolean("showFooterInMessages", true)) - embed.setFooter("On " + Settings.serverName); - // send the embed to all channels in the list - for (Channel channel : channels) { - // only send the embed, if the channel is present, to avoid exceptions - if (channel.asServerTextChannel().isPresent()) { - channel.asServerTextChannel().get().sendMessage(embed); - } - } + embed.setFooter("On " + Settings.serverName); + + sendMessages(embed); } } + +enum BroadcastType { + playerCommandBroadcast, + serverCommandBroadcast, + chatMessageBroadcast +} \ No newline at end of file diff --git a/src/main/java/com/github/mafelp/minecraft/CommandListener.java b/src/main/java/com/github/mafelp/minecraft/CommandListener.java new file mode 100644 index 0000000..1e95977 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/CommandListener.java @@ -0,0 +1,39 @@ +package com.github.mafelp.minecraft; + +import com.github.mafelp.discord.DiscordMessageBroadcast; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.server.ServerCommandEvent; + +public class CommandListener implements Listener { + @EventHandler + public void onCommand(PlayerCommandPreprocessEvent playerCommandPreprocessEvent) { + if (!Settings.getConfiguration().getBoolean("sendCommandToDiscord.player")) { + Logging.debug("Sending user commands to the discord server is disabled. Not sending command."); + return; + } + + String message = playerCommandPreprocessEvent.getMessage(); + Player player = playerCommandPreprocessEvent.getPlayer(); + + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast(message, player); + discordMessageBroadcast.start(); + } + + @EventHandler + public void onServerCommand(ServerCommandEvent serverCommandEvent) { + if (!Settings.getConfiguration().getBoolean("sendCommandToDiscord.server")) { + Logging.debug("Sending server commands to the discord server is disabled. Not sending command."); + return; + } + + String command = serverCommandEvent.getCommand(); + + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast(command); + discordMessageBroadcast.start(); + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index af8f86c..2ba4824 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -87,6 +87,7 @@ private void listenerRegistration() { // for more information read the Javadoc in the specific classes pluginManager.registerEvents(new JoinListener(), this); pluginManager.registerEvents(new MinecraftChatListener(), this); + pluginManager.registerEvents(new CommandListener(), this); } /** diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index f1117d1..4723a53 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -262,6 +262,8 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("permission.discordServerAdmin.allowedUserIDs", new ArrayList()); defaultConfiguration.set("permission.discordBotAdmin.allowedUserIDs", new ArrayList()); defaultConfiguration.set("saveEscapeCharacterInConfig", true); + defaultConfiguration.set("sendCommandToDiscord.player", false); + defaultConfiguration.set("sendCommandToDiscord.server", false); return defaultConfiguration; } From b912884c08db22d55e473a8cc5f289c75b65cfd3 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 17 Jun 2021 14:25:47 +0200 Subject: [PATCH 053/158] =?UTF-8?q?=F0=9F=94=84=20Updated=20README=20to=20?= =?UTF-8?q?represent=20the=20latest=20changes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 278fb2a..d376af9 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,17 @@ # MCDC A [Minecraft](https://www.minecraft.net) plugin for [paper servers](https://papermc.io). -## Functions +## Features The bot can currently do all the checked items, unchecked will be implemented in the future. - [X] Display discord messages in the minecraft chat - [X] Discord messages can be sent to the bot via direct message - [X] Discord messages can be sent to any server channel the bot is present on - [X] Display minecraft messages in a discord chat - [X] managing a "#mincraft-server" channel on a specific discord server - - [ ] this includes that only members with a role can see this channel and write in it -

- - [ ] whisper between a discord user and a minecraft user - - [ ] linking between a discord and a minecraft account - + - [X] this includes that only members with a role can see this channel and write in it + - [X] whisper between a discord user and a minecraft user + - [X] linking between a discord and a minecraft account + - [X] Toggle-able: Sending minecraft commands to the discord chats. ## Installation 1. Download the latest [release](https://github.com/MaFeLP/MCDC/releases/) and put it into `/plugins`. From 8a72a53eb1ae22d04ccc0bb18173f33c278a29ac Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 17 Jun 2021 14:29:29 +0200 Subject: [PATCH 054/158] =?UTF-8?q?=F0=9F=94=84=20Updated=20the=20default?= =?UTF-8?q?=20configuration=20to=20have=20the=20new=20settings=20in=20it.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 40 ++++++++++++++++++++++++++++++++++++++++ defaultConfiguration.yml | 7 +++++++ 2 files changed, 47 insertions(+) diff --git a/README.md b/README.md index d376af9..c296baa 100644 --- a/README.md +++ b/README.md @@ -58,12 +58,52 @@ apiToken: 'Your API Token goes here!' # Allowed values: any String discordCommandPrefix: '.' +# Selects if messages that are commands should be deleted after execution. +# Allowed values: +deleteDiscordCommandMessages: false + # Discord Channel IDs to broadcast messages to. channelIDs: - 1234 +# Enables accounts and linking. +# Allowed values +enableLinking: true + +# Allow players to list all the accounts. +# Allowed values +allowListAllAccounts: true + +# Decides, if the config value 'serverName' should be displayed in the footer of discord messages. +# Allowed values +showFooterInMessages: true + +# The value that should be displayed below the name +activity: + # If the bot should have an activity. + enabled: true + # The type of the message, aka. the first word: + # can be set to custom, competing, listening, watching, streaming or playing + type: listening + # The text that should be displayed. + message: "your messages 👀" + +# If the bot should send a message to the listening channels, if a command was executed by ... +sendCommandToDiscord: + # ... a player. + player: false + # ... the server. + server: false + # Permission section for setting permission levels permission: + # The permissions on linking and editing accounts. + accountEdit: + # The OP level needed to remove accounts of players. + level: 3 + # A list of UUIDs of Players who have a wildcard to use this command. + allowedUserUUIDs: + - a unique ID # Permission for minecraft command /config configEdit: diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 7fbb4f8..8e90d45 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -55,6 +55,13 @@ activity: # The text that should be displayed. message: "your messages 👀" +# If the bot should send a message to the listening channels, if a command was executed by ... +sendCommandToDiscord: + # ... a player. + player: false + # ... the server. + server: false + # Permission section for setting permission levels permission: # The permissions on linking and editing accounts. From d38e6fd948a60e6c529d27fec01b55b401eff1ac Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 17 Jun 2021 14:46:29 +0200 Subject: [PATCH 055/158] =?UTF-8?q?=E2=9E=95=20Added=20CHANGELOG=20for=20v?= =?UTF-8?q?ersion=200.9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03159d5..619d1e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,23 @@ # Changelog +## BIG Account update +### v0.9.0 +➕ Added Accounts!
+↳ Place an account Tag in your minecraft message, and it will be replaced with a discord ping (if the user has a linked account)!
+↳ Added a new minecraft command `/link`: Link your minecraft and discord accounts!
+↳ Added a new minecraft command `/unlink`: Unlink your minecraft and discord accounts!
+↳ Added a new minecraft command `/account`: Manage your accounts!
+↳ Added a new minecraft command `/whisper`: Whisper to a friend on discord!
+↳ Added a new minecraft command `/dcmsg`: Whisper to a friend on discord!
+↳ Added a new discord command `link`: Link your discord to your minecraft!
+↳ Added a new discord command `whisper`: Whisper your message to a minecraft player!
+↳ Added a new discord command `mcmsg`: Whisper your message to a minecraft player!
+➕ Added some more toggles:
+↳ The bot **can** send message with server commands and player commands to all the channels.
+↳ Toggle, if the footer should be displayed.
+↳ Toggle, if discord command messages should be deleted b the bot.
+ +--- + ## Small bug fixes ### v0.8.4-beta ➕ Added Error message, when then bot does not have the required permissions, to create Channels or/and roles (See issue [29](https://github.com/MaFeLP/MCDC/issues/29)).
@@ -157,7 +176,7 @@ ## v0.3.1-beta ### 🏁 Commenting update! ➕ Added building instructions with Java 8
-➕ Added full Javadoc documentation in [doc](./doc)
+➕ Added full Javadoc documentation in [doc](https://mafelp.github.io/MCDC/doc/development/index.html)
➕ Added full commentary to the full code base
➕ Added [RoleAdmin.java](./src/main/java/com/github/mafelp/discord/RoleAdmin.java) to prepare for Role management in coming builds From c27f9435b1ca07b347ccc16bc1d4503247b05fe9 Mon Sep 17 00:00:00 2001 From: GitHub Date: Thu, 17 Jun 2021 14:54:16 +0200 Subject: [PATCH 056/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20t?= =?UTF-8?q?he=20CommandLister=20and=20associated=20methods/fields/enums.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/discord/DiscordMessageBroadcast.java | 15 +++++++++++++++ .../mafelp/discord/commands/WhisperListener.java | 3 +++ .../github/mafelp/minecraft/CommandListener.java | 15 +++++++++++++-- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java index ff7ad3f..45dbbe5 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java @@ -31,6 +31,9 @@ public class DiscordMessageBroadcast extends Thread { */ private final String message; + /** + * The type of the broadcast. + */ private final BroadcastType broadcastType; /** @@ -171,8 +174,20 @@ private void playerCommandBroadcast() { } } +/** + * The type of the broadcast. + */ enum BroadcastType { + /** + * A player executed a command. + */ playerCommandBroadcast, + /** + * The server executed a command. + */ serverCommandBroadcast, + /** + * A player sent a normal message. + */ chatMessageBroadcast } \ No newline at end of file diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index 0a50ec2..d9cf989 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -221,6 +221,9 @@ public void onMessageCreate(MessageCreateEvent messageCreateEvent) { * The method that creates a prefix for whispered messages, according to the settings.
* This prefix can either be a one-liner or a two-liner. * @param messageCreateEvent The event that stores all the information about the whisper message sender. + * @param playerIsReceiver Receiver is a player; if not, it will be the console so don't display line + * breaks and emoji if this is set to false. + * @param receiver The "name" of the receiver. * @return The prefix to add to the message. */ private static String whisperPrefix(MessageCreateEvent messageCreateEvent, boolean playerIsReceiver, String receiver) { diff --git a/src/main/java/com/github/mafelp/minecraft/CommandListener.java b/src/main/java/com/github/mafelp/minecraft/CommandListener.java index 1e95977..db05770 100644 --- a/src/main/java/com/github/mafelp/minecraft/CommandListener.java +++ b/src/main/java/com/github/mafelp/minecraft/CommandListener.java @@ -9,10 +9,17 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.server.ServerCommandEvent; +/** + * The class that handles the command sending events. + */ public class CommandListener implements Listener { + /** + * The method that handles commands executed by a player. + * @param playerCommandPreprocessEvent The event passed in by the plugin framework with information about the event. + */ @EventHandler public void onCommand(PlayerCommandPreprocessEvent playerCommandPreprocessEvent) { - if (!Settings.getConfiguration().getBoolean("sendCommandToDiscord.player")) { + if (!Settings.getConfiguration().getBoolean("sendCommandToDiscord.player", false)) { Logging.debug("Sending user commands to the discord server is disabled. Not sending command."); return; } @@ -24,9 +31,13 @@ public void onCommand(PlayerCommandPreprocessEvent playerCommandPreprocessEvent) discordMessageBroadcast.start(); } + /** + * The method that handles commands executed in the server's console. + * @param serverCommandEvent The event passed in by the plugin framework with information about the event. + */ @EventHandler public void onServerCommand(ServerCommandEvent serverCommandEvent) { - if (!Settings.getConfiguration().getBoolean("sendCommandToDiscord.server")) { + if (!Settings.getConfiguration().getBoolean("sendCommandToDiscord.server", false)) { Logging.debug("Sending server commands to the discord server is disabled. Not sending command."); return; } From 4c4aa1c838e177a0732c4ee4c08f4a877817319a Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 18 Jun 2021 21:36:19 +0200 Subject: [PATCH 057/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20Default=20Java?= =?UTF-8?q?=20Version=20to=2016?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index dc685ac..ec4e388 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ A Spigot plugin for cross communicating with a discord server - 15 + 16 UTF-8 https://github.com/MaFeLP/MCDC From 9a4c7187cd51d078faafa64df8f0d55503834eb2 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 18 Jun 2021 21:39:14 +0200 Subject: [PATCH 058/158] =?UTF-8?q?=F0=9F=8F=81=20Added=20three=20more=20T?= =?UTF-8?q?o-Do=20targets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index c296baa..28fbb87 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ The bot can currently do all the checked items, unchecked will be implemented in - [X] whisper between a discord user and a minecraft user - [X] linking between a discord and a minecraft account - [X] Toggle-able: Sending minecraft commands to the discord chats. +

+ - [ ] A message in a channel that displays all online Members. + - [ ] Tab completion in Minecraft + - [ ] Migrate to Slash Commands on discord, as soon as the API is ready. ## Installation 1. Download the latest [release](https://github.com/MaFeLP/MCDC/releases/) and put it into `/plugins`. From 287f6c3d0320cd74694959d30aac83eeee601086 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 18 Jun 2021 21:41:55 +0200 Subject: [PATCH 059/158] =?UTF-8?q?=E2=9E=95=20Added=20missing=20default?= =?UTF-8?q?=20entries=20to=20the=20configuration.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/utils/Settings.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 4723a53..6f1e055 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -250,6 +250,8 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("debug", false); defaultConfiguration.set("discordCommandPrefix", "."); defaultConfiguration.set("deleteDiscordCommandMessages", false); + defaultConfiguration.set("channelIDs", new ArrayList().add(1234L)); + defaultConfiguration.set("enableLinking", true); defaultConfiguration.set("allowListAllAccounts", true); defaultConfiguration.set("showFooterInMessages", true); defaultConfiguration.set("activity.enabled", true); From 3f88858a3bb5088263756e90f73df3c21c2f4cf5 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 18 Jun 2021 22:03:37 +0200 Subject: [PATCH 060/158] =?UTF-8?q?=E2=9E=95=20Added=20that=20only=20one?= =?UTF-8?q?=20account=20could=20be=20registered=20with=20each=20minecraft/?= =?UTF-8?q?discord=20user.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/accounts/AccountManager.java | 3 ++- .../github/mafelp/accounts/DiscordLinker.java | 3 +++ .../mafelp/accounts/MinecraftLinker.java | 3 +++ .../mafelp/discord/commands/LinkListener.java | 18 ++++++++++++++++++ .../github/mafelp/minecraft/commands/Link.java | 15 ++++++++++++--- 5 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 0621196..53aeee4 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -107,7 +107,8 @@ protected static List setLinkedAccounts(List set) { * @return the list of all linked Accounts. */ public static List addAccount(Account account) { - linkedAccounts.add(account); + if (!linkedAccounts.contains(account)) + linkedAccounts.add(account); return linkedAccounts; } diff --git a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java index 6d6936e..72b208d 100644 --- a/src/main/java/com/github/mafelp/accounts/DiscordLinker.java +++ b/src/main/java/com/github/mafelp/accounts/DiscordLinker.java @@ -26,6 +26,9 @@ public class DiscordLinker { * @return The Token used to link the account in minecraft. */ public static int getLinkToken(User user) { + if (Account.getByDiscordUser(user).isPresent()) + return -1; + if (linkableAccounts.containsKey(user)) return linkableAccounts.get(user); else { diff --git a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java index 0a92e36..f74a46e 100644 --- a/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java +++ b/src/main/java/com/github/mafelp/accounts/MinecraftLinker.java @@ -26,6 +26,9 @@ public class MinecraftLinker { * @return The Token used to link the account in discord. */ public static int getLinkToken(Player player) { + if (Account.getByPlayer(player).isPresent()) + return -1; + if (linkableAccounts.containsKey(player)) return linkableAccounts.get(player); else { diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index 3784e2f..f2ef3fc 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -100,6 +100,24 @@ public void onMessageCreate(MessageCreateEvent event) { .setFooter("More information on linking here: https://mafelp.github.io/MCDC/linking") ; + EmbedBuilder alreadyRegistered = new EmbedBuilder() + .setAuthor(event.getMessageAuthor()) + .setColor(new Color(0xFF3C00)) + .setTitle("Account Already Registered!") + .setFooter("More information on linking here: https://mafelp.github.io/MCDC/linking") + ; + + if (Account.getByDiscordUser(event.getMessageAuthor().asUser().get()).isPresent()) { + Account account = Account.getByDiscordUser(event.getMessageAuthor().asUser().get()).get(); + + alreadyRegistered.setDescription("Sorry, but your Discord Account is already linked to the minecraft user " + account.getPlayer().getName() + "!\n" + + "Use \"/unlink\" in Minecraft or \"" + Settings.getConfiguration().get("discordCommandPrefix") + "unlink\" to unlink your accounts!"); + + event.getMessageAuthor().asUser().get().sendMessage(alreadyRegistered); + + return; + } + if (command.getStringArgument(1).isPresent()) { Logging.debug("User \"" + event.getMessageAuthor().getDisplayName() + "\" used the command 'link' wrong. Sending help embed..."); event.getMessage().reply(helpMessage); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Link.java b/src/main/java/com/github/mafelp/minecraft/commands/Link.java index e4eeb48..5d72f59 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Link.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Link.java @@ -33,9 +33,18 @@ public class Link implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { // Check if the command Sender is a player. - if (sender instanceof Player) { - // If the CommandSender is a player, we can safely cast it to a player. - Player player = (Player) sender; + if (sender instanceof Player player) { + if (Account.getByPlayer(player).isPresent()) { + // If the CommandSender is a player, we can safely cast it to a player. + Account account = Account.getByPlayer(player).get(); + + final String message = "Sorry, but your Minecraft Account is already linked to the discord user " + account.getUser().getName() + "!\n" + + "Use \"/unlink\" in Minecraft or \"" + Settings.getConfiguration().get("discordCommandPrefix") + "unlink\" to unlink your accounts!"; + + player.sendMessage(prefix + ChatColor.RED + message); + + return true; + } // If no arguments are given, return and send the user a token. if (args == null) { From 83c5394a0cc09c2ca15b48e2d69eaa7d4dbdae42 Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 21:11:44 +0200 Subject: [PATCH 061/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20Javacord=20to?= =?UTF-8?q?=20version=203.3.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ec4e388..ebc44ff 100644 --- a/pom.xml +++ b/pom.xml @@ -88,7 +88,7 @@ org.javacord javacord - 3.3.0 + 3.3.2 pom From 0c4fa943896dd57177bb5d64edc36412328ba806 Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 22:06:55 +0200 Subject: [PATCH 062/158] =?UTF-8?q?=E2=9E=95=20Added=20MainSlashCommandLis?= =?UTF-8?q?tener=20to=20handle=20all=20slash=20command=20interactions.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/MainSlashCommandListener.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java new file mode 100644 index 0000000..2f07005 --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -0,0 +1,15 @@ +package com.github.mafelp.discord.commands; + +import org.javacord.api.event.interaction.SlashCommandCreateEvent; +import org.javacord.api.listener.interaction.SlashCommandCreateListener; + +public class MainSlashCommandListener implements SlashCommandCreateListener { + @Override + public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent) { + switch (slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()) { + case "setup" -> {} + case "link" -> LinkListener.onSlashCommand(slashCommandCreateEvent); + default -> {} + } + } +} From 310bb3ed32ab8f9d729902c000d0325cdc52866d Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 22:08:47 +0200 Subject: [PATCH 063/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20.link?= =?UTF-8?q?=20to=20/link=20on=20discord.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 22 +++- .../mafelp/discord/commands/LinkListener.java | 110 ++++-------------- 2 files changed, 41 insertions(+), 91 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index eae6f0b..6fa9507 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -10,8 +10,12 @@ import org.javacord.api.entity.permission.PermissionType; import org.javacord.api.entity.permission.Permissions; import org.javacord.api.entity.permission.PermissionsBuilder; +import org.javacord.api.interaction.SlashCommand; +import org.javacord.api.interaction.SlashCommandOption; +import org.javacord.api.interaction.SlashCommandOptionType; import java.io.*; +import java.util.Collections; import java.util.Locale; import java.util.Objects; import java.util.concurrent.CompletionException; @@ -88,12 +92,14 @@ public void run() { .addListener(CreateChannelListener::new) .addListener(CreateRoleListener::new) .addListener(SetupListener::new) - .addListener(LinkListener::new) .addListener(UnlinkListener::new) .addListener(WhisperListener::new) + .addListener(MainSlashCommandListener::new) // log the bot in and join the servers .login().join(); + registerSlashCommands(); + Logging.info(ChatColor.GREEN + "Successfully started the discord instance!"); Logging.info(ChatColor.RESET + "The bot invitation token is: " + discordApi.createBotInvite(botPermissions)); } catch (IllegalStateException | CompletionException exception) { @@ -123,6 +129,16 @@ public void run() { } } + private void registerSlashCommands() { + SlashCommand.with("link", "A command to link your discord and minecraft accounts", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.INTEGER, "token", "The token used to link your accounts", false) + ) + ).setDefaultPermission(true) + .createGlobal(discordApi) + .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + } + /** * Shutdown method to disconnect the bot instance */ @@ -137,7 +153,9 @@ public static void shutdown() { Logging.info(ChatColor.DARK_GRAY + "Shutting down Discord Instance..."); // Disconnect the bot / shut the bot down - Settings.discordApi.disconnect(); + try { + Settings.discordApi.disconnect(); + } catch (IllegalStateException ignored) {} Settings.discordApi = null; } } diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index f2ef3fc..45718f6 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -3,145 +3,77 @@ import com.github.mafelp.accounts.Account; import com.github.mafelp.accounts.DiscordLinker; import com.github.mafelp.accounts.MinecraftLinker; -import com.github.mafelp.utils.Command; -import com.github.mafelp.utils.CommandParser; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; -import com.github.mafelp.utils.exceptions.CommandNotFinishedException; -import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.User; -import org.javacord.api.event.message.MessageCreateEvent; -import org.javacord.api.listener.message.MessageCreateListener; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; import java.awt.*; import java.util.Optional; -import static com.github.mafelp.utils.Settings.discordCommandPrefix; - /** * The class that handles discord messages and test, if they are the link command. If so, it starts the linking process. */ -public class LinkListener implements MessageCreateListener { +public class LinkListener { /** * The method that handles messages, that are sent, tests if they are the link command. * If so, this method starts the linking process. * @param event The event sent from the Discord API, containing important information about the message, * such as the channel it has been sent to and the {@link User} who has sent it. */ - @Override - public void onMessageCreate(MessageCreateEvent event) { - // If the message is sent by the bot, return - if (event.getMessageAuthor().isYourself()) { - return; - } - - // If message does not start with the command prefix, return - // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || - // event.getReadableMessageContent() == null) - // return; - - // Gets the content of the message as strings (prints it, if debug is enabled) - String content = event.getReadableMessageContent(); - - // Tries parsing the command. The error handling is being done by the CreateChannelListener. - Command command; - try { - command = CommandParser.parseFromString(content); - } catch (CommandNotFinishedException | NoCommandGivenException e) { - // Logging.logException(e, "Error parsing the command from the string..."); - return; - } - - // If the command does not equal link, exit. - if (!command.getCommand().equalsIgnoreCase(Settings.discordCommandPrefix + "link")) { - // Logging.debug("Not the link command: \"" + command.getCommand() + "\" != \"" + discordCommandPrefix + "link" + "\""); - return; - } - - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { - Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); - Logging.debug("Deleted the original command message."); - } - - // Tries to parse the message author into a user. If this fails, don't execute this command. - if (event.getMessageAuthor().asUser().isEmpty()) { - Logging.debug("Could not parse user, while trying to execute link command. Aborting..."); - event.getMessage().reply( - new EmbedBuilder() - .setTitle("Error!") - .setDescription("Could not parse the sender of this message into a discord user. We therefore cannot execute the command \"link\", as requested. See https://mafelp.github.io/MCDC/errors/ for more information.") - .setColor(Color.RED) - .setAuthor(Settings.discordApi.getYourself()) - ); - - return; - } - - Logging.debug("Executing link command for user " + event.getMessageAuthor().asUser().get().getName()); - - // help message for wrong usage - EmbedBuilder helpMessage = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) - .setTitle("Error") - .addField("Usage", discordCommandPrefix + "link []") - .addField("Functionality", "Links your discord account to a minecraft account..") - .setColor(new Color(0xFFB500)) - .setFooter("Help message for command \"link\"") - ; + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); + Logging.debug("Executing link command for user " + author); // Embed sent on successful account linking EmbedBuilder successEmbed = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setColor(Color.GREEN) .setTitle("Success!") .setFooter("More information on linking here: https://mafelp.github.io/MCDC/linking") ; EmbedBuilder alreadyRegistered = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setColor(new Color(0xFF3C00)) .setTitle("Account Already Registered!") .setFooter("More information on linking here: https://mafelp.github.io/MCDC/linking") ; - if (Account.getByDiscordUser(event.getMessageAuthor().asUser().get()).isPresent()) { - Account account = Account.getByDiscordUser(event.getMessageAuthor().asUser().get()).get(); + if (Account.getByDiscordUser(author).isPresent()) { + Account account = Account.getByDiscordUser(author).get(); alreadyRegistered.setDescription("Sorry, but your Discord Account is already linked to the minecraft user " + account.getPlayer().getName() + "!\n" + "Use \"/unlink\" in Minecraft or \"" + Settings.getConfiguration().get("discordCommandPrefix") + "unlink\" to unlink your accounts!"); - event.getMessageAuthor().asUser().get().sendMessage(alreadyRegistered); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(alreadyRegistered).respond(); return; } - if (command.getStringArgument(1).isPresent()) { - Logging.debug("User \"" + event.getMessageAuthor().getDisplayName() + "\" used the command 'link' wrong. Sending help embed..."); - event.getMessage().reply(helpMessage); - return; - } + int token = event.getSlashCommandInteraction().getFirstOptionIntValue().orElse(-1); // Checks if a number is given as the first argument. If not, send the user a new Link token. - if (command.getIntegerArgument(0).isEmpty()) { + if (token == -1) { Logging.debug("No Integer Argument given in link command. Sending LinkTokenEmbed..."); - sendLinkToken(event.getMessageAuthor().asUser().get()); + sendLinkToken(author, event); // If a number is being found at the first argument, try to link it to a minecraft account. } else { Logging.debug("LinkToken found. Checking it..."); - Optional linkedAccount = MinecraftLinker.linkToDiscord(event.getMessageAuthor().asUser().get(), command.getIntegerArgument(0).get()); + Optional linkedAccount = MinecraftLinker.linkToDiscord(author, token); if (linkedAccount.isEmpty()) { Logging.debug("LinkToken is invalid. Sending new Link Token"); - sendLinkToken(event.getMessageAuthor().asUser().get()); + sendLinkToken(author, event); return; } Logging.debug("LinkToken valid. sending success Embed."); - event.getMessageAuthor().asUser().get().sendMessage(successEmbed.addInlineField("Minecraft Account", linkedAccount.get().getPlayer().getName()) - .addInlineField("Discord Account", linkedAccount.get().getUsername() + " : " + linkedAccount.get().getMentionTag())); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed( + successEmbed.addInlineField("Minecraft Account", linkedAccount.get().getPlayer().getName()) + .addInlineField("Discord Account", linkedAccount.get().getUsername() + " : " + linkedAccount.get().getMentionTag()) + ).respond(); } } @@ -150,7 +82,7 @@ public void onMessageCreate(MessageCreateEvent event) { * links its accounts together. * @param user The user to create the linking token from. */ - private void sendLinkToken(final User user) { + private static void sendLinkToken(final User user, final SlashCommandCreateEvent event) { int minecraftLinkToken = DiscordLinker.getLinkToken(user); EmbedBuilder reply = new EmbedBuilder() @@ -162,6 +94,6 @@ private void sendLinkToken(final User user) { .setFooter("MCDC made by MaFeLP (https://mafelp.github.io/MCDC/") ; - user.sendMessage(reply); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(reply).respond(); } } \ No newline at end of file From 64e94ec95736ae7178c0c9d88ef182ae27610fa7 Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 22:09:19 +0200 Subject: [PATCH 064/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug=20in=20t?= =?UTF-8?q?he=20command=20parser,=20when=20empty=20strings=20are=20being?= =?UTF-8?q?=20passed=20in.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/utils/CommandParser.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/utils/CommandParser.java b/src/main/java/com/github/mafelp/utils/CommandParser.java index 14deb0d..6a35e8f 100644 --- a/src/main/java/com/github/mafelp/utils/CommandParser.java +++ b/src/main/java/com/github/mafelp/utils/CommandParser.java @@ -107,7 +107,11 @@ public static Command parseFromString(String commandArgumentString) throws Comma argumentList.add(argsList.get(i)); } - return new Command(argsList.get(0), argumentList.toArray(String[]::new)); + try { + return new Command(argsList.get(0), argumentList.toArray(String[]::new)); + } catch (IndexOutOfBoundsException e) { + return null; + } } /** From d29504c4b9f281577a71d63b76ee53af944ff832 Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 22:17:42 +0200 Subject: [PATCH 065/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20.unlink?= =?UTF-8?q?=20to=20the=20global=20slash=20command=20/unlink.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 8 +- .../commands/MainSlashCommandListener.java | 1 + .../discord/commands/UnlinkListener.java | 126 ++++-------------- 3 files changed, 34 insertions(+), 101 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 6fa9507..f85726f 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -92,7 +92,6 @@ public void run() { .addListener(CreateChannelListener::new) .addListener(CreateRoleListener::new) .addListener(SetupListener::new) - .addListener(UnlinkListener::new) .addListener(WhisperListener::new) .addListener(MainSlashCommandListener::new) // log the bot in and join the servers @@ -130,6 +129,7 @@ public void run() { } private void registerSlashCommands() { + // Link command SlashCommand.with("link", "A command to link your discord and minecraft accounts", Collections.singletonList( SlashCommandOption.create(SlashCommandOptionType.INTEGER, "token", "The token used to link your accounts", false) @@ -137,6 +137,12 @@ private void registerSlashCommands() { ).setDefaultPermission(true) .createGlobal(discordApi) .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + + // Unlink command + SlashCommand.with("unlink", "Unlink your discord account from your minecraft account") + .setDefaultPermission(true) + .createGlobal(discordApi) + .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); } /** diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index 2f07005..c7342ea 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -9,6 +9,7 @@ public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent switch (slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()) { case "setup" -> {} case "link" -> LinkListener.onSlashCommand(slashCommandCreateEvent); + case "unlink" -> UnlinkListener.onSlashCommand(slashCommandCreateEvent); default -> {} } } diff --git a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java index 126cca8..087f837 100644 --- a/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/UnlinkListener.java @@ -2,141 +2,67 @@ import com.github.mafelp.accounts.Account; import com.github.mafelp.accounts.AccountManager; -import com.github.mafelp.utils.Command; -import com.github.mafelp.utils.CommandParser; import com.github.mafelp.utils.Logging; -import com.github.mafelp.utils.Settings; -import com.github.mafelp.utils.exceptions.CommandNotFinishedException; -import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.User; -import org.javacord.api.event.message.MessageCreateEvent; -import org.javacord.api.listener.message.MessageCreateListener; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; import java.awt.*; import java.util.Optional; -import static com.github.mafelp.utils.Settings.*; +import static com.github.mafelp.utils.Settings.discordCommandPrefix; /** * The class used to listen in discord and unlinks your account. */ -public class UnlinkListener implements MessageCreateListener { +public class UnlinkListener{ /** * The method that initializes the unlinking. - * @param messageCreateEvent The + * @param event The event that hold information about this specific command. */ - @Override - public void onMessageCreate(MessageCreateEvent messageCreateEvent) { - // If the message is sent by the bot, return - if (messageCreateEvent.getMessageAuthor().isYourself()) { - return; - } - - // If message does not start with the command prefix, return - // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || - // event.getReadableMessageContent() == null) - // return; - - - // Gets the content of the message as strings (prints it, if debug is enabled) - String content = messageCreateEvent.getReadableMessageContent(); - - // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. - Command command; - try { - command = CommandParser.parseFromString(content); - } catch (CommandNotFinishedException | NoCommandGivenException e) { - // Logging.logException(e, "Error parsing hte command from the string..."); - return; - } - - // help message for wrong usage - EmbedBuilder helpMessage = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) - .setTitle("Error") - .addField("Usage", discordCommandPrefix + "unlink") - .addField("Functionality", "Unlinks your discord account from your minecraft account.") - .setColor(new Color(0xFFB500)) - .setFooter("Help message for command \"unlink\"") - ; - + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); // the embed sent on successful execution of the command. EmbedBuilder successEmbed = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) + .setAuthor(author) .setTitle("Success!") .setColor(Color.GREEN) ; // Embed to send, when the bot does not have the required Permissions. EmbedBuilder noAccountEmbed = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) + .setAuthor(author) .setTitle("Error!") .addField("NoAccountError","Sorry, you don't have an account to unlink! Use \"" + discordCommandPrefix + "link\" to create one!") .setColor(Color.RED) ; - // If the message is empty/if the arguments are none, return - if (command.getCommand() == null) - return; - - // If the command is not equal to setup, do nothing and return. - if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "unlink")) - return; - + Logging.debug("User \"" + author.getName() + "\" executed command \"unlink\". Parsing User..."); - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && messageCreateEvent.isServerMessage()) { - Logging.debug("Deleting original command message with ID: " + messageCreateEvent.getMessage().getIdAsString()); - messageCreateEvent.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); - Logging.debug("Deleted the original command message."); - } + Optional optionalAccount = Account.getByDiscordUser(author); - // On wrong usage, aka. when you pass arguments. - if (command.getStringArgument(0).isPresent()) { - messageCreateEvent.getChannel().sendMessage(helpMessage); + // If the user does not have an account. + if (optionalAccount.isEmpty()) { + Logging.debug("User \"" + author.getName() + "\" does not have an account to unlink... Sending noAccountEmbed..."); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noAccountEmbed).respond(); return; } - // Only execute if te message Author is a user and not a webhook. - if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { - Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" executed command \"unlink\". Parsing User..."); - User user = messageCreateEvent.getMessageAuthor().asUser().get(); - - Optional optionalAccount = Account.getByDiscordUser(user); - - // If the user does not have an account. - if (optionalAccount.isEmpty()) { - Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" does not have an account to unlink... Sending noAccountEmbed..."); - messageCreateEvent.getChannel().sendMessage(noAccountEmbed); - return; - } + Logging.debug("Getting the account for user \"" + author.getName() + "\"..."); + // Get the account and some information about it. + Account account = optionalAccount.get(); - Logging.debug("Getting the account for user \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\"..."); - // Get the account and some information about it. - Account account = optionalAccount.get(); + String minecraftName = account.getPlayer().getName(); + String mentionTag = account.getMentionTag(); + String username = account.getUsername(); - String minecraftName = account.getPlayer().getName(); - String mentionTag = account.getMentionTag(); - String username = account.getUsername(); + Logging.info("Removing account \"" + username + "\"..."); + // Then remove the account. + AccountManager.removeAccount(account); - Logging.info("Removing account \"" + username + "\"..."); - // Then remove the account. - AccountManager.removeAccount(account); + successEmbed.addField("Successful Unlinking","Successfully unlinked your minecraft account \"" + minecraftName + "\" from user discord account " + mentionTag); - successEmbed.addField("Successful Unlinking","Successfully unlinked your minecraft account \"" + minecraftName + "\" from user discord account " + mentionTag); - - Logging.info("Removed account \"" + username + "\"... Sending success embed..."); - messageCreateEvent.getChannel().sendMessage(successEmbed); - } else { - Logging.debug("MessageAuthor \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" is not a User! Sending Error embed..."); - messageCreateEvent.getChannel().sendMessage( - new EmbedBuilder() - .setAuthor(discordApi.getYourself()) - .setTitle("Error!") - .setColor(Color.RED) - .addField("UserParsingError","You are not a user, so you can't have an account!") - ); - } + Logging.info("Removed account \"" + username + "\"... Sending success embed..."); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(successEmbed).respond(); } } From deeb756f95cf059f1e77eea9f2dd53a6818ffa41 Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 23:57:36 +0200 Subject: [PATCH 066/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20.mcmsg?= =?UTF-8?q?=20and=20.whisper=20to=20discord=20slash=20commands:=20/mcmsg?= =?UTF-8?q?=20and=20/whisper?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 26 +- .../commands/MainSlashCommandListener.java | 5 +- .../discord/commands/WhisperListener.java | 247 ++++++------------ 3 files changed, 112 insertions(+), 166 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index f85726f..1d427f5 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -15,6 +15,7 @@ import org.javacord.api.interaction.SlashCommandOptionType; import java.io.*; +import java.util.Arrays; import java.util.Collections; import java.util.Locale; import java.util.Objects; @@ -89,10 +90,9 @@ public void run() { .setToken(Settings.getApiToken()) // register listeners .addListener(DiscordListener::new) - .addListener(CreateChannelListener::new) - .addListener(CreateRoleListener::new) - .addListener(SetupListener::new) - .addListener(WhisperListener::new) + //.addListener(CreateChannelListener::new) + //.addListener(CreateRoleListener::new) + //.addListener(SetupListener::new) .addListener(MainSlashCommandListener::new) // log the bot in and join the servers .login().join(); @@ -143,6 +143,24 @@ private void registerSlashCommands() { .setDefaultPermission(true) .createGlobal(discordApi) .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + + // Whisper and mcmsg commands + SlashCommand.with("whisper", "Whisper to your friends on the minecraft server!", + Arrays.asList( + SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), + SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) + )) + .setDefaultPermission(true) + .createGlobal(discordApi) + .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + SlashCommand.with("mcmsg", "Whisper to your friends on the minecraft server!", + Arrays.asList( + SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), + SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) + )) + .setDefaultPermission(true) + .createGlobal(discordApi) + .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); } /** diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index c7342ea..32644ce 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -1,5 +1,7 @@ package com.github.mafelp.discord.commands; +import com.github.mafelp.utils.Logging; +import org.bukkit.ChatColor; import org.javacord.api.event.interaction.SlashCommandCreateEvent; import org.javacord.api.listener.interaction.SlashCommandCreateListener; @@ -10,7 +12,8 @@ public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent case "setup" -> {} case "link" -> LinkListener.onSlashCommand(slashCommandCreateEvent); case "unlink" -> UnlinkListener.onSlashCommand(slashCommandCreateEvent); - default -> {} + case "whisper", "mcmsg" -> WhisperListener.onSlashCommand(slashCommandCreateEvent); + default -> Logging.info(ChatColor.RED + "Wait. Wait? This command is not recognised: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName() + " and this should not have happened!"); } } } diff --git a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java index d9cf989..9dc7f25 100644 --- a/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/WhisperListener.java @@ -1,232 +1,157 @@ package com.github.mafelp.discord.commands; import com.github.mafelp.accounts.Account; -import com.github.mafelp.utils.Command; -import com.github.mafelp.utils.CommandParser; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; -import com.github.mafelp.utils.exceptions.CommandNotFinishedException; -import com.github.mafelp.utils.exceptions.NoCommandGivenException; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.User; -import org.javacord.api.event.message.MessageCreateEvent; -import org.javacord.api.listener.message.MessageCreateListener; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; import java.awt.*; import java.util.Optional; +import java.util.concurrent.CompletionException; -import static com.github.mafelp.utils.Settings.discordApi; import static com.github.mafelp.utils.Settings.discordCommandPrefix; /** * The class that handles whispering on the discord side of things. */ -public class WhisperListener implements MessageCreateListener { +public class WhisperListener { /** * The method that initializes the unlinking. * - * @param messageCreateEvent The + * @param event The event containing information about the command that was being used. */ - @Override - public void onMessageCreate(MessageCreateEvent messageCreateEvent) { - // If the message is sent by the bot, return - if (messageCreateEvent.getMessageAuthor().isYourself()) { - return; - } - - // If message does not start with the command prefix, return - // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || - // event.getReadableMessageContent() == null) - // return; - - - // Gets the content of the message as strings (prints it, if debug is enabled) - String content = messageCreateEvent.getMessageContent(); - - // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. - Command command; - try { - command = CommandParser.parseFromString(content); - } catch (CommandNotFinishedException | NoCommandGivenException e) { - // Logging.logException(e, "Error parsing hte command from the string..."); - return; - } - + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); // help message for wrong usage EmbedBuilder helpMessage = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Usage", discordCommandPrefix + "whisper <@account name> \"\"") .addField("Alternative usage", discordCommandPrefix + "whister <@discord name> \"\"") .addField("Functionality", "Whispers your message to the minecraft account of the receiver.") .setColor(new Color(0xFFB500)) .setFooter("Help message for command \"whisper\""); - // Embed to send, when the bot does not have the required Permissions. EmbedBuilder noAccountEmbed = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) + .setAuthor(author) .setTitle("Error!") .setColor(Color.RED); - // If the message is empty/if the arguments are none, return - if (command.getCommand() == null) - return; - - // If the command is not equal to setup, do nothing and return. - if (!(command.getCommand().equalsIgnoreCase(discordCommandPrefix + "whisper") || command.getCommand().equalsIgnoreCase(discordCommandPrefix + "mcmsg"))) - return; - - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && messageCreateEvent.isServerMessage()) { - Logging.debug("Deleting original command message with ID: " + messageCreateEvent.getMessage().getIdAsString()); - messageCreateEvent.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); - Logging.debug("Deleted the original command message."); - } - // Only lets this command be executed with a private message or in a group of people. - if (messageCreateEvent.isPrivateMessage() || messageCreateEvent.isGroupMessage()) { + if (event.getSlashCommandInteraction().getChannel().isPresent() && ( + event.getSlashCommandInteraction().getChannel().get().asServerChannel().isPresent() + || event.getSlashCommandInteraction().getChannel().get().asGroupChannel().isPresent() + )) { EmbedBuilder notAPrivateMessage = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) + .setAuthor(author) .setTitle("Error!") .setColor(Color.RED) .addField("Not a private message error", "This command can only be used via direct message or in group messages with this bot."); - messageCreateEvent.getChannel().sendMessage(notAPrivateMessage); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(notAPrivateMessage).respond(); return; } - // On wrong usage, aka. when you pass arguments. - if (command.getStringArgument(0).isEmpty()) { - messageCreateEvent.getChannel().sendMessage(helpMessage); - return; - } - - // Only execute if te message Author is a user and not a webhook. - if (messageCreateEvent.getMessageAuthor().asUser().isPresent()) { - // noAccountEmbed.addField("","Sorry, user with tag " + ); - Logging.debug("User \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" executed command \"unlink\". Parsing User..."); - User user = messageCreateEvent.getMessageAuthor().asUser().get(); + Logging.debug("User \"" + author.getName() + "\" executed command \"" + event.getSlashCommandInteraction().getCommandName() + "\"."); - Optional optionalSenderAccount = Account.getByDiscordUser(user); + Optional optionalSenderAccount = Account.getByDiscordUser(author); - // If the user does not have an account. - if (optionalSenderAccount.isEmpty()) { - Logging.debug("User does not have an account. Sending no account Embed."); - noAccountEmbed.addField("You don't have account!", "You can only whisper, when you have an account! Use \"" + discordCommandPrefix + "link\" to create one!"); - messageCreateEvent.getChannel().sendMessage(noAccountEmbed); - return; - } - - StringBuilder userID = new StringBuilder(); - for (char c : command.getStringArgument(0).get().toCharArray()) { - if (c != '<' && c != '>' && c != '!' && c != '@') - userID.append(c); - } - - Account receiver; - Optional optionalAccount = Account.getByUsername(command.getStringArgument(0).get()); + // If the user does not have an account. + if (optionalSenderAccount.isEmpty()) { + Logging.debug("User does not have an account. Sending no account Embed."); + noAccountEmbed.addField("You don't have account!", "You can only whisper, when you have an account! Use \"" + discordCommandPrefix + "link\" to create one!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noAccountEmbed).respond(); + return; + } - if (optionalAccount.isPresent()) { - receiver = optionalAccount.get(); - Logging.debug("Found Account with tag " + receiver.getUsername()); - } else { + Account receiver; + Optional optionalAccount; + // If no valid user was given, use the discord api instead. This won't throw an error and because the API + // can not have an account, the execution will fail, with a no account embed. + if (event.getSlashCommandInteraction().getFirstOption().isPresent()) { + if (event.getSlashCommandInteraction().getFirstOption().get().requestUserValue().isPresent()) { try { - User userReceiver = discordApi.getUserById(Long.parseLong(userID.toString())).join(); - - if (userReceiver == null) { - Logging.debug("Could not get user by ID " + userID); - noAccountEmbed.addField("NoSuchUser", "No Discord Account could be found for the user with ID " + userID); - messageCreateEvent.getChannel().sendMessage(noAccountEmbed); - return; - } - - Optional optionalReceiverAccount = Account.getByDiscordUser(userReceiver); - Logging.debug("Getting the account for user \"" + command.getStringArgument(0).get() + "\"..."); - // Get the account and some information about it. - if (optionalReceiverAccount.isEmpty()) { - Logging.debug("Discord User " + userReceiver.getName() + " does not have an account. Sending noAccountEmbed."); - noAccountEmbed.addField("No Account", "Discord user " + userReceiver.getName() + " does not have a linked minecraft account. They should use \"" + discordCommandPrefix + "link\" to get one!"); - messageCreateEvent.getChannel().sendMessage(noAccountEmbed); - return; - } - receiver = optionalReceiverAccount.get(); - - } catch (NumberFormatException ex) { - messageCreateEvent.getChannel().sendMessage(helpMessage); - Logging.debug("Wrong usage of Discord Whisper command. Sending help embed..."); + optionalAccount = Account.getByDiscordUser(event.getSlashCommandInteraction().getFirstOption().get().requestUserValue().get().join()); + } catch (CompletionException e) { + Logging.debug("User " + event.getSlashCommandInteraction().getUser().getName() + " executed command \"" + event.getSlashCommandInteraction().getCommandName() + "\"; Response: No Such User"); + noAccountEmbed.addField("Discord User Not Found", "The User you entered is invalid. Please try again!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noAccountEmbed).respond(); return; } - } - - EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() - .setAuthor(messageCreateEvent.getMessageAuthor()) - .setTitle("PlayerNotOnlineError") - .setColor(Color.RED) - .addField("Player Not Online", "You cannot whisper to an offline player!"); - - OfflinePlayer player = receiver.getPlayer(); - if (player == null || !receiver.getPlayer().isOnline()) { - messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); - Logging.debug("Player not online. Cannot whisper message."); - return; - } - - Player onlinePlayer = player.getPlayer(); - if (onlinePlayer == null) { - messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); - Logging.debug("Player not online. Cannot whisper message."); + } else { + noAccountEmbed.addField("Discord User Not Found", "The User you entered is invalid. Please try again!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noAccountEmbed).respond(); return; } + } else { + // Should not be reached! + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); + return; + } - if (command.getStringArgument(1).isEmpty()) { - messageCreateEvent.getChannel().sendMessage(playerNotOnlineEmbed); - Logging.debug("Player not online. Cannot whisper message."); - return; + if (optionalAccount.isPresent()) { + receiver = optionalAccount.get(); + Logging.debug("Found Account with tag " + receiver.getUsername()); + } else { + if (event.getSlashCommandInteraction().getFirstOptionUserValue().isPresent()) { + Logging.debug("User " + event.getSlashCommandInteraction().getUser().getName() + " executed command \"" + event.getSlashCommandInteraction().getCommandName() + "\"; Response: User \"" + event.getSlashCommandInteraction().getFirstOptionUserValue().get().getName() + "\" does not have an account!"); + noAccountEmbed.addField("User has no account", "Sorry, but we could not find an account to whisper to for " + event.getSlashCommandInteraction().getFirstOptionUserValue().get().getMentionTag() + ". Please try again or tell them to use \"/link\"!"); + } else { + Logging.debug("User " + event.getSlashCommandInteraction().getUser().getName() + " executed command \"" + event.getSlashCommandInteraction().getCommandName() + "\"; Response: No Such User"); + noAccountEmbed.addField("Discord User Not Found", "The User you entered is invalid. Please try again!"); } + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noAccountEmbed).respond(); + return; + } - Logging.debug("Building whisper message..."); - StringBuilder messageBuilder = new StringBuilder(); + EmbedBuilder playerNotOnlineEmbed = new EmbedBuilder() + .setAuthor(author) + .setTitle("PlayerNotOnlineError") + .setColor(Color.RED) + .addField("Player Not Online", "You cannot whisper to an offline player!"); - for (int i = 1; i < command.getArguments().length; ++i) { - if (i != 1) - messageBuilder.append(' '); - Optional messagePart = command.getStringArgument(i); - if (messagePart.isPresent()) - messageBuilder.append(messagePart.get()); - else - break; - } - String message = messageBuilder.toString(); + OfflinePlayer player = receiver.getPlayer(); + if (player == null || !receiver.getPlayer().isOnline()) { + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(playerNotOnlineEmbed).respond(); + Logging.debug("Player not online. Cannot whisper message."); + return; + } - Logging.debug("Whisper message built! Sending it..."); - //Logging.info("User " + ChatColor.GRAY + messageCreateEvent.getMessageAuthor().getDisplayName() + ChatColor.RESET + "whispered the following to minecraft user " + ChatColor.GRAY + onlinePlayer.getDisplayName() + ChatColor.RESET + ": " + ChatColor.AQUA + message); - Settings.minecraftServer.getConsoleSender().sendMessage(whisperPrefix(messageCreateEvent, false, receiver.getUsername()) + message); - onlinePlayer.sendMessage(whisperPrefix(messageCreateEvent, true, "") + message); - } else { - Logging.debug("MessageAuthor \"" + messageCreateEvent.getMessageAuthor().getDisplayName() + "\" is not a User! Sending Error embed..."); - messageCreateEvent.getChannel().sendMessage( - new EmbedBuilder() - .setAuthor(discordApi.getYourself()) - .setTitle("Error!") - .setColor(Color.RED) - .addField("UserParsingError", "You are not a user, so you can't have an account!") - ); + Player onlinePlayer = player.getPlayer(); + if (onlinePlayer == null) { + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(playerNotOnlineEmbed).respond(); + Logging.debug("Player not online. Cannot whisper message."); + return; } + String message = event.getSlashCommandInteraction().getSecondOptionStringValue().orElse(null); + //Logging.info("User " + ChatColor.GRAY + author.getName() + ChatColor.RESET + "whispered the following to minecraft user " + ChatColor.GRAY + onlinePlayer.getDisplayName() + ChatColor.RESET + ": " + ChatColor.AQUA + message); + Settings.minecraftServer.getConsoleSender().sendMessage(whisperPrefix(event, false, receiver.getUsername()) + message); + onlinePlayer.sendMessage(whisperPrefix(event, true, "") + message); + + event.getSlashCommandInteraction().createImmediateResponder().addEmbed( + new EmbedBuilder() + .setAuthor(author) + .setColor(Color.GREEN) + .setTitle("Success!") + .addField("You whispered to " + onlinePlayer.getName() + ":", message) + ).respond(); } /** * The method that creates a prefix for whispered messages, according to the settings.
* This prefix can either be a one-liner or a two-liner. - * @param messageCreateEvent The event that stores all the information about the whisper message sender. + * @param event The event that stores all the information about the whisper message sender. * @param playerIsReceiver Receiver is a player; if not, it will be the console so don't display line * breaks and emoji if this is set to false. * @param receiver The "name" of the receiver. * @return The prefix to add to the message. */ - private static String whisperPrefix(MessageCreateEvent messageCreateEvent, boolean playerIsReceiver, String receiver) { + private static String whisperPrefix(SlashCommandCreateEvent event, boolean playerIsReceiver, String receiver) { String first = ""; String last; if (Settings.shortMsg) { @@ -259,7 +184,7 @@ private static String whisperPrefix(MessageCreateEvent messageCreateEvent, boole } return first + - messageCreateEvent.getMessageAuthor().getDisplayName() + + event.getSlashCommandInteraction().getUser().getName() + last; } } \ No newline at end of file From 54bd56f62ef8d8e8270f47382f5e00e40d866547 Mon Sep 17 00:00:00 2001 From: GitHub Date: Wed, 14 Jul 2021 23:58:40 +0200 Subject: [PATCH 067/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug,=20where?= =?UTF-8?q?=20the=20bot=20would=20send=20an=20empty=20message=20to=20the?= =?UTF-8?q?=20minecraft=20chat=20from=20itself,=20when=20it=20sent=20a=20p?= =?UTF-8?q?rivate=20message=20as=20the=20response=20to=20a=20slash=20comma?= =?UTF-8?q?nd=20in=20a=20private=20chat.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/discord/DiscordListener.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/DiscordListener.java b/src/main/java/com/github/mafelp/discord/DiscordListener.java index 8fcf724..0a5fc92 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordListener.java +++ b/src/main/java/com/github/mafelp/discord/DiscordListener.java @@ -42,6 +42,14 @@ public void onMessageCreate(MessageCreateEvent event) { if (event.getReadableMessageContent().startsWith(Settings.discordCommandPrefix)) return; + /* + * If the message is empty and only houses an embed. + * + * This embed can not be displayed in the in-game chat and would therefore be an empty message. + */ + if (event.getReadableMessageContent().equalsIgnoreCase("")) + return; + // Send the readable content of the message into the minecraft chat // for everyone to read. From 538c3be2a0e92ae714e52ba7154af3376c892409 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 16 Jul 2021 22:52:39 +0200 Subject: [PATCH 068/158] =?UTF-8?q?=E2=9E=95=20Added=20slash=20commands=20?= =?UTF-8?q?on=20server=20info=20message=20This=20message=20in=20being=20di?= =?UTF-8?q?splayed=20on=20each=20startup=20of=20the=20server=20and=20gives?= =?UTF-8?q?=20the=20user=20information=20about=20how=20to=20enable=20slash?= =?UTF-8?q?=20commands=20on=20the=20server.=20This=20is=20due=20to=20a=20l?= =?UTF-8?q?imitation=20of=20discord,=20on=20which=20bots=20have=20to=20be?= =?UTF-8?q?=20specially=20authorised=20to=20add=20slash=20commands=20to=20?= =?UTF-8?q?the=20server.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 1d427f5..8fb89bd 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -11,14 +11,12 @@ import org.javacord.api.entity.permission.Permissions; import org.javacord.api.entity.permission.PermissionsBuilder; import org.javacord.api.interaction.SlashCommand; +import org.javacord.api.interaction.SlashCommandBuilder; import org.javacord.api.interaction.SlashCommandOption; import org.javacord.api.interaction.SlashCommandOptionType; import java.io.*; -import java.util.Arrays; -import java.util.Collections; -import java.util.Locale; -import java.util.Objects; +import java.util.*; import java.util.concurrent.CompletionException; import static com.github.mafelp.utils.Settings.discordApi; @@ -101,6 +99,7 @@ public void run() { Logging.info(ChatColor.GREEN + "Successfully started the discord instance!"); Logging.info(ChatColor.RESET + "The bot invitation token is: " + discordApi.createBotInvite(botPermissions)); + Logging.info(ChatColor.YELLOW + "If you do not see any slash commands in your server, click this link and authorise this bot for your server: https://discord.com/api/oauth2/authorize?client_id=" + discordApi.getClientId() + "&scope=applications.commands"); } catch (IllegalStateException | CompletionException exception) { // If the API creation fails, // log an error to the console. @@ -129,38 +128,37 @@ public void run() { } private void registerSlashCommands() { + List slashCommands = new ArrayList<>(); + // Link command - SlashCommand.with("link", "A command to link your discord and minecraft accounts", + slashCommands.add(SlashCommand.with("link", "A command to link your discord and minecraft accounts", Collections.singletonList( SlashCommandOption.create(SlashCommandOptionType.INTEGER, "token", "The token used to link your accounts", false) ) - ).setDefaultPermission(true) - .createGlobal(discordApi) - .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + )); // Unlink command - SlashCommand.with("unlink", "Unlink your discord account from your minecraft account") - .setDefaultPermission(true) - .createGlobal(discordApi) - .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + slashCommands.add(SlashCommand.with("unlink", "Unlink your discord account from your minecraft account")); // Whisper and mcmsg commands - SlashCommand.with("whisper", "Whisper to your friends on the minecraft server!", + slashCommands.add(SlashCommand.with("whisper", "Whisper to your friends on the minecraft server!", Arrays.asList( SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) )) - .setDefaultPermission(true) - .createGlobal(discordApi) - .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); - SlashCommand.with("mcmsg", "Whisper to your friends on the minecraft server!", + ); + slashCommands.add(SlashCommand.with("mcmsg", "Whisper to your friends on the minecraft server!", Arrays.asList( SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) - )) - .setDefaultPermission(true) - .createGlobal(discordApi) - .thenAccept(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + ) + )); + + // Do the actual registering of the slash commands. + slashCommands.forEach(slashCommandBuilder -> + slashCommandBuilder.createGlobal(discordApi).thenAccept(slashCommand -> + Logging.info("Added global slash command \"" + slashCommand.getName() + "\"") + )); } /** From 66b2d0ec9077b7fac67b3022d15a8d4bddb452bc Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 16 Jul 2021 23:35:14 +0200 Subject: [PATCH 069/158] =?UTF-8?q?=E2=9E=95=20Migrated=20the=20CreateChan?= =?UTF-8?q?nelListener=20to=20slash=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 14 ++ .../commands/CreateChannelListener.java | 121 ++++-------------- .../commands/MainSlashCommandListener.java | 8 ++ 3 files changed, 46 insertions(+), 97 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 8fb89bd..9f2edeb 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -154,6 +154,20 @@ private void registerSlashCommands() { ) )); + slashCommands.add(SlashCommand.with("create", "Create a channel/role for syncing minecraft and discord messages", + Arrays.asList( + SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "channel", "Create a channel to sync minecraft messages to", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name the channel should have", true) + )), + SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "role", "Create a role which you can give the permission to read/write to channels", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name the channel should have", true) + )) + )) + //.setDefaultPermission(false) + ); + // Do the actual registering of the slash commands. slashCommands.forEach(slashCommandBuilder -> slashCommandBuilder.createGlobal(discordApi).thenAccept(slashCommand -> diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index 865ecbc..40d4fef 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -1,19 +1,16 @@ package com.github.mafelp.discord.commands; -import com.github.mafelp.utils.*; import com.github.mafelp.discord.ChannelAdmin; -import com.github.mafelp.utils.exceptions.CommandNotFinishedException; -import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; import org.javacord.api.entity.message.embed.EmbedBuilder; -import org.javacord.api.event.message.MessageCreateEvent; -import org.javacord.api.listener.message.MessageCreateListener; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; import java.awt.*; -import java.util.Arrays; import java.util.concurrent.CompletionException; -import static com.github.mafelp.utils.Logging.info; import static com.github.mafelp.utils.Settings.*; /** @@ -21,45 +18,17 @@ * As discord announced just today, there will be an update to the bot API, that'll be adding * slash command support. This class will be moved, if the update is available in this API. */ -public class CreateChannelListener implements MessageCreateListener { +public class CreateChannelListener { /** * The method called by the discord API, for every chat message. - * This method will filter them and execute commands accordingly. * @param event The event containing information about the message. */ - @Override - public void onMessageCreate(MessageCreateEvent event) { - // If the message is sent by the bot, return - if (event.getMessageAuthor().isYourself()) { - return; - } - - // If message does not start with the command prefix, return - // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || - // event.getReadableMessageContent() == null) - // return; - - // Gets the content of the message as strings (prints it, if debug is enabled) - String content = event.getReadableMessageContent(); - if (debug) - info("Readable Message content is: " + content); - - - // Tris to parse the command. - Command command; - try { - command = CommandParser.parseFromString(content); - } catch (CommandNotFinishedException | NoCommandGivenException e) { - Logging.logException(e, "Error parsing the command from the string..."); - return; - } - - if (debug) - info("Arguments are: " + command.getCommand() + " " + Arrays.toString(command.getArguments())); - + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); // help message for wrong usage EmbedBuilder helpMessage = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Usage", discordCommandPrefix + "createChannel ") .setColor(new Color(0xFFB500)) @@ -68,7 +37,7 @@ public void onMessageCreate(MessageCreateEvent event) { // error embed for server not present EmbedBuilder serverNotPresentError = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Server not present Error","Could not get the server. Maybe you sent this " + "message in a direct message?") @@ -77,12 +46,11 @@ public void onMessageCreate(MessageCreateEvent event) { ; EmbedBuilder successEmbed = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Success!") .addField("Successful channel creation", "Successfully created a new channel to sync minecraft message to!") .setColor(Color.GREEN) - .setFooter("") ; EmbedBuilder welcomeEmbed = new EmbedBuilder() @@ -96,71 +64,30 @@ public void onMessageCreate(MessageCreateEvent event) { .setFooter("Made by MaFeLP: https://github.com/mafelp") ; - // If the message is empty/if the arguments are none, return - if (command.getCommand() == null) - return; - - // Check if the message start with the command prefix - if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "createChannel")) - return; - - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { - Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); - Logging.debug("Deleted the original command message."); - } - - - // Checks the permission of the message author. - if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { - Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); - event.getChannel().sendMessage(CheckPermission.getPermissionDeniedEmbed(event.getMessageAuthor(), "create Channel")); - return; - } - + // TODO add permission to the command // get the first channel argument and checks, if it 'empty', but it exists. - if (command.getStringArgument(0).isPresent()) { - if (command.getStringArgument(0).get().equalsIgnoreCase("")) { - Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); - event.getChannel().sendMessage(helpMessage); - return; - } - } - - // If the command has a wrong number of arguments, send the help message and exit. - if (command.getArguments().length != 1) { - event.getChannel().sendMessage(helpMessage); + if (event.getSlashCommandInteraction().getSecondOptionStringValue().isEmpty()) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } - // Try getting the first argument. If it does not exist, send the help message and exit. - String name; - if (command.getStringArgument(0).isPresent()) - name = command.getStringArgument(0).get(); - else { - event.getChannel().sendMessage(helpMessage); + String name = event.getSlashCommandInteraction().getSecondOptionStringValue().get(); + if (name.equalsIgnoreCase("")) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } // If the server is present, create a new channel - if (event.getServer().isPresent()) { + if (event.getSlashCommandInteraction().getServer().isPresent()) { try { - ChannelAdmin.createChannel(name, event.getServer().get(), + ChannelAdmin.createChannel(name, event.getSlashCommandInteraction().getServer().get(), "Cross communication channel with the Minecraft Server " + Settings.serverName, - successEmbed, event.getChannel(), + successEmbed, event.getSlashCommandInteraction().createImmediateResponder(), welcomeEmbed); } catch (CompletionException exception) { - // Embed to send, when the bot does not have the required Permissions. - EmbedBuilder noPermissionEmbed = new EmbedBuilder() - .setAuthor(discordApi.getYourself()) - .setTitle("Error!") - .addField("PermissionDeniedException","Could not execute this command, because the bot lacks permissions to do so!") - .addField("how to fix", "Please refer to this projects website https://mafelp.github.io/MCDC/create-admin-role for instructions, on how to do so.") - .setColor(Color.RED) - ; - - event.getChannel().sendMessage(noPermissionEmbed); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(serverNotPresentError).respond(); Logging.info(ChatColor.RED + "Could not execute createChannel command. Do not have the required permissions."); } } else { @@ -168,8 +95,8 @@ public void onMessageCreate(MessageCreateEvent event) { Settings.minecraftServer.getLogger().warning(Settings.prefix + "Could not execute Command createChannel"); // Reply to the sender with the error embed - event.getChannel().sendMessage(serverNotPresentError).thenAcceptAsync(message -> - Logging.info("Send error embed to " + event.getMessageAuthor().getDisplayName()) + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(serverNotPresentError).respond().thenAcceptAsync(message -> + Logging.info("Send error embed to " + author.getName()) ); } } diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index 32644ce..e3f8e24 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -8,11 +8,19 @@ public class MainSlashCommandListener implements SlashCommandCreateListener { @Override public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent) { + Logging.debug("Slash command interaction caught: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()); switch (slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()) { case "setup" -> {} case "link" -> LinkListener.onSlashCommand(slashCommandCreateEvent); case "unlink" -> UnlinkListener.onSlashCommand(slashCommandCreateEvent); case "whisper", "mcmsg" -> WhisperListener.onSlashCommand(slashCommandCreateEvent); + case "create" -> { + switch (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOptionStringValue().orElse("")) { + case "channel" -> CreateChannelListener.onSlashCommand(slashCommandCreateEvent); + case "role" -> {} + default -> Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": no First option given!"); + } + } default -> Logging.info(ChatColor.RED + "Wait. Wait? This command is not recognised: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName() + " and this should not have happened!"); } } From d8a6ba44eeaa93705fe2ac3b7413c664f50540f3 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 16 Jul 2021 23:37:22 +0200 Subject: [PATCH 070/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Moved=20the=20perm?= =?UTF-8?q?ission=20TODO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/discord/DiscordMain.java | 2 ++ .../github/mafelp/discord/commands/CreateChannelListener.java | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 9f2edeb..400d6b5 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -154,6 +154,7 @@ private void registerSlashCommands() { ) )); + // Create role and create channel commands slashCommands.add(SlashCommand.with("create", "Create a channel/role for syncing minecraft and discord messages", Arrays.asList( SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "channel", "Create a channel to sync minecraft messages to", @@ -165,6 +166,7 @@ private void registerSlashCommands() { SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name the channel should have", true) )) )) + // TODO make command only executable with certain permissions //.setDefaultPermission(false) ); diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index 40d4fef..6d0043b 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -64,7 +64,6 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { .setFooter("Made by MaFeLP: https://github.com/mafelp") ; - // TODO add permission to the command // get the first channel argument and checks, if it 'empty', but it exists. if (event.getSlashCommandInteraction().getSecondOptionStringValue().isEmpty()) { Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); From c221566e434f52f31443b68965d595c3e3eae071 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 16 Jul 2021 23:38:06 +0200 Subject: [PATCH 071/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20the=20C?= =?UTF-8?q?hannelAdmin=20to=20use=20slash=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/discord/ChannelAdmin.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/ChannelAdmin.java b/src/main/java/com/github/mafelp/discord/ChannelAdmin.java index 2585654..79b4901 100644 --- a/src/main/java/com/github/mafelp/discord/ChannelAdmin.java +++ b/src/main/java/com/github/mafelp/discord/ChannelAdmin.java @@ -2,17 +2,15 @@ import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; -import com.github.mafelp.minecraft.skins.Skin; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.javacord.api.entity.channel.Channel; import org.javacord.api.entity.channel.ServerTextChannel; import org.javacord.api.entity.channel.ServerTextChannelBuilder; -import org.javacord.api.entity.channel.TextChannel; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.server.Server; +import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder; -import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletionException; @@ -52,12 +50,12 @@ protected static List getMessageChannels() { * @param server server on which to create the channel on * @param topic the topic the channel should have * @param successEmbed the embed to be sent into successChannel after completion - * @param successChannel the channel successEmbed is sent to + * @param responder The slash command responder to send the success message to. * @param welcomeEmbed the embed to sent to the newly created channel * @return the newly created channel */ public static ServerTextChannel createChannel(String name, Server server, String topic, - EmbedBuilder successEmbed, TextChannel successChannel, + EmbedBuilder successEmbed, InteractionImmediateResponseBuilder responder, EmbedBuilder welcomeEmbed) throws CompletionException { // Create the Channel ServerTextChannel serverTextChannel = new ServerTextChannelBuilder(server) @@ -74,7 +72,7 @@ public static ServerTextChannel createChannel(String name, Server server, String // Add a field containing a link to the new channel and send the embed successEmbed.addField("New Channel", "The new channel is: <#" + serverTextChannel.getIdAsString() + ">"); - successChannel.sendMessage(successEmbed); + responder.addEmbed(successEmbed).respond(); // Also send the welcome embed into the newly created channel serverTextChannel.sendMessage(welcomeEmbed); From bef8d18281c79f0eac4b270815c6e779e3008d34 Mon Sep 17 00:00:00 2001 From: GitHub Date: Fri, 16 Jul 2021 23:41:21 +0200 Subject: [PATCH 072/158] =?UTF-8?q?=F0=9F=9A=AB=20Disabled=20channel=20cre?= =?UTF-8?q?ation=20in=20the=20setup=20command=20This=20was=20done,=20becau?= =?UTF-8?q?se=20the=20method,=20handling=20the=20Actual=20creation=20(Chan?= =?UTF-8?q?nelAdmin#createChannel)=20now=20only=20accepts=20ImmediateRespo?= =?UTF-8?q?nderBuilders.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/discord/commands/SetupListener.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index e6f4188..03a2f4a 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -174,9 +174,16 @@ public void onMessageCreate(MessageCreateEvent event) { return; } - ServerTextChannel serverTextChannel = ChannelAdmin.createChannel(name, event.getServer().get(), "Minecraft Cross platform communication.", successEmbed, event.getServerTextChannel().get(), welcomeEmbed); - - Logging.info("Added channel \"" + serverTextChannel.getName() + "\" and role \"" + role.getName() + "\" to server \"" + event.getServer().get().getName() + "\"!"); + // TODO migrate to slash commands + // ServerTextChannel serverTextChannel = ChannelAdmin.createChannel(name, event.getServer().get(), "Minecraft Cross platform communication.", successEmbed, event.getServerTextChannel().get(), welcomeEmbed); + //Logging.info("Added channel \"" + serverTextChannel.getName() + "\" and role \"" + role.getName() + "\" to server \"" + event.getServer().get().getName() + "\"!"); + Logging.info(ChatColor.RED + "Creating a text channel with setup is currently not supported. Please try again later."); + event.getServerTextChannel().get().sendMessage(new EmbedBuilder() + .setAuthor(event.getApi().getYourself()) + .setColor(Color.RED) + .setTitle("Feature unavailable") + .setDescription("Due to the current migration process to slash commands, it is currently not supported to create text channels with the setup command. You can still do this manually, by using the \"/create channel\" command.") + ).join(); // If this exception is thrown, the bot either does not have the correct permissions to create channels and Roles, // send the user an embed explaining the issue. From 124f02251615c006b994a37d4f7a1fc6bedbc4a8 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 20:48:01 +0200 Subject: [PATCH 073/158] =?UTF-8?q?=F0=9F=94=8D=20Added=20argument=20check?= =?UTF-8?q?s=20These=20checks=20are=20a=20prevention=20of=20error=20stack?= =?UTF-8?q?=20traces=20in=20the=20slash=20commands.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../discord/commands/MainSlashCommandListener.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index e3f8e24..ac46dee 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -15,13 +15,17 @@ public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent case "unlink" -> UnlinkListener.onSlashCommand(slashCommandCreateEvent); case "whisper", "mcmsg" -> WhisperListener.onSlashCommand(slashCommandCreateEvent); case "create" -> { - switch (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOptionStringValue().orElse("")) { - case "channel" -> CreateChannelListener.onSlashCommand(slashCommandCreateEvent); - case "role" -> {} - default -> Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": no First option given!"); + if (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().isPresent()) { + switch (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().get().getName()) { + case "channel" -> CreateChannelListener.onSlashCommand(slashCommandCreateEvent); + case "role" -> {} + default -> Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": First option is: " + slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().get().getName()); + } + } else { + Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": no First option given!"); } } default -> Logging.info(ChatColor.RED + "Wait. Wait? This command is not recognised: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName() + " and this should not have happened!"); } } -} +} \ No newline at end of file From a3db0a436db51d6333c52f3b44afb57144d2351c Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 21:09:48 +0200 Subject: [PATCH 074/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20/create?= =?UTF-8?q?=20role=20to=20a=20slash=20command.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../discord/commands/CreateRoleListener.java | 97 ++++++------------- .../commands/MainSlashCommandListener.java | 2 +- 2 files changed, 30 insertions(+), 69 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index bf9052b..8bcf238 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -1,14 +1,13 @@ package com.github.mafelp.discord.commands; import com.github.mafelp.discord.RoleAdmin; -import com.github.mafelp.utils.*; -import com.github.mafelp.utils.exceptions.CommandNotFinishedException; -import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Logging; import org.bukkit.ChatColor; import org.javacord.api.entity.message.embed.EmbedBuilder; -import org.javacord.api.entity.permission.*; -import org.javacord.api.event.message.MessageCreateEvent; -import org.javacord.api.listener.message.MessageCreateListener; +import org.javacord.api.entity.permission.Role; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; import java.awt.*; import java.util.concurrent.CompletionException; @@ -20,40 +19,18 @@ * CreateRoleListenerClass implements role creation with the command prefix+createRole name * on the server, where the command was executed. */ -public class CreateRoleListener implements MessageCreateListener { +public class CreateRoleListener { /** * The method that is being called every time a message was sent to the discord channel.
* It first checks if the content of the message is the command createRole and then creates the role accordingly. * @param event The event passed in by the api containing information about the message. */ - @Override - public void onMessageCreate(MessageCreateEvent event) { - // If the message is sent by the bot, return - if (event.getMessageAuthor().isYourself()) { - return; - } - - // If message does not start with the command prefix, return - // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || - // event.getReadableMessageContent() == null) - // return; - - - // Gets the content of the message as strings (prints it, if debug is enabled) - String content = event.getReadableMessageContent(); - - // Tries parsing the command. If it fails, exit. The error handling is being done by the CreateChannelListener. - Command command; - try { - command = CommandParser.parseFromString(content); - } catch (CommandNotFinishedException | NoCommandGivenException e) { - // Logging.logException(e, "Error parsing hte command from the string..."); - return; - } + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); // help message for wrong usage EmbedBuilder helpMessage = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Usage", discordCommandPrefix + "createRole ") .setFooter("Help message for command \"createRole\"") @@ -62,7 +39,7 @@ public void onMessageCreate(MessageCreateEvent event) { // error embed for server not present EmbedBuilder serverNotPresentError = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Server not present Error","Could not get the server. Maybe you sent this " + "message in a direct message?") @@ -71,7 +48,7 @@ public void onMessageCreate(MessageCreateEvent event) { ; EmbedBuilder successEmbed = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Success!") .addField("Successful role creation", "Successfully created a new role to sync permissions for the channel to!") @@ -88,38 +65,24 @@ public void onMessageCreate(MessageCreateEvent event) { .setColor(Color.RED) ; - // If the message is empty/if the arguments are none, return - if (command.getCommand() == null) - return; - - if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "createRole")) + // If the server could not be found, send an error message and exit. + if (event.getSlashCommandInteraction().getServer().isEmpty()) { + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(serverNotPresentError).respond(); + Logging.info("Could not create the new Server Role: Server is not present. Sending Error Reply."); return; - - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { - Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); - Logging.debug("Deleted the original command message."); } // Checks the permission of the message author. - if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { - Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"createChannel\"!"); - event.getChannel().sendMessage(CheckPermission.getPermissionDeniedEmbed(event.getMessageAuthor(), "create Role")); + if (!CheckPermission.hasAdminPermission(author, event.getSlashCommandInteraction().getServer().get())) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(CheckPermission.getPermissionDeniedEmbed(author, "create Role")); return; } // If the user passed a wrong number of arguments, send the help message and exit. - if (command.getStringArgument(0).isEmpty() || command.getStringArgument(1).isPresent()) { - info("Person " + ChatColor.GRAY + event.getMessageAuthor().getDisplayName() + ChatColor.RESET + " used the command createRole wrong. Sending help embed."); - event.getChannel().sendMessage(helpMessage); - return; - } - - // If the server could not be found, send an error message and exit. - if (event.getServer().isEmpty()) { - event.getChannel().sendMessage(serverNotPresentError); - Logging.info("Could not create the new Server Role: Server is not present. Sending Error Reply."); + if (event.getSlashCommandInteraction().getSecondOptionStringValue().isEmpty()) { + info("Person " + ChatColor.GRAY + author.getName() + ChatColor.RESET + " used the command createRole wrong. Sending help embed."); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } @@ -128,27 +91,25 @@ public void onMessageCreate(MessageCreateEvent event) { // Try creating the new Role try { - if (event.getChannel().asServerTextChannel().isPresent()) { - Role role = RoleAdmin.createNewRole(event.getServer().get(), command.getStringArgument(0).get(), successEmbed, event.getChannel().asServerTextChannel().get()); - event.getMessageAuthor().asUser().ifPresent(user -> { - user.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); - info("Added role \"" + role.getName() + "\" to player \"" + user.getName() + "\"."); - }); + if (event.getSlashCommandInteraction().getChannel().isPresent() && event.getSlashCommandInteraction().getChannel().get().asServerTextChannel().isPresent()) { + Role role = RoleAdmin.createNewRole(event.getSlashCommandInteraction().getServer().get(), event.getSlashCommandInteraction().getSecondOptionStringValue().get(), successEmbed, event.getSlashCommandInteraction().getChannel().get().asServerTextChannel().get()); + author.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); + info("Added role \"" + role.getName() + "\" to player \"" + author.getName() + "\"."); } else { minecraftServer.getLogger().warning(prefix + "Could not get the ServerTextChannel. Sending error embed."); - event.getChannel().sendMessage( + event.getSlashCommandInteraction().createImmediateResponder().addEmbed( new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setColor(Color.RED) .setTitle("Error!") .addField("ServerTextChannelNotPresentError", "Could not get this Channel as a server text channel. Maybe you sent this message in private message?") - ); + ).respond(); } // If this exception is thrown, the bot either does not have the permission to create a new channel or // the connection to the discord servers has been lost. } catch (CompletionException exception) { - event.getChannel().sendMessage(noPermissionEmbed); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noPermissionEmbed).respond(); Logging.info(ChatColor.RED + "Could not execute createRole command. Do not have the required permissions."); } } diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index ac46dee..48a389d 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -18,7 +18,7 @@ public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent if (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().isPresent()) { switch (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().get().getName()) { case "channel" -> CreateChannelListener.onSlashCommand(slashCommandCreateEvent); - case "role" -> {} + case "role" -> CreateRoleListener.onSlashCommand(slashCommandCreateEvent); default -> Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": First option is: " + slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().get().getName()); } } else { From 7d89f9189c214c07932e274340b60dcc810ff71c Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 21:11:08 +0200 Subject: [PATCH 075/158] =?UTF-8?q?=E2=9E=95=20Added=20admin=20permission?= =?UTF-8?q?=20check=20for=20type=20User=20This=20also=20requires=20you=20t?= =?UTF-8?q?o=20have=20a=20server=20given,=20on=20which=20you=20want=20to?= =?UTF-8?q?=20check=20the=20permission=20of.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/utils/CheckPermission.java | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/mafelp/utils/CheckPermission.java b/src/main/java/com/github/mafelp/utils/CheckPermission.java index 0c75b35..17bb644 100644 --- a/src/main/java/com/github/mafelp/utils/CheckPermission.java +++ b/src/main/java/com/github/mafelp/utils/CheckPermission.java @@ -8,14 +8,15 @@ import org.bukkit.entity.Player; import org.javacord.api.entity.message.MessageAuthor; import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.entity.server.Server; +import org.javacord.api.entity.user.User; import java.awt.*; import java.io.*; import java.util.Scanner; import static com.github.mafelp.utils.Logging.debug; -import static com.github.mafelp.utils.Settings.getConfiguration; -import static com.github.mafelp.utils.Settings.prefix; +import static com.github.mafelp.utils.Settings.*; /** * Class used to check permissions on Discord or on the Minecraft server @@ -28,7 +29,7 @@ public class CheckPermission { * @param action The action the person tried to do. Will be inserted into embed. * @return an embed to sent to the person. */ - public static EmbedBuilder getPermissionDeniedEmbed(final MessageAuthor messageAuthor, final String action) { + public static EmbedBuilder getPermissionDeniedEmbed(final User messageAuthor, final String action) { return new EmbedBuilder() .setAuthor(messageAuthor) .setTitle("Error") @@ -62,6 +63,29 @@ public static boolean hasAdminPermission (final MessageAuthor messageAuthor) { return false; } + /** + * Checks if a user is a server admin or in the permission.adminIDs list in the config.yml + * file. + * @param user The user to check the permissions from. + * @param server The server to check the if the user has admin permission on. + * @return if the person is authorized to do so. + */ + public static boolean hasAdminPermission (final User user, final Server server) { + // Checking if the sender has the required permissions + if (user.isBotOwner()) + return true; + + if (server.isAdmin(user)) + return true; + + for (long person : getConfiguration().getLongList("permission.adminIDs")) { + if (user.getId() == person) + return true; + } + + return false; + } + /** * Checks if a user a server admin or in the permissions.botAdminIDs list in the * config.yml file. From 93455b4b28e89ffa14c5aea979e1d289e321bed0 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 21:19:43 +0200 Subject: [PATCH 076/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20RoleAdm?= =?UTF-8?q?in=20to=20respond=20correctly=20to=20slash=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/discord/RoleAdmin.java | 17 ++++++++++------- .../discord/commands/CreateRoleListener.java | 2 +- .../mafelp/discord/commands/SetupListener.java | 4 ++-- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/RoleAdmin.java b/src/main/java/com/github/mafelp/discord/RoleAdmin.java index 933b001..4279b53 100644 --- a/src/main/java/com/github/mafelp/discord/RoleAdmin.java +++ b/src/main/java/com/github/mafelp/discord/RoleAdmin.java @@ -1,10 +1,11 @@ package com.github.mafelp.discord; import org.bukkit.ChatColor; -import org.javacord.api.entity.channel.ServerTextChannel; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.permission.*; import org.javacord.api.entity.server.Server; +import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder; +import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.concurrent.CompletionException; @@ -21,12 +22,13 @@ public class RoleAdmin { * Method creates a new Role on a server with the specified name. * @param server The server to create the new role on. * @param name The name of the new role. - * @param successEmbed The embed to sent the user on success. - * @param successChannel The channel to sent the successEmbed to. + * @param successEmbed The Embed to send on a success. + * @param successBuilder The immediate responseBuilder to answer to the slash commands. * @return The newly created role */ public static Role createNewRole(Server server, String name, - EmbedBuilder successEmbed, ServerTextChannel successChannel) throws CompletionException { + @Nullable EmbedBuilder successEmbed, + @Nullable InteractionImmediateResponseBuilder successBuilder) throws CompletionException { // Set the permissions the new role should have. Permissions permissions = new PermissionsBuilder() .setAllowed(PermissionType.ADD_REACTIONS) @@ -75,9 +77,10 @@ public static Role createNewRole(Server server, String name, info("Created new Role " + ChatColor.GRAY + role.getName() + ChatColor.RESET + " on server " + ChatColor.RESET + server.getName() + "!"); // Send the success embed, if one exists. - if (successEmbed != null) - successChannel.sendMessage(successEmbed.addField("New Role", "The new role is: " + role.getMentionTag() + "!") - .addField("Usage:", "Give the role to any members that should be allowed to view and write to the minecraft channel. Later this will get added automatically with linking!")); + if (successEmbed != null && successBuilder != null) + successBuilder.addEmbed(successEmbed.addField("New Role", "The new role is: " + role.getMentionTag() + "!") + .addField("Usage:", "Give the role to any members that should be allowed to view and write to the minecraft channel. Later this will get added automatically with linking!") + ).respond(); discordApi.getYourself().addRole(role, "MCDC needs to see the channel as well!"); info("Added role \"" + role.getName() + "\" to the discord API."); diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index 8bcf238..6695831 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -92,7 +92,7 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { // Try creating the new Role try { if (event.getSlashCommandInteraction().getChannel().isPresent() && event.getSlashCommandInteraction().getChannel().get().asServerTextChannel().isPresent()) { - Role role = RoleAdmin.createNewRole(event.getSlashCommandInteraction().getServer().get(), event.getSlashCommandInteraction().getSecondOptionStringValue().get(), successEmbed, event.getSlashCommandInteraction().getChannel().get().asServerTextChannel().get()); + Role role = RoleAdmin.createNewRole(event.getSlashCommandInteraction().getServer().get(), event.getSlashCommandInteraction().getSecondOptionStringValue().get(), successEmbed, event.getSlashCommandInteraction().createImmediateResponder()); author.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); info("Added role \"" + role.getName() + "\" to player \"" + author.getName() + "\"."); } else { diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index 03a2f4a..e1c41a0 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -118,7 +118,7 @@ public void onMessageCreate(MessageCreateEvent event) { // Checks the permission of the message author. if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"setup\"!"); - event.getChannel().sendMessage(CheckPermission.getPermissionDeniedEmbed(event.getMessageAuthor(), "setup the server")); + //event.getChannel().sendMessage(CheckPermission.getPermissionDeniedEmbed(event.getMessageAuthor(), "setup the server")); return; } @@ -161,7 +161,7 @@ public void onMessageCreate(MessageCreateEvent event) { // try to create the role. try { - Role role = RoleAdmin.createNewRole(event.getServer().get(), name, null, event.getChannel().asServerTextChannel().get()); + Role role = RoleAdmin.createNewRole(event.getServer().get(), name, null, null); event.getMessageAuthor().asUser().ifPresent(user -> { user.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); From 42918ee5efd6f2ae637c93670dde2b84b78267b6 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 21:29:14 +0200 Subject: [PATCH 077/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Migrated=20.setup?= =?UTF-8?q?=20to=20a=20slash=20command=20Now=20use=20/setup=20=20to?= =?UTF-8?q?=20create=20a=20role=20and=20a=20channel=20for=20message=20sync?= =?UTF-8?q?ing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/MainSlashCommandListener.java | 2 +- .../discord/commands/SetupListener.java | 128 ++++-------------- 2 files changed, 29 insertions(+), 101 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index 48a389d..bd81e1e 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -10,7 +10,7 @@ public class MainSlashCommandListener implements SlashCommandCreateListener { public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent) { Logging.debug("Slash command interaction caught: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()); switch (slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()) { - case "setup" -> {} + case "setup" -> SetupListener.onSlashCommand(slashCommandCreateEvent); case "link" -> LinkListener.onSlashCommand(slashCommandCreateEvent); case "unlink" -> UnlinkListener.onSlashCommand(slashCommandCreateEvent); case "whisper", "mcmsg" -> WhisperListener.onSlashCommand(slashCommandCreateEvent); diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index e1c41a0..3d4cea7 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -2,15 +2,14 @@ import com.github.mafelp.discord.ChannelAdmin; import com.github.mafelp.discord.RoleAdmin; -import com.github.mafelp.utils.*; -import com.github.mafelp.utils.exceptions.CommandNotFinishedException; -import com.github.mafelp.utils.exceptions.NoCommandGivenException; +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Logging; import org.bukkit.ChatColor; import org.javacord.api.entity.channel.ServerTextChannel; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.permission.Role; -import org.javacord.api.event.message.MessageCreateEvent; -import org.javacord.api.listener.message.MessageCreateListener; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; import java.awt.*; import java.util.concurrent.CompletionException; @@ -21,40 +20,18 @@ /** * discord channel setup command class. This commands creates a new role and channel based on the arguments. */ -public class SetupListener implements MessageCreateListener { +public class SetupListener { /** * The method that is being called every time a message was sent to the discord channel.
* It first checks if the content of the message is the command setup and then creates a role and channel accordingly. * @param event The event passed in by the api containing information about the message. */ - @Override - public void onMessageCreate(MessageCreateEvent event) { - // If the message is sent by the bot, return - if (event.getMessageAuthor().isYourself()) { - return; - } - - // If message does not start with the command prefix, return - // if (event.getReadableMessageContent().startsWith(discordCommandPrefix) || - // event.getReadableMessageContent() == null) - // return; - - - // Gets the content of the message as strings (prints it, if debug is enabled) - String content = event.getReadableMessageContent(); - - // If the command could not be passed, exit. Error handling is done by the CreateChannelListener. - Command command; - try { - command = CommandParser.parseFromString(content); - } catch (CommandNotFinishedException | NoCommandGivenException e) { - // Logging.logException(e, "Error parsing hte command from the string..."); - return; - } - + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); + // help message for wrong usage EmbedBuilder helpMessage = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Usage", discordCommandPrefix + "setup ") .addField("Functionality", "Adds a role with the specified name and an according channel in which only the role can see and write to it.") @@ -64,7 +41,7 @@ public void onMessageCreate(MessageCreateEvent event) { // error embed for server not present EmbedBuilder serverNotPresentError = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Error") .addField("Server not present Error","Could not get the server. Maybe you sent this " + "message in a direct message?") @@ -74,7 +51,7 @@ public void onMessageCreate(MessageCreateEvent event) { // the embed sent on successful execution of the command. EmbedBuilder successEmbed = new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) + .setAuthor(author) .setTitle("Success!") .setColor(Color.GREEN) ; @@ -100,95 +77,46 @@ public void onMessageCreate(MessageCreateEvent event) { .setColor(Color.RED) ; - // If the message is empty/if the arguments are none, return - if (command.getCommand() == null) - return; - - // If the command is not equal to setup, do nothing and return. - if (!command.getCommand().equalsIgnoreCase(discordCommandPrefix + "setup")) + // If no server could be found, send an error message and exit. + if (event.getSlashCommandInteraction().getServer().isEmpty()) { + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(serverNotPresentError).respond(); + Logging.info("Could not setup the server: Server is not present. Sending Error Reply."); return; - - // Deletes the original message, if specified in the configuration under deleteDiscordCommandMessages - if (Settings.getConfiguration().getBoolean("deleteDiscordCommandMessages") && event.isServerMessage()) { - Logging.debug("Deleting original command message with ID: " + event.getMessage().getIdAsString()); - event.getMessage().delete("Specified in MCDC configuration: Was a command message.").join(); - Logging.debug("Deleted the original command message."); } // Checks the permission of the message author. - if (!CheckPermission.hasAdminPermission(event.getMessageAuthor())) { - Logging.info("User \"" + event.getMessageAuthor().getDisplayName() + "\" tried to execute command \"setup\"!"); - //event.getChannel().sendMessage(CheckPermission.getPermissionDeniedEmbed(event.getMessageAuthor(), "setup the server")); - return; - } - - // If the command has a wrong number of arguments, send the help embed and exit. - if (command.getStringArgument(0).isEmpty() || command.getStringArgument(1).isPresent()) { - info("Person " + ChatColor.GRAY + event.getMessageAuthor().getDisplayName() + ChatColor.RESET + " used the command setup wrong. Sending help embed."); - event.getChannel().sendMessage(helpMessage); + if (!CheckPermission.hasAdminPermission(author, event.getSlashCommandInteraction().getServer().get())) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"setup\"!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(CheckPermission.getPermissionDeniedEmbed(author, "setup the server")).respond(); return; } // If the first argument is empty, send the help message and exit. - if (command.getStringArgument(0).get().equalsIgnoreCase("")) { - info("Person " + ChatColor.GRAY + event.getMessageAuthor().getDisplayName() + ChatColor.RESET + " used the command setup wrong. Sending help embed."); - event.getChannel().sendMessage(helpMessage); - return; - } - - // If no server could be found, send an error message and exit. - if (event.getServer().isEmpty()) { - event.getChannel().sendMessage(serverNotPresentError); - Logging.info("Could not setup the server: Server is not present. Sending Error Reply."); + if (event.getSlashCommandInteraction().getFirstOptionStringValue().isEmpty()) { + info("Person " + ChatColor.GRAY + author.getName() + ChatColor.RESET + " used the command setup wrong. Sending help embed."); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } - // If the channel you sent your message to is not a TextChannel, send as error message and exit. - if (event.getChannel().asServerTextChannel().isEmpty()) { - minecraftServer.getLogger().warning(prefix + "Could not get the ServerTextChannel. Sending error embed."); - event.getChannel().sendMessage( - new EmbedBuilder() - .setAuthor(event.getMessageAuthor()) - .setColor(Color.RED) - .setTitle("Error!") - .addField("ServerTextChannelNotPresentError", "Could not get this Channel as a server text channel. Maybe you sent this message in private message?") - ); - - return; - } - - String name = command.getStringArgument(0).get(); + String name = event.getSlashCommandInteraction().getFirstOptionStringValue().get(); // try to create the role. try { - Role role = RoleAdmin.createNewRole(event.getServer().get(), name, null, null); + Role role = RoleAdmin.createNewRole(event.getSlashCommandInteraction().getServer().get(), name, null, null); - event.getMessageAuthor().asUser().ifPresent(user -> { - user.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); - info("Added role \"" + role.getName() + "\" to player \"" + user.getName() + "\"."); - }); + author.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); + info("Added role \"" + role.getName() + "\" to player \"" + author.getName() + "\"."); successEmbed.addField("Successful role creation", "Successfully created the new role " + role.getMentionTag() + " to sync permissions for the Minecraft Channels to."); - if (event.getServerTextChannel().isEmpty()) { - return; - } - - // TODO migrate to slash commands - // ServerTextChannel serverTextChannel = ChannelAdmin.createChannel(name, event.getServer().get(), "Minecraft Cross platform communication.", successEmbed, event.getServerTextChannel().get(), welcomeEmbed); - //Logging.info("Added channel \"" + serverTextChannel.getName() + "\" and role \"" + role.getName() + "\" to server \"" + event.getServer().get().getName() + "\"!"); + ServerTextChannel serverTextChannel = ChannelAdmin.createChannel(name, event.getSlashCommandInteraction().getServer().get(), "Minecraft Cross platform communication.", successEmbed, event.getSlashCommandInteraction().createImmediateResponder(), welcomeEmbed); + Logging.info("Added channel \"" + serverTextChannel.getName() + "\" and role \"" + role.getName() + "\" to server \"" + event.getSlashCommandInteraction().getServer().get() + "\"!"); Logging.info(ChatColor.RED + "Creating a text channel with setup is currently not supported. Please try again later."); - event.getServerTextChannel().get().sendMessage(new EmbedBuilder() - .setAuthor(event.getApi().getYourself()) - .setColor(Color.RED) - .setTitle("Feature unavailable") - .setDescription("Due to the current migration process to slash commands, it is currently not supported to create text channels with the setup command. You can still do this manually, by using the \"/create channel\" command.") - ).join(); // If this exception is thrown, the bot either does not have the correct permissions to create channels and Roles, // send the user an embed explaining the issue. } catch (CompletionException exception) { - event.getChannel().sendMessage(noPermissionEmbed); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(noPermissionEmbed).respond(); Logging.info(ChatColor.RED + "Could not execute Setup command. Do not have the required permissions."); } } From effd1f752e8a9451dd7564e858cca07d6cb185cc Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 21:32:24 +0200 Subject: [PATCH 078/158] =?UTF-8?q?=E2=9E=95=20Added=20/setup=20to=20the?= =?UTF-8?q?=20registering=20method.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/discord/DiscordMain.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 400d6b5..7f45e86 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -88,9 +88,6 @@ public void run() { .setToken(Settings.getApiToken()) // register listeners .addListener(DiscordListener::new) - //.addListener(CreateChannelListener::new) - //.addListener(CreateRoleListener::new) - //.addListener(SetupListener::new) .addListener(MainSlashCommandListener::new) // log the bot in and join the servers .login().join(); @@ -170,6 +167,15 @@ private void registerSlashCommands() { //.setDefaultPermission(false) ); + // Setup command + slashCommands.add(SlashCommand.with("setup","Creates and channel and a role for syncing minecraft and discord messages", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name of the role and the channel") + )) + // TODO make command only executable with certain permissions + //.setDefaultPermission(false) + ); + // Do the actual registering of the slash commands. slashCommands.forEach(slashCommandBuilder -> slashCommandBuilder.createGlobal(discordApi).thenAccept(slashCommand -> From d727b2abe3c926994cde51bec4ed5eb9725fd899 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 21 Jul 2021 22:52:39 +0200 Subject: [PATCH 079/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20bug=20in=20slash?= =?UTF-8?q?=20commands=20The=20slash=20command=20would=20not=20get=20the?= =?UTF-8?q?=20argument=20which=20contains=20the=20name=20for=20the=20role/?= =?UTF-8?q?channel.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/CreateChannelListener.java | 16 +++++++++++++--- .../discord/commands/CreateRoleListener.java | 19 +++++++++++++++---- .../discord/commands/SetupListener.java | 1 - 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index 6d0043b..77f781a 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -64,14 +64,24 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { .setFooter("Made by MaFeLP: https://github.com/mafelp") ; - // get the first channel argument and checks, if it 'empty', but it exists. - if (event.getSlashCommandInteraction().getSecondOptionStringValue().isEmpty()) { + // Checks if the first argument after the first argument exists. + if (event.getSlashCommandInteraction().getFirstOption().isEmpty() || + event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().isEmpty()) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); + return; + } + + // Gets the first argument after the first argument and then gets the it as a string + var secondOption = event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().get(); + String name = secondOption.getStringValue().get(); + + if (secondOption.getStringValue().isEmpty()) { Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } - String name = event.getSlashCommandInteraction().getSecondOptionStringValue().get(); if (name.equalsIgnoreCase("")) { Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index 6695831..01ed743 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -79,9 +79,20 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { return; } - // If the user passed a wrong number of arguments, send the help message and exit. - if (event.getSlashCommandInteraction().getSecondOptionStringValue().isEmpty()) { - info("Person " + ChatColor.GRAY + author.getName() + ChatColor.RESET + " used the command createRole wrong. Sending help embed."); + // Checks if the first argument after the first argument exists. + if (event.getSlashCommandInteraction().getFirstOption().isEmpty() || + event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().isEmpty()) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"create role\"!"); + event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); + return; + } + + // Gets the first argument after the first argument and then gets the it as a string + var secondOption = event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().get(); + String name = secondOption.getStringValue().get(); + + if (secondOption.getStringValue().isEmpty()) { + Logging.info("User \"" + author.getName() + "\" tried to execute command \"create role\"!"); event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } @@ -92,7 +103,7 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { // Try creating the new Role try { if (event.getSlashCommandInteraction().getChannel().isPresent() && event.getSlashCommandInteraction().getChannel().get().asServerTextChannel().isPresent()) { - Role role = RoleAdmin.createNewRole(event.getSlashCommandInteraction().getServer().get(), event.getSlashCommandInteraction().getSecondOptionStringValue().get(), successEmbed, event.getSlashCommandInteraction().createImmediateResponder()); + Role role = RoleAdmin.createNewRole(event.getSlashCommandInteraction().getServer().get(), name, successEmbed, event.getSlashCommandInteraction().createImmediateResponder()); author.addRole(role, "MCDC role creation: Person who created the role should get the role assigned, as well."); info("Added role \"" + role.getName() + "\" to player \"" + author.getName() + "\"."); } else { diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index 3d4cea7..e63b962 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -111,7 +111,6 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { ServerTextChannel serverTextChannel = ChannelAdmin.createChannel(name, event.getSlashCommandInteraction().getServer().get(), "Minecraft Cross platform communication.", successEmbed, event.getSlashCommandInteraction().createImmediateResponder(), welcomeEmbed); Logging.info("Added channel \"" + serverTextChannel.getName() + "\" and role \"" + role.getName() + "\" to server \"" + event.getSlashCommandInteraction().getServer().get() + "\"!"); - Logging.info(ChatColor.RED + "Creating a text channel with setup is currently not supported. Please try again later."); // If this exception is thrown, the bot either does not have the correct permissions to create channels and Roles, // send the user an embed explaining the issue. From f02baac81159f737e0284322d7e24385572e8ee9 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 22 Jul 2021 21:53:52 +0200 Subject: [PATCH 080/158] =?UTF-8?q?=F0=9F=8F=8E=20Optimised=20slash=20comm?= =?UTF-8?q?and=20creation=20Put=20the=20registration=20of=20a=20slash=20co?= =?UTF-8?q?mmand=20into=20one=20request?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/discord/DiscordMain.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 7f45e86..66f88a6 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -177,10 +177,9 @@ private void registerSlashCommands() { ); // Do the actual registering of the slash commands. - slashCommands.forEach(slashCommandBuilder -> - slashCommandBuilder.createGlobal(discordApi).thenAccept(slashCommand -> - Logging.info("Added global slash command \"" + slashCommand.getName() + "\"") - )); + discordApi.bulkOverwriteGlobalSlashCommands(slashCommands).thenAccept(createdSlashCommands -> + createdSlashCommands.forEach(slashCommand -> Logging.info("Added global slash command \"" + slashCommand.getName() + "\"")) + ); } /** From 820c97205e7e9943fd46c358a106504aa438c787 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 22 Jul 2021 22:21:03 +0200 Subject: [PATCH 081/158] =?UTF-8?q?=E2=9E=95=20Added=20Saving=20of=20newly?= =?UTF-8?q?=20created=20roles?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defaultConfiguration.yml | 4 ++++ src/main/java/com/github/mafelp/discord/RoleAdmin.java | 9 +++++++++ src/main/java/com/github/mafelp/utils/Settings.java | 8 +++++++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 8e90d45..47e5ce1 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -33,6 +33,10 @@ deleteDiscordCommandMessages: false channelIDs: - 1234 +# Discord Role IDs that hav permission to use slash commands +roleIDs: + - 1234 + # Enables accounts and linking. # Allowed values enableLinking: true diff --git a/src/main/java/com/github/mafelp/discord/RoleAdmin.java b/src/main/java/com/github/mafelp/discord/RoleAdmin.java index 4279b53..e2b530d 100644 --- a/src/main/java/com/github/mafelp/discord/RoleAdmin.java +++ b/src/main/java/com/github/mafelp/discord/RoleAdmin.java @@ -1,5 +1,6 @@ package com.github.mafelp.discord; +import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.permission.*; @@ -85,6 +86,14 @@ public static Role createNewRole(Server server, String name, discordApi.getYourself().addRole(role, "MCDC needs to see the channel as well!"); info("Added role \"" + role.getName() + "\" to the discord API."); + var roleIDs = Settings.getConfiguration().getLongList("roleIDs"); + if (roleIDs.get(0) == 1234L) { + roleIDs.set(0, role.getId()); + } else { + roleIDs.add(role.getId()); + } + Settings.getConfiguration().set("roleIDs", roleIDs); + return role; } } diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 6f1e055..af20f61 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -8,6 +8,7 @@ import java.io.*; import java.util.ArrayList; +import java.util.List; import java.util.UUID; import static com.github.mafelp.utils.Logging.info; @@ -250,7 +251,12 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("debug", false); defaultConfiguration.set("discordCommandPrefix", "."); defaultConfiguration.set("deleteDiscordCommandMessages", false); - defaultConfiguration.set("channelIDs", new ArrayList().add(1234L)); + List channelIDs = new ArrayList<>(); + channelIDs.add(1234L); + defaultConfiguration.set("channelIDs", channelIDs); + List roleIDs = new ArrayList<>(); + roleIDs.add(1234L); + defaultConfiguration.set("roleIDs", roleIDs); defaultConfiguration.set("enableLinking", true); defaultConfiguration.set("allowListAllAccounts", true); defaultConfiguration.set("showFooterInMessages", true); From cd8de07cb5992e33f3326b459962057b8eb3060d Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 22 Jul 2021 23:38:21 +0200 Subject: [PATCH 082/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug=20in=20s?= =?UTF-8?q?lash=20command=20/setup=20Before=20the=20fix=20you=20were=20not?= =?UTF-8?q?=20required=20to=20give=20a=20name.=20Now=20you=20have=20to.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/discord/DiscordMain.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 66f88a6..5fadb12 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -170,7 +170,7 @@ private void registerSlashCommands() { // Setup command slashCommands.add(SlashCommand.with("setup","Creates and channel and a role for syncing minecraft and discord messages", Collections.singletonList( - SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name of the role and the channel") + SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name of the role and the channel", true) )) // TODO make command only executable with certain permissions //.setDefaultPermission(false) From 412acedb18c7f1e3f099193fdabd7f6d5d0c6962 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 22 Jul 2021 23:48:29 +0200 Subject: [PATCH 083/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20a=20bug=20when?= =?UTF-8?q?=20creating=20roles=20Before=20the=20fix=20the=20bot=20would=20?= =?UTF-8?q?not=20save=20the=20role=20id=20to=20the=20configuration.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/discord/RoleAdmin.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/github/mafelp/discord/RoleAdmin.java b/src/main/java/com/github/mafelp/discord/RoleAdmin.java index e2b530d..2447d69 100644 --- a/src/main/java/com/github/mafelp/discord/RoleAdmin.java +++ b/src/main/java/com/github/mafelp/discord/RoleAdmin.java @@ -93,6 +93,7 @@ public static Role createNewRole(Server server, String name, roleIDs.add(role.getId()); } Settings.getConfiguration().set("roleIDs", roleIDs); + Settings.saveConfiguration(); return role; } From 2747a92e00484ce237b82b2e50806d61dcc370b3 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Fri, 23 Jul 2021 00:58:25 +0200 Subject: [PATCH 084/158] =?UTF-8?q?=E2=9E=95=20Added=20slash=20command=20p?= =?UTF-8?q?ermissions=20=E2=9A=A0=EF=B8=8F=E2=9A=A0=EF=B8=8F=20Warning=20?= =?UTF-8?q?=E2=9A=A0=EF=B8=8F=E2=9A=A0=EF=B8=8F=20The=20global=20account?= =?UTF-8?q?=20slash=20commands=20are=20currently=20not=20workinga=20nd=20i?= =?UTF-8?q?'m=20working=20on=20a=20fix=20right=20now.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 105 ++++++++++++++---- 1 file changed, 84 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 5fadb12..d6f3acd 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -10,10 +10,8 @@ import org.javacord.api.entity.permission.PermissionType; import org.javacord.api.entity.permission.Permissions; import org.javacord.api.entity.permission.PermissionsBuilder; -import org.javacord.api.interaction.SlashCommand; -import org.javacord.api.interaction.SlashCommandBuilder; -import org.javacord.api.interaction.SlashCommandOption; -import org.javacord.api.interaction.SlashCommandOptionType; +import org.javacord.api.entity.server.Server; +import org.javacord.api.interaction.*; import java.io.*; import java.util.*; @@ -84,6 +82,7 @@ public void run() { try { // Create the API Settings.discordApi = new DiscordApiBuilder() + .setWaitForServersOnStartup(true) // set the token, specified in the config.yml or with command "/token " .setToken(Settings.getApiToken()) // register listeners @@ -125,34 +124,34 @@ public void run() { } private void registerSlashCommands() { - List slashCommands = new ArrayList<>(); + List accountSlashCommands = new ArrayList<>(); + List adminSlashCommands = new ArrayList<>(); // Link command - slashCommands.add(SlashCommand.with("link", "A command to link your discord and minecraft accounts", + accountSlashCommands.add(SlashCommand.with("link", "A command to link your discord and minecraft accounts", Collections.singletonList( SlashCommandOption.create(SlashCommandOptionType.INTEGER, "token", "The token used to link your accounts", false) ) )); // Unlink command - slashCommands.add(SlashCommand.with("unlink", "Unlink your discord account from your minecraft account")); + accountSlashCommands.add(SlashCommand.with("unlink", "Unlink your discord account from your minecraft account")); // Whisper and mcmsg commands - slashCommands.add(SlashCommand.with("whisper", "Whisper to your friends on the minecraft server!", + accountSlashCommands.add(SlashCommand.with("whisper", "Whisper to your friends on the minecraft server!", Arrays.asList( SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) )) ); - slashCommands.add(SlashCommand.with("mcmsg", "Whisper to your friends on the minecraft server!", + accountSlashCommands.add(SlashCommand.with("mcmsg", "Whisper to your friends on the minecraft server!", Arrays.asList( SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) - ) - )); + ))); // Create role and create channel commands - slashCommands.add(SlashCommand.with("create", "Create a channel/role for syncing minecraft and discord messages", + adminSlashCommands.add(SlashCommand.with("create", "Create a channel/role for syncing minecraft and discord messages", Arrays.asList( SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "channel", "Create a channel to sync minecraft messages to", Collections.singletonList( @@ -163,23 +162,87 @@ private void registerSlashCommands() { SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name the channel should have", true) )) )) - // TODO make command only executable with certain permissions - //.setDefaultPermission(false) + .setDefaultPermission(false) ); // Setup command - slashCommands.add(SlashCommand.with("setup","Creates and channel and a role for syncing minecraft and discord messages", + adminSlashCommands.add(SlashCommand.with("setup","Creates and channel and a role for syncing minecraft and discord messages", Collections.singletonList( SlashCommandOption.create(SlashCommandOptionType.STRING, "name", "The name of the role and the channel", true) )) - // TODO make command only executable with certain permissions - //.setDefaultPermission(false) + .setDefaultPermission(false) ); - // Do the actual registering of the slash commands. - discordApi.bulkOverwriteGlobalSlashCommands(slashCommands).thenAccept(createdSlashCommands -> - createdSlashCommands.forEach(slashCommand -> Logging.info("Added global slash command \"" + slashCommand.getName() + "\"")) - ); + // If linking is NOT enabled, set the default permission for all the slash commands to false. No one can use them then + if (!Settings.getConfiguration().getBoolean("enableLinking", true)) { + Logging.info("Linking is not enabled. Setting permission for all slash commands to false."); + accountSlashCommands.forEach(slashCommandBuilder -> slashCommandBuilder.setDefaultPermission(false)); + } + discordApi.bulkOverwriteGlobalSlashCommands(accountSlashCommands).thenAccept(slashCommands -> { + slashCommands.forEach(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); + /* + Logging.debug("Updating global account slash commands..."); + List updatedSlashCommands = new ArrayList<>(); + var roleIDs = Settings.getConfiguration().getLongList("roleIDs"); + Logging.debug("Role IDs are: " + roleIDs); + if (roleIDs.get(0) != 1234L) { + Logging.debug("Role IDs are not on default. Continuing..."); + for (Server server : discordApi.getServers()) { + List permissions = new ArrayList<>(); + StringBuilder sb = new StringBuilder("`-> No Permissions: "); + server.getRoles().forEach(role -> { + if (!roleIDs.contains(role.getId())) { + permissions.add(SlashCommandPermissions.create(role.getId(), SlashCommandPermissionType.ROLE, false)); + sb.append(role.getName()).append("; "); + } + }); + sb.append("\n`-> Affected Slash commands: "); + slashCommands.forEach(slashCommand -> { + updatedSlashCommands.add(new ServerSlashCommandPermissionsBuilder(slashCommand.getId(), permissions)); + sb.append(slashCommand.getName()).append("; "); + }); + updatedSlashCommands.forEach(serverSlashCommandPermissionsBuilder -> sb.append(serverSlashCommandPermissionsBuilder.getCommandId()).append("; ")); + Logging.debug("Updating slash commands for server " + server.getName() + "\n" + sb.toString()); + discordApi.batchUpdateSlashCommandPermissions(server, updatedSlashCommands).join(); + Logging.info("Updated slash command permissions for server " + server.getName()); + } + } */ + }); + for (Server server : discordApi.getServers()) { + discordApi.bulkOverwriteServerSlashCommands(server, adminSlashCommands).thenAccept(slashCommands -> { + // Setup a list with all allowed Users, configured in the config file and the bot owner + var allowedUserIDs = Settings.getConfiguration().getLongList("permission.discordServerAdmin.allowedUserIDs"); + allowedUserIDs = Settings.getConfiguration().getLongList("permission.discordBotAdmin.allowedUserIDs"); + allowedUserIDs.remove(1234L); + if (!allowedUserIDs.contains(discordApi.getOwnerId())) + allowedUserIDs.add(discordApi.getOwnerId()); + + // Register the slash commands for each server + List updatedSlashCommands = new ArrayList<>(); + List permissions = new ArrayList<>(); + Logging.debug("Updating admin slash command permission for server " + server.getName()); + // Check if the server owner of this server is in the allowed lists. + // If not, add them only for this server and remove them afterwards. + boolean serverOwnerIsAllowed = allowedUserIDs.contains(server.getOwnerId()); + if (!serverOwnerIsAllowed) + allowedUserIDs.add(server.getOwnerId()); + + // Create permission to use this slash command for each allowed user + allowedUserIDs.forEach(userID -> permissions.add(SlashCommandPermissions.create(userID, SlashCommandPermissionType.USER, true))); + // Prepare the commands to have the new permissions: Allow all allowed users to use this slash command. + slashCommands.forEach(slashCommand -> updatedSlashCommands.add(new ServerSlashCommandPermissionsBuilder(slashCommand.getId(), permissions))); + + // Do the actual updates + discordApi.batchUpdateSlashCommandPermissions(server, updatedSlashCommands).thenAccept(serverSlashCommandPermissions -> + Logging.info("Updated admin slash command permissions for server " + server.getName())); + + if (!serverOwnerIsAllowed) + allowedUserIDs.remove(server.getOwnerId()); + + permissions.clear(); + updatedSlashCommands.clear(); + }); + } } /** From e4532df11ef7685e2e33c8203c82855c6487bd2e Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 17:43:15 +0200 Subject: [PATCH 085/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20slash=20commands?= =?UTF-8?q?=20bug=20This=20will=20now=20allow=20the=20global=20slash=20com?= =?UTF-8?q?mands=20"/link",=20"/unlink",=20"/whisper"=20and=20"/mcmsg"=20t?= =?UTF-8?q?o=20be=20executed.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 40 ++++--------------- 1 file changed, 8 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index d6f3acd..7d44da5 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -132,7 +132,7 @@ private void registerSlashCommands() { Collections.singletonList( SlashCommandOption.create(SlashCommandOptionType.INTEGER, "token", "The token used to link your accounts", false) ) - )); + ).setDefaultPermission(true)); // Unlink command accountSlashCommands.add(SlashCommand.with("unlink", "Unlink your discord account from your minecraft account")); @@ -143,12 +143,13 @@ private void registerSlashCommands() { SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) )) + .setDefaultPermission(true) ); accountSlashCommands.add(SlashCommand.with("mcmsg", "Whisper to your friends on the minecraft server!", Arrays.asList( SlashCommandOption.create(SlashCommandOptionType.USER, "user", "The user to whisper your message to", true), SlashCommandOption.create(SlashCommandOptionType.STRING, "message", "What you want to whisper", true) - ))); + )).setDefaultPermission(true)); // Create role and create channel commands adminSlashCommands.add(SlashCommand.with("create", "Create a channel/role for syncing minecraft and discord messages", @@ -178,36 +179,11 @@ private void registerSlashCommands() { Logging.info("Linking is not enabled. Setting permission for all slash commands to false."); accountSlashCommands.forEach(slashCommandBuilder -> slashCommandBuilder.setDefaultPermission(false)); } - discordApi.bulkOverwriteGlobalSlashCommands(accountSlashCommands).thenAccept(slashCommands -> { - slashCommands.forEach(slashCommand -> Logging.info("Added global slash command " + slashCommand.getName())); - /* - Logging.debug("Updating global account slash commands..."); - List updatedSlashCommands = new ArrayList<>(); - var roleIDs = Settings.getConfiguration().getLongList("roleIDs"); - Logging.debug("Role IDs are: " + roleIDs); - if (roleIDs.get(0) != 1234L) { - Logging.debug("Role IDs are not on default. Continuing..."); - for (Server server : discordApi.getServers()) { - List permissions = new ArrayList<>(); - StringBuilder sb = new StringBuilder("`-> No Permissions: "); - server.getRoles().forEach(role -> { - if (!roleIDs.contains(role.getId())) { - permissions.add(SlashCommandPermissions.create(role.getId(), SlashCommandPermissionType.ROLE, false)); - sb.append(role.getName()).append("; "); - } - }); - sb.append("\n`-> Affected Slash commands: "); - slashCommands.forEach(slashCommand -> { - updatedSlashCommands.add(new ServerSlashCommandPermissionsBuilder(slashCommand.getId(), permissions)); - sb.append(slashCommand.getName()).append("; "); - }); - updatedSlashCommands.forEach(serverSlashCommandPermissionsBuilder -> sb.append(serverSlashCommandPermissionsBuilder.getCommandId()).append("; ")); - Logging.debug("Updating slash commands for server " + server.getName() + "\n" + sb.toString()); - discordApi.batchUpdateSlashCommandPermissions(server, updatedSlashCommands).join(); - Logging.info("Updated slash command permissions for server " + server.getName()); - } - } */ - }); + discordApi.bulkOverwriteGlobalSlashCommands(accountSlashCommands).thenAccept(slashCommands -> + slashCommands.forEach(slashCommand -> { + Logging.info("Added global slash command \"/" + slashCommand.getName() + "\""); + Logging.debug("Default-Permission for \"/" + slashCommand.getName() + "\": " + slashCommand.getDefaultPermission()); + })); for (Server server : discordApi.getServers()) { discordApi.bulkOverwriteServerSlashCommands(server, adminSlashCommands).thenAccept(slashCommands -> { // Setup a list with all allowed Users, configured in the config file and the bot owner From fa68dbc3744cbc8ee2806a3f5a67da704fc98441 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 17:48:49 +0200 Subject: [PATCH 086/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20L?= =?UTF-8?q?inkListener#sendLinkToken?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/discord/commands/LinkListener.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index 45718f6..eb663c6 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -81,6 +81,7 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { * This method sends the user a token, that it can use in {@link com.github.mafelp.minecraft.commands.Link} to * links its accounts together. * @param user The user to create the linking token from. + * @param event The event to respond to. */ private static void sendLinkToken(final User user, final SlashCommandCreateEvent event) { int minecraftLinkToken = DiscordLinker.getLinkToken(user); From ad1e1d7764e274869362b4b2c9a5a6e22346eb68 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 17:49:06 +0200 Subject: [PATCH 087/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20D?= =?UTF-8?q?iscordMain#registerSlashCommands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/discord/DiscordMain.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 7d44da5..036850b 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -123,6 +123,9 @@ public void run() { } } + /** + * Method to register all slash commands (in bulk). + */ private void registerSlashCommands() { List accountSlashCommands = new ArrayList<>(); List adminSlashCommands = new ArrayList<>(); From 6cef280bbee0ca862777615467c9c5b6d9b92d01 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 17:49:30 +0200 Subject: [PATCH 088/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20M?= =?UTF-8?q?ainSlashCommandListener#onSlashCommandCreate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/discord/commands/MainSlashCommandListener.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index bd81e1e..54cd27d 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -5,7 +5,15 @@ import org.javacord.api.event.interaction.SlashCommandCreateEvent; import org.javacord.api.listener.interaction.SlashCommandCreateListener; +/** + * The class to handle all slash command reactions. + */ public class MainSlashCommandListener implements SlashCommandCreateListener { + /** + * The method to handle the actual handling of the slash command events, by handing them over to their own files. + * @param slashCommandCreateEvent The event passed over by the discord api that contains the slash command + * interaction. + */ @Override public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent) { Logging.debug("Slash command interaction caught: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName()); From 8287ccc5cbc6f307ec56af44bfe4ee9beaef01d9 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 17:59:22 +0200 Subject: [PATCH 089/158] =?UTF-8?q?=E2=9E=95=20Added=20information=20messa?= =?UTF-8?q?ge=20about=20slash=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/discord/DiscordMain.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 036850b..38f320b 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -222,6 +222,10 @@ private void registerSlashCommands() { updatedSlashCommands.clear(); }); } + Logging.info(ChatColor.GREEN + "Registered slash Commands."); + Logging.info(ChatColor.YELLOW + "Information: Due to caching, it can take " + ChatColor.BOLD + "UP TO" + ChatColor.RESET + ChatColor.YELLOW + " an hour"); + Logging.info(ChatColor.YELLOW + "Information: until the slash commands can be used (until they appear or the message"); + Logging.info(ChatColor.YELLOW + "Information: \"InvalidInteractionID\" disappears when trying to use a slash command)"); } /** From 3031aa0fe676c697f75116d1b5f380505956e48c Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 17:59:42 +0200 Subject: [PATCH 090/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20build=20version?= =?UTF-8?q?=20to=200.10.0-beta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ebc44ff..9ff26fc 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.github.mafelp mcdc - 0.9.0-beta + 0.10.0-beta jar Mcdc From 2f970e7c3965fc7cd59aa0df3422acd73e832388 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 18:07:31 +0200 Subject: [PATCH 091/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20CHANGELOG.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 15 +++++++ .../com/github/mafelp/minecraft/Main.java | 1 + .../commands/WhisperTabCompleter.java | 45 +++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 619d1e9..f664a38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,19 @@ # Changelog +## Slash Commands Update +### v0.10.0 +➕ Added Slash Commands!
+↳ Now use discord commands by using a slash (/) instead of the old discordCommandPrefix Entry in the config file

+ +**⚠️ Information about slash commands⚠️**
+ - It can take **up to** an hour until the slash commands are registered + - This is a caching limitation put in place by discord. + - If you do not see any slash commands after this hour, please see your console log for a link! + - You **CAN NOT** use normal message commands like `.setup` anymore. Use `/setup` instead, if you are the discord server **owner** and/or the bot owner. +
+🚫 Removed the old discord commands, that could be used in messages. + +--- + ## BIG Account update ### v0.9.0 ➕ Added Accounts!
diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 2ba4824..4f21ea9 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -108,6 +108,7 @@ private void commandRegistration() { Objects.requireNonNull(getCommand("unlink")).setExecutor(new Unlink()); Logging.info("Command \"unlink\" has been enabled."); Objects.requireNonNull(getCommand("whisper")).setExecutor(new Whisper()); + Objects.requireNonNull(this.getCommand("whisper")).setTabCompleter(new WhisperTabCompleter()); Logging.info("Command \"whisper\" has been enabled."); } } diff --git a/src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java new file mode 100644 index 0000000..65eaf19 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java @@ -0,0 +1,45 @@ +package com.github.mafelp.minecraft.commands; + +import com.github.mafelp.accounts.Account; +import com.github.mafelp.utils.Settings; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.util.StringUtil; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class WhisperTabCompleter implements TabCompleter { + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { + final List results = new ArrayList<>(); + + if (args.length == 1) { + for (OfflinePlayer player : Settings.minecraftServer.getOfflinePlayers()) { + Account.getByPlayer(player).ifPresent(account -> { + results.add(account.getUsername()); + results.add(account.getPlayer().getName()); + }); + } + } else { + return new ArrayList<>(); + } + + // return results; + return sortedResults(args[0], results); + } + + // Sorts possible results to provide true tab auto complete based off of what is already typed. + public static List sortedResults(String arg, List results) { + final List completions = new ArrayList<>(); + StringUtil.copyPartialMatches(arg, results, completions); + Collections.sort(completions); + results.clear(); + results.addAll(completions); + return results; + } +} From 92a68702234d4dac977bfa9e8aa1f49274b1c0fb Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sat, 24 Jul 2021 18:10:56 +0200 Subject: [PATCH 092/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20README.md=20Th?= =?UTF-8?q?is=20represents=20latest=20changes=20in=20this=20project:=20Sla?= =?UTF-8?q?sh=20Commands=20are=20now=20available=20on=20discord.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 28fbb87..1a3827a 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,13 @@ The bot can currently do all the checked items, unchecked will be implemented in - [X] whisper between a discord user and a minecraft user - [X] linking between a discord and a minecraft account - [X] Toggle-able: Sending minecraft commands to the discord chats. -

+ - [X] Slash Commands: use slash commands in the discord chat. +

- [ ] A message in a channel that displays all online Members. - [ ] Tab completion in Minecraft - - [ ] Migrate to Slash Commands on discord, as soon as the API is ready. + - [ ] Migrate more slash commands to discord + - [ ] `/account` + - [ ] `/config` ## Installation 1. Download the latest [release](https://github.com/MaFeLP/MCDC/releases/) and put it into `/plugins`. From 7eea4f15dd037c4b7663a0688b6f424ec2f756ca Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 18:27:17 +0200 Subject: [PATCH 093/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Refactored=20Whisp?= =?UTF-8?q?erTabCompleter=20Moved=20it=20into=20TabCompleters=20Package?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/minecraft/Main.java | 7 +------ .../{commands => tabCompleters}/WhisperTabCompleter.java | 2 +- 2 files changed, 2 insertions(+), 7 deletions(-) rename src/main/java/com/github/mafelp/minecraft/{commands => tabCompleters}/WhisperTabCompleter.java (96%) diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 4f21ea9..8870be3 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -2,19 +2,14 @@ import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.minecraft.commands.*; -import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.minecraft.tabCompleters.WhisperTabCompleter; import com.github.mafelp.utils.Logging; -import com.github.mafelp.utils.Permissions; import com.github.mafelp.utils.Settings; import com.github.mafelp.discord.DiscordMain; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; -import static com.github.mafelp.utils.Logging.debug; -import static com.github.mafelp.utils.Settings.prefix; - -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Objects; diff --git a/src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java similarity index 96% rename from src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java rename to src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java index 65eaf19..2bbd421 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/WhisperTabCompleter.java +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java @@ -1,4 +1,4 @@ -package com.github.mafelp.minecraft.commands; +package com.github.mafelp.minecraft.tabCompleters; import com.github.mafelp.accounts.Account; import com.github.mafelp.utils.Settings; From 9d659f95f006a2abe47e6b479c8dc57bdf26324a Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 18:38:12 +0200 Subject: [PATCH 094/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Refactored=20the?= =?UTF-8?q?=20result=20sorting=20method=20Moved=20it=20into=20its=20own=20?= =?UTF-8?q?class.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/tabCompleters/ResultSorter.java | 19 +++++++++++++++++++ .../tabCompleters/WhisperTabCompleter.java | 14 ++------------ 2 files changed, 21 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java new file mode 100644 index 0000000..5c7a16a --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java @@ -0,0 +1,19 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class ResultSorter { + // Sorts possible results to provide true tab auto complete based off of what is already typed. + public static List sortedResults(String arg, List results) { + final List completions = new ArrayList<>(); + StringUtil.copyPartialMatches(arg, results, completions); + Collections.sort(completions); + results.clear(); + results.addAll(completions); + return results; + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java index 2bbd421..0c328a0 100644 --- a/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java @@ -6,13 +6,13 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; -import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import static com.github.mafelp.minecraft.tabCompleters.ResultSorter.sortedResults; + public class WhisperTabCompleter implements TabCompleter { @Override public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { @@ -32,14 +32,4 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman // return results; return sortedResults(args[0], results); } - - // Sorts possible results to provide true tab auto complete based off of what is already typed. - public static List sortedResults(String arg, List results) { - final List completions = new ArrayList<>(); - StringUtil.copyPartialMatches(arg, results, completions); - Collections.sort(completions); - results.clear(); - results.addAll(completions); - return results; - } } From 0752c875fef55dd484cef8a1b375164a1b2e747b Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 18:40:43 +0200 Subject: [PATCH 095/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20t?= =?UTF-8?q?he=20ResultSorter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/minecraft/tabCompleters/ResultSorter.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java index 5c7a16a..2e7ccfe 100644 --- a/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/ResultSorter.java @@ -6,7 +6,17 @@ import java.util.Collections; import java.util.List; +/** + * A class that sorts tab completion results. + */ public class ResultSorter { + /** + * A method that sorts the results provided in the second argument alphabetically and after what has already been + * typed (first argument). + * @param arg The string that has already been typed. + * @param results The results to be sorted. + * @return The sorted results. + */ // Sorts possible results to provide true tab auto complete based off of what is already typed. public static List sortedResults(String arg, List results) { final List completions = new ArrayList<>(); From beb51fcb54c6414d1757054472b3c5bc0e3b5ad1 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 18:48:44 +0200 Subject: [PATCH 096/158] =?UTF-8?q?=F0=9F=93=97=20Added=20Javadoc=20to=20t?= =?UTF-8?q?he=20WhisperTabCompleter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../minecraft/tabCompleters/WhisperTabCompleter.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java index 0c328a0..7049f08 100644 --- a/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/WhisperTabCompleter.java @@ -13,7 +13,18 @@ import static com.github.mafelp.minecraft.tabCompleters.ResultSorter.sortedResults; +/** + * The method that handles all the tab completion for the /whisper and /dcmsg commands. + */ public class WhisperTabCompleter implements TabCompleter { + /** + * The Method that handles the getting of of the results. + * @param sender The sender that is typing the command. + * @param cmd The command that the sender is trying to type. + * @param alias The first argument of the command, which also can be an alias. + * @param args The arguments that are provided until now. + * @return A list of available results for this command. + */ @Override public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { final List results = new ArrayList<>(); From cf5d86fb787a63cc7f34e7698e17ed61eaf89488 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 20:58:23 +0200 Subject: [PATCH 097/158] =?UTF-8?q?=E2=9E=95=20Added=20getAllMinecraftAcco?= =?UTF-8?q?untNames=20This=20method=20gets=20all=20minecraft=20names=20of?= =?UTF-8?q?=20players=20that=20have=20an=20account=20and=20their=20account?= =?UTF-8?q?=20username.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/accounts/AccountManager.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/java/com/github/mafelp/accounts/AccountManager.java b/src/main/java/com/github/mafelp/accounts/AccountManager.java index 53aeee4..2a7e659 100644 --- a/src/main/java/com/github/mafelp/accounts/AccountManager.java +++ b/src/main/java/com/github/mafelp/accounts/AccountManager.java @@ -4,6 +4,7 @@ import com.github.mafelp.utils.Settings; import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import org.bukkit.OfflinePlayer; import java.io.*; import java.util.*; @@ -121,4 +122,17 @@ public static List removeAccount(Account account) { linkedAccounts.removeAll(Collections.singleton(account)); return linkedAccounts; } + + /** + * Gets all names of minecraft Players who have an account and all the usernames. + * @return The list of names and usernames. + */ + public static List getAllMinecraftAccountNames() { + List out = new ArrayList<>(); + + for (OfflinePlayer player : Settings.minecraftServer.getOfflinePlayers()) + Account.getByPlayer(player).ifPresent(account -> out.addAll(Arrays.asList(account.getUsername(), account.getPlayer().getName()))); + + return out; + } } From fc949c9b03ce6f87452313551fc3f1f84da49e96 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 21:17:56 +0200 Subject: [PATCH 098/158] =?UTF-8?q?=E2=9E=95=20Added=20AccountTabCompleter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 2 + .../tabCompleters/AccountTabCompleter.java | 94 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/AccountTabCompleter.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 8870be3..8b915cc 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -2,6 +2,7 @@ import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.minecraft.commands.*; +import com.github.mafelp.minecraft.tabCompleters.AccountTabCompleter; import com.github.mafelp.minecraft.tabCompleters.WhisperTabCompleter; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; @@ -99,6 +100,7 @@ private void commandRegistration() { Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); Logging.info("Command \"link\" has been enabled."); Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); + Objects.requireNonNull(this.getCommand("account")).setTabCompleter(new AccountTabCompleter()); Logging.info("Command \"account\" has been enabled."); Objects.requireNonNull(getCommand("unlink")).setExecutor(new Unlink()); Logging.info("Command \"unlink\" has been enabled."); diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/AccountTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/AccountTabCompleter.java new file mode 100644 index 0000000..db3a80f --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/AccountTabCompleter.java @@ -0,0 +1,94 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Permissions; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static com.github.mafelp.minecraft.tabCompleters.ResultSorter.sortedResults; + +/** + * The method that handles all the tab completion for the /account commands + */ +public class AccountTabCompleter implements TabCompleter { + /** + * The Method that handles the getting of of the results. + * @param sender The sender that is typing the command. + * @param cmd The command that the sender is trying to type. + * @param alias The first argument of the command, which also can be an alias. + * @param args The arguments that are provided until now. + * @return A list of available results for this command. + */ + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { + List results; + + switch (args.length) { + case 1 -> { + results = new ArrayList<>(Arrays.asList( + "get", + "list" + )); + + if (sender instanceof Player) { + results.addAll(Arrays.asList( + "link", + "unlink", + "name", "username" + )); + + if (CheckPermission.checkPermission(Permissions.accountEdit, (Player) sender)) { + results.addAll(Arrays.asList( + "remove", + "save", + "reload" + )); + } + } else { + results.addAll(Arrays.asList( + "remove", + "save", + "reload" + )); + } + + // return results; + return sortedResults(args[0], results); + } + case 2 -> { + switch (args[0]) { + case "remove" -> { + if (CheckPermission.checkPermission(Permissions.accountEdit, (Player) sender)) + return sortedResults(args[1], AccountManager.getAllMinecraftAccountNames()); + else + return new ArrayList<>(); + } + case "get" -> { + return sortedResults(args[1], AccountManager.getAllMinecraftAccountNames()); + } + case "link" -> { + return Collections.singletonList("()"); + } + case "name", "username" -> { + return Collections.singletonList(""); + } + default -> { + return new ArrayList<>(); + } + } + } + default -> { + return new ArrayList<>(); + } + } + } +} From e755490da931b3763667d3881c9d0331c64bdfb0 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 21:45:36 +0200 Subject: [PATCH 099/158] =?UTF-8?q?=E2=9E=95=20Added=20ConfigTabCompleter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 2 + .../tabCompleters/ConfigTabCompleter.java | 74 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/ConfigTabCompleter.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 8b915cc..e0ad43b 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -3,6 +3,7 @@ import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.minecraft.commands.*; import com.github.mafelp.minecraft.tabCompleters.AccountTabCompleter; +import com.github.mafelp.minecraft.tabCompleters.ConfigTabCompleter; import com.github.mafelp.minecraft.tabCompleters.WhisperTabCompleter; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; @@ -95,6 +96,7 @@ private void commandRegistration() { Objects.requireNonNull(getCommand("token")).setExecutor(new Token()); Logging.info("Command \"token\" has been enabled."); Objects.requireNonNull(getCommand("config")).setExecutor(new Config()); + Objects.requireNonNull(getCommand("config")).setTabCompleter(new ConfigTabCompleter()); Logging.info("Command \"config\" has been enabled."); if (Settings.getConfiguration().getBoolean("enableLinking")) { Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/ConfigTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/ConfigTabCompleter.java new file mode 100644 index 0000000..3459dbf --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/ConfigTabCompleter.java @@ -0,0 +1,74 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Permissions; +import com.github.mafelp.utils.Settings; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +import static com.github.mafelp.minecraft.tabCompleters.ResultSorter.sortedResults; + +/** + * The method that handles all the tab completion for the /config command. + */ +public class ConfigTabCompleter implements TabCompleter { + /** + * The Method that handles the getting of of the results. + * @param sender The sender that is typing the command. + * @param cmd The command that the sender is trying to type. + * @param alias The first argument of the command, which also can be an alias. + * @param args The arguments that are provided until now. + * @return A list of available results for this command. + */ + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { + if (sender instanceof Player) + if (!CheckPermission.checkPermission(Permissions.configEdit, (Player) sender)) + return new ArrayList<>(); + + switch (args.length) { + case 1 -> { + return Arrays.asList( + "reload", + "save", + "default", + "set", + "get", + "add", + "remove" + ); + } + case 2 -> { + switch (args[0].toLowerCase(Locale.ROOT)) { + case "set", "get", "add", "remove" -> { + return sortedResults(args[1], new ArrayList<>(Settings.getConfiguration().getKeys(true))); + } + default -> { + return new ArrayList<>(); + } + } + } + case 3 -> { + switch (args[0].toLowerCase(Locale.ROOT)) { + case "set", "add" -> { + return Collections.singletonList(""); + } + case "remove" -> { + return sortedResults(args[2], Settings.getConfiguration().getStringList(args[2])); + } + default -> { + return new ArrayList<>(); + } + } + } + default -> { + return new ArrayList<>(); + } + } + } +} From cf78ed8c7b98d292ed6a29385988c094d360a455 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 21:48:11 +0200 Subject: [PATCH 100/158] =?UTF-8?q?=E2=9E=95=20Added=20LinkTabCompleter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 2 ++ .../tabCompleters/LinkTabCompleter.java | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/LinkTabCompleter.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index e0ad43b..d502b2a 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -4,6 +4,7 @@ import com.github.mafelp.minecraft.commands.*; import com.github.mafelp.minecraft.tabCompleters.AccountTabCompleter; import com.github.mafelp.minecraft.tabCompleters.ConfigTabCompleter; +import com.github.mafelp.minecraft.tabCompleters.LinkTabCompleter; import com.github.mafelp.minecraft.tabCompleters.WhisperTabCompleter; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; @@ -100,6 +101,7 @@ private void commandRegistration() { Logging.info("Command \"config\" has been enabled."); if (Settings.getConfiguration().getBoolean("enableLinking")) { Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); + Objects.requireNonNull(getCommand("link")).setTabCompleter(new LinkTabCompleter()); Logging.info("Command \"link\" has been enabled."); Objects.requireNonNull(getCommand("account")).setExecutor(new AccountCommand()); Objects.requireNonNull(this.getCommand("account")).setTabCompleter(new AccountTabCompleter()); diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/LinkTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/LinkTabCompleter.java new file mode 100644 index 0000000..bab5415 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/LinkTabCompleter.java @@ -0,0 +1,31 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +/** + * The method that handles all the tab completion for the /whisper and /dcmsg commands. + */ +public class LinkTabCompleter implements TabCompleter { + /** + * The Method that handles the getting of of the results. + * @param sender The sender that is typing the command. + * @param cmd The command that the sender is trying to type. + * @param alias The first argument of the command, which also can be an alias. + * @param args The arguments that are provided until now. + * @return A list of available results for this command. + */ + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { + if (args.length == 1) { + return Collections.singletonList("()"); + } else { + return Collections.emptyList(); + } + } +} From 140e6755a1ed9435e5a4efc7c6d6bf8aa1bfdb77 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 21:50:33 +0200 Subject: [PATCH 101/158] =?UTF-8?q?=E2=9E=95=20Added=20TokenTabCompleter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 6 ++-- .../tabCompleters/TokenTabCompleter.java | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/TokenTabCompleter.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index d502b2a..b1d7cff 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -2,10 +2,7 @@ import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.minecraft.commands.*; -import com.github.mafelp.minecraft.tabCompleters.AccountTabCompleter; -import com.github.mafelp.minecraft.tabCompleters.ConfigTabCompleter; -import com.github.mafelp.minecraft.tabCompleters.LinkTabCompleter; -import com.github.mafelp.minecraft.tabCompleters.WhisperTabCompleter; +import com.github.mafelp.minecraft.tabCompleters.*; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; import com.github.mafelp.discord.DiscordMain; @@ -95,6 +92,7 @@ private void commandRegistration() { // All commands // for more information read the Javadoc in the specific classes Objects.requireNonNull(getCommand("token")).setExecutor(new Token()); + Objects.requireNonNull(getCommand("token")).setTabCompleter(new TokenTabCompleter()); Logging.info("Command \"token\" has been enabled."); Objects.requireNonNull(getCommand("config")).setExecutor(new Config()); Objects.requireNonNull(getCommand("config")).setTabCompleter(new ConfigTabCompleter()); diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/TokenTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/TokenTabCompleter.java new file mode 100644 index 0000000..ee59d64 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/TokenTabCompleter.java @@ -0,0 +1,31 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +/** + * The method that handles all the tab completion for the /whisper and /dcmsg commands. + */ +public class TokenTabCompleter implements TabCompleter { + /** + * The Method that handles the getting of of the results. + * @param sender The sender that is typing the command. + * @param cmd The command that the sender is trying to type. + * @param alias The first argument of the command, which also can be an alias. + * @param args The arguments that are provided until now. + * @return A list of available results for this command. + */ + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { + if (args.length == 1) { + return Collections.singletonList(""); + } else { + return Collections.emptyList(); + } + } +} From 4238d828e039675440913138b5bfbdc70bb55646 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 21:52:35 +0200 Subject: [PATCH 102/158] =?UTF-8?q?=E2=9E=95=20Added=20UnlinkTabCompleter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 1 + .../mafelp/minecraft/commands/Unlink.java | 4 +-- .../tabCompleters/UnlinkTabCompleter.java | 27 +++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/UnlinkTabCompleter.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index b1d7cff..d02fb3e 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -105,6 +105,7 @@ private void commandRegistration() { Objects.requireNonNull(this.getCommand("account")).setTabCompleter(new AccountTabCompleter()); Logging.info("Command \"account\" has been enabled."); Objects.requireNonNull(getCommand("unlink")).setExecutor(new Unlink()); + Objects.requireNonNull(getCommand("unlink")).setTabCompleter(new UnlinkTabCompleter()); Logging.info("Command \"unlink\" has been enabled."); Objects.requireNonNull(getCommand("whisper")).setExecutor(new Whisper()); Objects.requireNonNull(this.getCommand("whisper")).setTabCompleter(new WhisperTabCompleter()); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java b/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java index b8fd7da..3bdf28c 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Unlink.java @@ -31,9 +31,7 @@ public class Unlink implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, String[] args) { // Only players can have accounts. - if (commandSender instanceof Player) { - Player player = (Player) commandSender; - + if (commandSender instanceof Player player) { Optional accountOptional = Account.getByPlayer(player); if (accountOptional.isEmpty()) { diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/UnlinkTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/UnlinkTabCompleter.java new file mode 100644 index 0000000..ecae376 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/UnlinkTabCompleter.java @@ -0,0 +1,27 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; + +import java.util.Collections; +import java.util.List; + +/** + * The method that handles all the tab completion for the /whisper and /dcmsg commands. + */ +public class UnlinkTabCompleter implements TabCompleter { + /** + * The Method that handles the getting of of the results. + * @param sender The sender that is typing the command. + * @param cmd The command that the sender is trying to type. + * @param alias The first argument of the command, which also can be an alias. + * @param args The arguments that are provided until now. + * @return A list of available results for this command. + */ + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String alias, @NotNull String[] args) { + return Collections.emptyList(); + } +} From ffc5207ac968f90eb6f36206ea7eeae850d64299 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 21:58:39 +0200 Subject: [PATCH 103/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20build=20version?= =?UTF-8?q?=20to=200.11.0-beta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- src/main/java/com/github/mafelp/utils/Settings.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9ff26fc..e9d5178 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.github.mafelp mcdc - 0.10.0-beta + 0.11.0-beta jar Mcdc diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index af20f61..1debd4f 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -37,7 +37,7 @@ public class Settings { /** * version number of the plugin - displayed to users */ - public static final String version = "v0.9.0-beta"; + public static final String version = "v0.11.0-beta"; /** * enables more information being displayed while executing events From 4fb8deb169d7a2b90bf73f9187ed6a865d1c4da6 Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 22:01:13 +0200 Subject: [PATCH 104/158] =?UTF-8?q?=E2=9E=95=20Added=20changes=20since=20l?= =?UTF-8?q?ast=20release.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f664a38..e4b93bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,10 @@ # Changelog +## Tab Completions +### v0.11.0-beta +➕ Added Tab Completion to all Minecraft commands + +--- + ## Slash Commands Update ### v0.10.0 ➕ Added Slash Commands!
From 812ae86a901895bde8b1191c4c65a8bfe208595d Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 22:01:36 +0200 Subject: [PATCH 105/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20README.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1a3827a..07ea4f5 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ The bot can currently do all the checked items, unchecked will be implemented in - [X] linking between a discord and a minecraft account - [X] Toggle-able: Sending minecraft commands to the discord chats. - [X] Slash Commands: use slash commands in the discord chat. + - [X] Tab completion in Minecraft

- [ ] A message in a channel that displays all online Members. - - [ ] Tab completion in Minecraft - [ ] Migrate more slash commands to discord - [ ] `/account` - [ ] `/config` From a14d0e0c166a60dd30acc39ff305502f7efb361b Mon Sep 17 00:00:00 2001 From: GitHub <60669873+MaFeLP@users.noreply.github.com> Date: Sun, 25 Jul 2021 22:12:57 +0200 Subject: [PATCH 106/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20README.md=20?= =?UTF-8?q?=E2=9E=95=20Added=20a=20new=20TODO=20to=20the=20list?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 07ea4f5..52dfef8 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ The bot can currently do all the checked items, unchecked will be implemented in - [ ] Migrate more slash commands to discord - [ ] `/account` - [ ] `/config` + - [ ] Add a new command: `/help` ## Installation 1. Download the latest [release](https://github.com/MaFeLP/MCDC/releases/) and put it into `/plugins`. From 9aab9d200fde73d085efc3aeffffaf76cc53b2f1 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 4 Aug 2021 22:09:21 +0200 Subject: [PATCH 107/158] Syncronisation pull (#35) From 8a522916fc7f39604559f63adaf264df3a439182 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 17:45:17 +0200 Subject: [PATCH 108/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20dependency=20or?= =?UTF-8?q?g.jetbrains.annotations=20to=2021.0.1=2020.1.0=20->=2021.0.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e9d5178..f67b3ec 100644 --- a/pom.xml +++ b/pom.xml @@ -94,7 +94,7 @@ org.jetbrains annotations - 20.1.0 + 21.0.1 compile From 74542856e45bc13ff9d16b55f7b60fe660eefc7f Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 18:29:04 +0200 Subject: [PATCH 109/158] =?UTF-8?q?=E2=9E=95=20Added=20minecraft=20help=20?= =?UTF-8?q?command=20Displays=20help=20text=20when=20executed=20with=20no?= =?UTF-8?q?=20arguments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 3 + .../mafelp/minecraft/commands/Help.java | 85 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 src/main/java/com/github/mafelp/minecraft/commands/Help.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index d02fb3e..a36dfb1 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -97,6 +97,9 @@ private void commandRegistration() { Objects.requireNonNull(getCommand("config")).setExecutor(new Config()); Objects.requireNonNull(getCommand("config")).setTabCompleter(new ConfigTabCompleter()); Logging.info("Command \"config\" has been enabled."); + Objects.requireNonNull(getCommand("help")).setExecutor(new Help()); + //Objects.requireNonNull(getCommand("help")).setTabCompleter(new HelpTabCompleter()); + Logging.info("Command \"/help\" has been enabled."); if (Settings.getConfiguration().getBoolean("enableLinking")) { Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); Objects.requireNonNull(getCommand("link")).setTabCompleter(new LinkTabCompleter()); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java new file mode 100644 index 0000000..ce2a12e --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -0,0 +1,85 @@ +package com.github.mafelp.minecraft.commands; + +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Permissions; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import static com.github.mafelp.utils.Logging.info; + +public class Help implements CommandExecutor { + @Override + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length == 0) { + sendNormalHelpMessage(sender); + info("\"" + sender.getName() + "\" executed command \"/help\"; Result: Normal help message."); + return true; + } + + info(sender.getName() + "Executed command \"/help\""); + + return false; + } + + private static void sendNormalHelpMessage(CommandSender sender) { + // Message for admin users: + /* + * +--------------------------[MCDC/HELP]--------------------------+ + * General command help. Use "/mcdc:help " + * for more information on a specific command. + * + * Commands: + * |-> /account -> Manage accounts/get account info + * |-> /config -> Configure this plugin + * |-> /link -> Link your minecraft to discord + * |-> /mcdc:help -> Lists this help + * |-> /dcmsg -> Sends a private message to a discord user + * |-> /token -> Sets the token for the discord bot + * |-> /unlink -> Unlinks your minecraft and discord accounts + * `-> /whisper -> Sends a private message to a discord user + * +--------------------------[MCDC/HELP]--------------------------+ + */ + + // Message for normal users: + /* + * +--------------------------[MCDC/HELP]--------------------------+ + * General command help. Use "/mcdc:help " + * for more information on a specific command. + * + * Commands: + * |-> /account -> Manage accounts/get account info + * |-> /link -> Link your minecraft to discord + * |-> /mcdc:help -> Lists this help + * |-> /dcmsg -> Sends a private message to a discord user + * |-> /unlink -> Unlinks your minecraft and discord accounts + * `-> /whisper -> Sends a private message to a discord user + * +--------------------------[MCDC/HELP]--------------------------+ + */ + + String out = ChatColor.GREEN + "+--------------------------" + ChatColor.BLACK + "[" + ChatColor.GOLD + "MCDC" + ChatColor.BLACK + "/" + ChatColor.YELLOW + "HELP" + ChatColor.BLACK + "]" + ChatColor.GREEN + "--------------------------+\n" + + ChatColor.AQUA + "General command help. Use \"" + ChatColor.GRAY + "/mcdc:help " + ChatColor.AQUA + "\"\n" + + " for more information on a specific command.\n" + + ChatColor.GREEN + ChatColor.UNDERLINE + "Commands" + ChatColor.RESET + ChatColor.BLACK + ":\n" + + ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/account" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Manage accounts/get account info\n"; + + if (!(sender instanceof Player) || CheckPermission.checkPermission(Permissions.configEdit, sender)) + out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/config" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Configure this plugin\n"; + + if (sender instanceof Player) + out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/link" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Link your minecraft to discord\n"; + + out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/mcdc:help" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Shows this page\n"; + out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/dcmsg" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; + + if (sender instanceof Player) + out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/unlink" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Unlinks your minecraft and discord accounts\n"; + + out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/whisper" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; + out += ChatColor.GREEN + "+--------------------------" + ChatColor.BLACK + "[" + ChatColor.GOLD + "MCDC" + ChatColor.BLACK + "/" + ChatColor.YELLOW + "HELP" + ChatColor.BLACK + "]" + ChatColor.GREEN + "--------------------------+"; + + sender.sendMessage(out); + } +} From a776279edc58e7ca2490b90d45172eea8b715f0b Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 18:33:30 +0200 Subject: [PATCH 110/158] =?UTF-8?q?=E2=9C=85=20Enabled=20command=20/help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/plugin.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index e67c8c3..e042575 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -8,6 +8,9 @@ description: A Spigot plugin for cross communicatin with a discord server website: https://github.com/MaFeLP/MCDC commands: + help: + description: Displays a help text about all commands. + usage: /mcdc:help (COMMAND) link: description: Links your discord account to your minecraft account. token: @@ -28,4 +31,4 @@ commands: description: The command to whisper to a discord user. usage: /whisper @AccountTag "" aliases: - - dcmsg \ No newline at end of file + - dcmsg From dd10e4e205deba2840395e8452e90824622345c4 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 18:57:27 +0200 Subject: [PATCH 111/158] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Visual=20bug=20?= =?UTF-8?q?fixes=20in=20help=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 2 +- .../mafelp/minecraft/commands/Help.java | 25 ++++++++++--------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index a36dfb1..8ece433 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -99,7 +99,7 @@ private void commandRegistration() { Logging.info("Command \"config\" has been enabled."); Objects.requireNonNull(getCommand("help")).setExecutor(new Help()); //Objects.requireNonNull(getCommand("help")).setTabCompleter(new HelpTabCompleter()); - Logging.info("Command \"/help\" has been enabled."); + Logging.info("Command \"help\" has been enabled."); if (Settings.getConfiguration().getBoolean("enableLinking")) { Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); Objects.requireNonNull(getCommand("link")).setTabCompleter(new LinkTabCompleter()); diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index ce2a12e..dd8f189 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -59,26 +59,27 @@ private static void sendNormalHelpMessage(CommandSender sender) { * +--------------------------[MCDC/HELP]--------------------------+ */ - String out = ChatColor.GREEN + "+--------------------------" + ChatColor.BLACK + "[" + ChatColor.GOLD + "MCDC" + ChatColor.BLACK + "/" + ChatColor.YELLOW + "HELP" + ChatColor.BLACK + "]" + ChatColor.GREEN + "--------------------------+\n" - + ChatColor.AQUA + "General command help. Use \"" + ChatColor.GRAY + "/mcdc:help " + ChatColor.AQUA + "\"\n" - + " for more information on a specific command.\n" - + ChatColor.GREEN + ChatColor.UNDERLINE + "Commands" + ChatColor.RESET + ChatColor.BLACK + ":\n" - + ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/account" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Manage accounts/get account info\n"; + String out = ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+\n" + + ChatColor.RED + " If you are searching for the vanilla help, use \"" + ChatColor.GRAY + "/minecraft:help" + ChatColor.RED + "\"!\n\n" + + ChatColor.AQUA + " General command help. Use \"" + ChatColor.GRAY + "/mcdc:help " + ChatColor.AQUA + "\"\n" + + " for more information on a specific command.\n\n" + + ChatColor.GREEN + ChatColor.UNDERLINE + "Commands" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/account" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Manage accounts/get account info\n"; if (!(sender instanceof Player) || CheckPermission.checkPermission(Permissions.configEdit, sender)) - out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/config" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Configure this plugin\n"; + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/config" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Configure this plugin\n"; if (sender instanceof Player) - out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/link" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Link your minecraft to discord\n"; + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/link" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Link your minecraft to discord\n"; - out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/mcdc:help" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Shows this page\n"; - out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/dcmsg" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/mcdc:help" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Shows this page\n"; + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/dcmsg" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; if (sender instanceof Player) - out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/unlink" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Unlinks your minecraft and discord accounts\n"; + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/unlink" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Removes your account\n"; - out += ChatColor.GRAY + " |->" + ChatColor.DARK_AQUA + "/whisper" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; - out += ChatColor.GREEN + "+--------------------------" + ChatColor.BLACK + "[" + ChatColor.GOLD + "MCDC" + ChatColor.BLACK + "/" + ChatColor.YELLOW + "HELP" + ChatColor.BLACK + "]" + ChatColor.GREEN + "--------------------------+"; + out += ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "/whisper" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; + out += ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+"; sender.sendMessage(out); } From 018ab28434d6eb5b90dce58a776d97c3b1fac25d Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 19:25:44 +0200 Subject: [PATCH 112/158] =?UTF-8?q?=F0=9F=9F=A2=20Prepared=20for=20differe?= =?UTF-8?q?nt=20command=20help=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/minecraft/commands/Help.java | 44 +++++++++++++++---- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index dd8f189..faa750b 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -8,23 +8,51 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.Locale; + import static com.github.mafelp.utils.Logging.info; public class Help implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + String out = ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+\n"; + if (args.length == 0) { - sendNormalHelpMessage(sender); + out += sendNormalHelpMessage(sender); info("\"" + sender.getName() + "\" executed command \"/help\"; Result: Normal help message."); - return true; + } else { + switch (args[0].toLowerCase(Locale.ROOT)) { + case "account" -> { + } + case "config" -> { + } + case "help" -> { + } + case "link" -> { + } + case "token" -> { + } + case "unlink" -> { + } + case "whisper", "dcmsg" -> { + } + default -> { + out += ChatColor.RED + "Unknown command: \"" + ChatColor.GRAY + args[0] + ChatColor.RED + "\"! See below for a full list!\n"; + out += sendNormalHelpMessage(sender); + info("\"" + sender.getName() + "\" executed command \"/help\"; Result: Normal help message."); + } + } } - info(sender.getName() + "Executed command \"/help\""); + out += ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+"; + sender.sendMessage(out); - return false; + return true; } - private static void sendNormalHelpMessage(CommandSender sender) { + private static String sendNormalHelpMessage(CommandSender sender) { // Message for admin users: /* * +--------------------------[MCDC/HELP]--------------------------+ @@ -59,8 +87,7 @@ private static void sendNormalHelpMessage(CommandSender sender) { * +--------------------------[MCDC/HELP]--------------------------+ */ - String out = ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+\n" - + ChatColor.RED + " If you are searching for the vanilla help, use \"" + ChatColor.GRAY + "/minecraft:help" + ChatColor.RED + "\"!\n\n" + String out = ChatColor.RED + " If you are searching for the vanilla help, use \"" + ChatColor.GRAY + "/minecraft:help" + ChatColor.RED + "\"!\n\n" + ChatColor.AQUA + " General command help. Use \"" + ChatColor.GRAY + "/mcdc:help " + ChatColor.AQUA + "\"\n" + " for more information on a specific command.\n\n" + ChatColor.GREEN + ChatColor.UNDERLINE + "Commands" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n" @@ -79,8 +106,7 @@ private static void sendNormalHelpMessage(CommandSender sender) { out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "/unlink" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Removes your account\n"; out += ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "/whisper" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sends a private message to a discord user\n"; - out += ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+"; - sender.sendMessage(out); + return out; } } From 0a344acac4ff174ecbfc5cf93cb8a82d7667ed42 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 19:27:36 +0200 Subject: [PATCH 113/158] =?UTF-8?q?=E2=9E=A1=EF=B8=8F=20Refactored=20Help#?= =?UTF-8?q?sendNormalHelpMessage=20into=20Help#normalHelpMessage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/minecraft/commands/Help.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index faa750b..77d09b5 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -9,7 +9,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Arrays; import java.util.Locale; import static com.github.mafelp.utils.Logging.info; @@ -20,7 +19,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command String out = ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+\n"; if (args.length == 0) { - out += sendNormalHelpMessage(sender); + out += normalHelpMessage(sender); info("\"" + sender.getName() + "\" executed command \"/help\"; Result: Normal help message."); } else { switch (args[0].toLowerCase(Locale.ROOT)) { @@ -40,7 +39,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } default -> { out += ChatColor.RED + "Unknown command: \"" + ChatColor.GRAY + args[0] + ChatColor.RED + "\"! See below for a full list!\n"; - out += sendNormalHelpMessage(sender); + out += normalHelpMessage(sender); info("\"" + sender.getName() + "\" executed command \"/help\"; Result: Normal help message."); } } @@ -52,7 +51,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return true; } - private static String sendNormalHelpMessage(CommandSender sender) { + private static String normalHelpMessage(CommandSender sender) { // Message for admin users: /* * +--------------------------[MCDC/HELP]--------------------------+ From c4edb029c188eb650f8cfee4d66c75f05eab1073 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 19:55:02 +0200 Subject: [PATCH 114/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?help=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/minecraft/commands/Help.java | 57 +++++++++++++++++-- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index 77d09b5..4cef101 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -14,17 +14,18 @@ import static com.github.mafelp.utils.Logging.info; public class Help implements CommandExecutor { + private static final String spacerLine = ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+\n"; + @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - String out = ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+\n"; + String out = spacerLine + ""; if (args.length == 0) { out += normalHelpMessage(sender); info("\"" + sender.getName() + "\" executed command \"/help\"; Result: Normal help message."); } else { switch (args[0].toLowerCase(Locale.ROOT)) { - case "account" -> { - } + case "account" -> out += accountHelp(sender instanceof Player, CheckPermission.checkPermission(Permissions.accountEdit, sender)); case "config" -> { } case "help" -> { @@ -45,7 +46,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } } - out += ChatColor.GREEN + "+--------------------" + ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "MCDC" + ChatColor.DARK_GRAY + "/" + ChatColor.YELLOW + "HELP" + ChatColor.DARK_GRAY + "]" + ChatColor.GREEN + "--------------------+"; + out += spacerLine; sender.sendMessage(out); return true; @@ -108,4 +109,52 @@ private static String normalHelpMessage(CommandSender sender) { return out; } + + private static String commandHelpPageStarter(String description) { + return ChatColor.RED + " If you are searching for the vanilla help, use \"" + ChatColor.GRAY + "/minecraft:help" + ChatColor.RED + "\"!\n\n" + + ChatColor.AQUA + " Help for command \"" + ChatColor.GRAY + "/account" + ChatColor.AQUA + "\". Use \"" + ChatColor.GRAY + "/mcdc:help" + ChatColor.AQUA + "\"\n" + + " to see a list of all available commands.\n\n" + + ChatColor.GREEN + ChatColor.UNDERLINE + "Description" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n" + + ChatColor.RESET + description + "\n" + + ChatColor.RESET + " The subcommands are structured as followed:\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "subcommand 1" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + + ChatColor.GRAY + " | |-> " + ChatColor.DARK_AQUA + "subcommand argument 1" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "subcommand argument 2" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "subcommand 2" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "subcommand argument 1" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "subcommand argument 2" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + + spacerLine + + ChatColor.GREEN + ChatColor.UNDERLINE + "Subcommands" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n"; + } + + private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermission) { + String out = commandHelpPageStarter(" The account command provides lots of useful features for managing\n" + + " your local minecraft server/discord relationship.\n" + + ChatColor.RED + ChatColor.BOLD + " THIS ACCOUNT IS NOT OFFICIAL AND ONLY VALID ON THIS SERVER AND WITH THE MCDC BOT!") + ; + + if (isPlayer) + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "link" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Initiates the mc/dc linking process.\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "OPTIONAL - the linking token, given from discord\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "name" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Give yourself a new account tag\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "name" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "STRING - your new account name\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "username" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Give yourself a new account tag\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "name" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "STRING - your new account name\n" + ; + + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "get" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Gets the account tag for a user\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "user" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The user to get the tag from\n"; + + if (hasAccountEditPermission) + out += ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "remove" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Removes an account from a user\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "account tag" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The account tag of the user whose account shall be removed.\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "save" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Saves all currently linked accounts to the file.\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "reload" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Reloads all accounts from the file.\n" + ; + + if (isPlayer) + out += ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "unlink" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Deletes your account\n"; + + return out; + } } From 5bcd93c3c06e60717b222bcd66aa0b651c01cc18 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:25:26 +0200 Subject: [PATCH 115/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?config=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mafelp/minecraft/commands/Help.java | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index 4cef101..430f69c 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -2,11 +2,13 @@ import com.github.mafelp.utils.CheckPermission; import com.github.mafelp.utils.Permissions; +import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.Locale; @@ -27,6 +29,15 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command switch (args[0].toLowerCase(Locale.ROOT)) { case "account" -> out += accountHelp(sender instanceof Player, CheckPermission.checkPermission(Permissions.accountEdit, sender)); case "config" -> { + if (CheckPermission.checkPermission(Permissions.configEdit, sender)) + out += configHelp(); + else { + sender.sendMessage( + Settings.prefix + ChatColor.RED + "Sorry, you don't have the permission to edit the config,\n" + + Settings.prefix + "So the help would be of no use for you!" + ); + return true; + } } case "help" -> { } @@ -52,7 +63,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return true; } - private static String normalHelpMessage(CommandSender sender) { + private static @NotNull String normalHelpMessage(CommandSender sender) { // Message for admin users: /* * +--------------------------[MCDC/HELP]--------------------------+ @@ -110,7 +121,8 @@ private static String normalHelpMessage(CommandSender sender) { return out; } - private static String commandHelpPageStarter(String description) { + @Contract(pure = true) + private static @NotNull String commandHelpPageStarter(String description) { return ChatColor.RED + " If you are searching for the vanilla help, use \"" + ChatColor.GRAY + "/minecraft:help" + ChatColor.RED + "\"!\n\n" + ChatColor.AQUA + " Help for command \"" + ChatColor.GRAY + "/account" + ChatColor.AQUA + "\". Use \"" + ChatColor.GRAY + "/mcdc:help" + ChatColor.AQUA + "\"\n" + " to see a list of all available commands.\n\n" @@ -157,4 +169,27 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis return out; } + + @Contract(pure = true) + private static @NotNull String configHelp() { + return commandHelpPageStarter(" The config command provides functionality to configure\n" + + " The discord bot and the plugin behavior.") + + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "add" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Adds a value to the list at PATH\n" + + ChatColor.GRAY + " | |-> " + ChatColor.DARK_AQUA + "PATH" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The PATH to add the VALUE to\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "VALUE" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The VALUE to add to the list at PATH\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "default" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Resets the configuration to its default values.\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "get" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Gets the value from the PATH\n" + + ChatColor.GRAY + " | |-> " + ChatColor.DARK_AQUA + "PATH" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The PATH to get the value from\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "reload" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Reloads the configuration from the file.\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "remove" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Removes a value from the list at PATH\n" + + ChatColor.GRAY + " | |-> " + ChatColor.DARK_AQUA + "PATH" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The PATH to add the VALUE to\n" + + ChatColor.GRAY + " | `-> " + ChatColor.DARK_AQUA + "VALUE" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The VALUE to add to the list at PATH\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "save" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Saves the configuration to the config file\n" + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "set" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sets the PATH to VALUE\n" + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "PATH" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The PATH to add the VALUE to\n" + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "VALUE" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The VALUE to add to the list at PATH\n" + + spacerLine + ; + } } From 266728126a0c5ae4a2d43ff433774aba0841c10a Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:32:33 +0200 Subject: [PATCH 116/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?help=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/minecraft/commands/Help.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index 430f69c..bdebf6d 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -39,8 +39,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return true; } } - case "help" -> { - } + case "help" -> out += ChatColor.RESET + " Displays information about all available commands."; case "link" -> { } case "token" -> { @@ -136,7 +135,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "subcommand argument 1" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "subcommand argument 2" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Description\n" + spacerLine - + ChatColor.GREEN + ChatColor.UNDERLINE + "Subcommands" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n"; + + ChatColor.GREEN + ChatColor.UNDERLINE + "Subcommands" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n" + ChatColor.RESET; } private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermission) { From 2492070a8f0f09859a8a56381200a053ee1a0652 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:37:59 +0200 Subject: [PATCH 117/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?link=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/minecraft/commands/Help.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index bdebf6d..399959b 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -191,4 +191,12 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis + spacerLine ; } + + private static @NotNull String linkHelp() { + return commandHelpPageStarter(""" + The link command is used to link your minecraft and + your discord account unofficially, so you can use functions + /dcmsg and pinging of users.""") + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "OPTIONAL - The token given to you by the discord bot on discord.\n"; + } } From 8ba55680347372c8ca646cd9af944d5aa41b5214 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:39:35 +0200 Subject: [PATCH 118/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?link=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/minecraft/commands/Help.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index 399959b..ecded9f 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -40,8 +40,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } } case "help" -> out += ChatColor.RESET + " Displays information about all available commands."; - case "link" -> { - } + case "link" -> out += linkHelp(); case "token" -> { } case "unlink" -> { From 03f0c1b3cdb148b17080b8ff5c423df08caae8e9 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:42:08 +0200 Subject: [PATCH 119/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?unlink=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/mafelp/minecraft/commands/Help.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index ecded9f..a7021be 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -43,8 +43,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command case "link" -> out += linkHelp(); case "token" -> { } - case "unlink" -> { - } + case "unlink" -> out += commandHelpPageStarter("The command used to delete your account/relationship with the discord bot."); case "whisper", "dcmsg" -> { } default -> { From 92464463690bf0e32d056ee83a6bf401c5f32a96 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:48:47 +0200 Subject: [PATCH 120/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?token=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/minecraft/commands/Help.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index a7021be..d6b97cc 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -42,6 +42,15 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command case "help" -> out += ChatColor.RESET + " Displays information about all available commands."; case "link" -> out += linkHelp(); case "token" -> { + if (CheckPermission.checkPermission(Permissions.configEdit, sender)) + out += tokenHelp(); + else { + sender.sendMessage( + Settings.prefix + ChatColor.RED + "Sorry, you don't have the permission to edit the config,\n" + + Settings.prefix + "So the help would be of no use for you!" + ); + return true; + } } case "unlink" -> out += commandHelpPageStarter("The command used to delete your account/relationship with the discord bot."); case "whisper", "dcmsg" -> { @@ -197,4 +206,10 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis /dcmsg and pinging of users.""") + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "OPTIONAL - The token given to you by the discord bot on discord.\n"; } + + private static @NotNull String tokenHelp() { + return commandHelpPageStarter(" The token command is used to change the discord bot token and restart the bot instance. ") + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The token used to identify the bot with discord.\n" + + "For more information, please see: https://mafelp.github.io/MCDC/installation#get-a-discord-bot-token\n"; + } } From bf9a5a5b027833c16a5167229728842efe7aa116 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 21:54:48 +0200 Subject: [PATCH 121/158] =?UTF-8?q?=E2=9E=95=20Added=20help=20for=20the=20?= =?UTF-8?q?whisper=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/commands/Help.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index d6b97cc..924aac9 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -53,8 +53,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } } case "unlink" -> out += commandHelpPageStarter("The command used to delete your account/relationship with the discord bot."); - case "whisper", "dcmsg" -> { - } + case "whisper", "dcmsg" -> out += whisperHelp(); default -> { out += ChatColor.RED + "Unknown command: \"" + ChatColor.GRAY + args[0] + ChatColor.RED + "\"! See below for a full list!\n"; out += normalHelpMessage(sender); @@ -212,4 +211,12 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The token used to identify the bot with discord.\n" + "For more information, please see: https://mafelp.github.io/MCDC/installation#get-a-discord-bot-token\n"; } + + private static @NotNull String whisperHelp() { + return commandHelpPageStarter(" The whisper/dcmsg command is used to write private messages\n" + + " to your friends on discord. This requires you to have an account.") + + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "account tag" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The account tag for the person who should be messaged\n" + + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "message" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The message you want to send them.\n" + ; + } } From a4d65af37770068d291d811a86b15e97da638ef5 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 22:00:41 +0200 Subject: [PATCH 122/158] =?UTF-8?q?=E2=9E=95=20Added=20tab=20completion=20?= =?UTF-8?q?for=20the=20help=20command.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/github/mafelp/minecraft/Main.java | 2 +- .../tabCompleters/HelpTabCompleter.java | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/tabCompleters/HelpTabCompleter.java diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 8ece433..9be7a12 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -98,7 +98,7 @@ private void commandRegistration() { Objects.requireNonNull(getCommand("config")).setTabCompleter(new ConfigTabCompleter()); Logging.info("Command \"config\" has been enabled."); Objects.requireNonNull(getCommand("help")).setExecutor(new Help()); - //Objects.requireNonNull(getCommand("help")).setTabCompleter(new HelpTabCompleter()); + Objects.requireNonNull(getCommand("help")).setTabCompleter(new HelpTabCompleter()); Logging.info("Command \"help\" has been enabled."); if (Settings.getConfiguration().getBoolean("enableLinking")) { Objects.requireNonNull(getCommand("link")).setExecutor(new Link()); diff --git a/src/main/java/com/github/mafelp/minecraft/tabCompleters/HelpTabCompleter.java b/src/main/java/com/github/mafelp/minecraft/tabCompleters/HelpTabCompleter.java new file mode 100644 index 0000000..fbfcdb9 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/tabCompleters/HelpTabCompleter.java @@ -0,0 +1,40 @@ +package com.github.mafelp.minecraft.tabCompleters; + +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Permissions; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class HelpTabCompleter implements TabCompleter { + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + if (args.length != 1) + return Collections.emptyList(); + + List out = new ArrayList<>(); + + if (CheckPermission.checkPermission(Permissions.configEdit, sender)) + out.addAll(Arrays.asList("token", "config")); + + out.addAll(Arrays.asList( + "account", + "help", + "link", + "token", + "unlink", + "whisper", + "dcmsg" + )); + + return ResultSorter.sortedResults(args[0], out); + } +} From 0be642ecbf657735f42c29f11b0304cb2a113bd3 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 22:32:45 +0200 Subject: [PATCH 123/158] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Visual=20bug=20?= =?UTF-8?q?fixes=20in=20some=20help=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/minecraft/commands/Help.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index 924aac9..54bf48e 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -39,7 +39,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return true; } } - case "help" -> out += ChatColor.RESET + " Displays information about all available commands."; + case "help" -> out += ChatColor.RESET + " Displays information about all available commands.\n"; case "link" -> out += linkHelp(); case "token" -> { if (CheckPermission.checkPermission(Permissions.configEdit, sender)) @@ -52,7 +52,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return true; } } - case "unlink" -> out += commandHelpPageStarter("The command used to delete your account/relationship with the discord bot."); + case "unlink" -> out += commandHelpPageStarter("The command used to delete your account/relationship with the discord bot.\n"); case "whisper", "dcmsg" -> out += whisperHelp(); default -> { out += ChatColor.RED + "Unknown command: \"" + ChatColor.GRAY + args[0] + ChatColor.RED + "\"! See below for a full list!\n"; @@ -194,7 +194,6 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "set" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Sets the PATH to VALUE\n" + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "PATH" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The PATH to add the VALUE to\n" + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "VALUE" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The VALUE to add to the list at PATH\n" - + spacerLine ; } @@ -209,7 +208,7 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis private static @NotNull String tokenHelp() { return commandHelpPageStarter(" The token command is used to change the discord bot token and restart the bot instance. ") + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The token used to identify the bot with discord.\n" + - "For more information, please see: https://mafelp.github.io/MCDC/installation#get-a-discord-bot-token\n"; + "For more information, please see: \nhttps://mafelp.github.io/MCDC/installation#get-a-discord-bot-token\n"; } private static @NotNull String whisperHelp() { From a66be2805bfc7a6392748e8d00364aaf64a51a33 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 22:35:45 +0200 Subject: [PATCH 124/158] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Visual=20bug=20?= =?UTF-8?q?fixes=20in=20default=20help=20page=20Made=20the=20command=20var?= =?UTF-8?q?iable=20for=20each=20individual?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/minecraft/commands/Help.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/commands/Help.java b/src/main/java/com/github/mafelp/minecraft/commands/Help.java index 54bf48e..5a7f3a4 100644 --- a/src/main/java/com/github/mafelp/minecraft/commands/Help.java +++ b/src/main/java/com/github/mafelp/minecraft/commands/Help.java @@ -52,7 +52,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command return true; } } - case "unlink" -> out += commandHelpPageStarter("The command used to delete your account/relationship with the discord bot.\n"); + case "unlink" -> out += commandHelpPageStarter("/unlink", "The command used to delete your account/relationship with the discord bot.\n"); case "whisper", "dcmsg" -> out += whisperHelp(); default -> { out += ChatColor.RED + "Unknown command: \"" + ChatColor.GRAY + args[0] + ChatColor.RED + "\"! See below for a full list!\n"; @@ -127,9 +127,9 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } @Contract(pure = true) - private static @NotNull String commandHelpPageStarter(String description) { + private static @NotNull String commandHelpPageStarter(String command, String description) { return ChatColor.RED + " If you are searching for the vanilla help, use \"" + ChatColor.GRAY + "/minecraft:help" + ChatColor.RED + "\"!\n\n" - + ChatColor.AQUA + " Help for command \"" + ChatColor.GRAY + "/account" + ChatColor.AQUA + "\". Use \"" + ChatColor.GRAY + "/mcdc:help" + ChatColor.AQUA + "\"\n" + + ChatColor.AQUA + " Help for command \"" + ChatColor.GRAY + command + ChatColor.AQUA + "\". Use \"" + ChatColor.GRAY + "/mcdc:help" + ChatColor.AQUA + "\"\n" + " to see a list of all available commands.\n\n" + ChatColor.GREEN + ChatColor.UNDERLINE + "Description" + ChatColor.RESET + ChatColor.DARK_GRAY + ":\n" + ChatColor.RESET + description + "\n" @@ -145,7 +145,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command } private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermission) { - String out = commandHelpPageStarter(" The account command provides lots of useful features for managing\n" + String out = commandHelpPageStarter("/account", " The account command provides lots of useful features for managing\n" + " your local minecraft server/discord relationship.\n" + ChatColor.RED + ChatColor.BOLD + " THIS ACCOUNT IS NOT OFFICIAL AND ONLY VALID ON THIS SERVER AND WITH THE MCDC BOT!") ; @@ -177,7 +177,7 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis @Contract(pure = true) private static @NotNull String configHelp() { - return commandHelpPageStarter(" The config command provides functionality to configure\n" + + return commandHelpPageStarter("/config", " The config command provides functionality to configure\n" + " The discord bot and the plugin behavior.") + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "add" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "Adds a value to the list at PATH\n" @@ -198,7 +198,7 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis } private static @NotNull String linkHelp() { - return commandHelpPageStarter(""" + return commandHelpPageStarter("/link", """ The link command is used to link your minecraft and your discord account unofficially, so you can use functions /dcmsg and pinging of users.""") @@ -206,13 +206,13 @@ private static String accountHelp(boolean isPlayer, boolean hasAccountEditPermis } private static @NotNull String tokenHelp() { - return commandHelpPageStarter(" The token command is used to change the discord bot token and restart the bot instance. ") + return commandHelpPageStarter("/token", " The token command is used to change the discord bot token and restart the bot instance. ") + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "token" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The token used to identify the bot with discord.\n" + "For more information, please see: \nhttps://mafelp.github.io/MCDC/installation#get-a-discord-bot-token\n"; } private static @NotNull String whisperHelp() { - return commandHelpPageStarter(" The whisper/dcmsg command is used to write private messages\n" + + return commandHelpPageStarter("/whisper", " The whisper/dcmsg command is used to write private messages\n" + " to your friends on discord. This requires you to have an account.") + ChatColor.GRAY + " |-> " + ChatColor.DARK_AQUA + "account tag" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The account tag for the person who should be messaged\n" + ChatColor.GRAY + " `-> " + ChatColor.DARK_AQUA + "message" + ChatColor.GRAY + " -> " + ChatColor.BLUE + "The message you want to send them.\n" From e4b3bfea6c7c65a35fa34219fc6a6d13d41f3590 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 10 Aug 2021 22:37:09 +0200 Subject: [PATCH 125/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20README.md=20Up?= =?UTF-8?q?dated=20Status=20of=20the=20help=20command.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 52dfef8..cde6e65 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ The bot can currently do all the checked items, unchecked will be implemented in - [ ] `/account` - [ ] `/config` - [ ] Add a new command: `/help` + - [X] `/help` in minecraft + - [ ] `/help` in discord ## Installation 1. Download the latest [release](https://github.com/MaFeLP/MCDC/releases/) and put it into `/plugins`. From f911be9b215295da6740e89ca6438fdb22290ce9 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Fri, 10 Sep 2021 21:52:04 +0200 Subject: [PATCH 126/158] =?UTF-8?q?=E2=9E=95=20Added=20Help=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 4 ++ .../mafelp/discord/commands/HelpListener.java | 57 +++++++++++++++++++ .../commands/MainSlashCommandListener.java | 3 +- 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/github/mafelp/discord/commands/HelpListener.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 38f320b..b8b7477 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -127,6 +127,10 @@ public void run() { * Method to register all slash commands (in bulk). */ private void registerSlashCommands() { + SlashCommand.with("help", "A command to give help about this bot and its commands").setDefaultPermission(true).createGlobal(discordApi).thenAccept(slashCommand -> + Logging.info("Added global slash command \"/" + slashCommand.getName() + "\"") + ); + List accountSlashCommands = new ArrayList<>(); List adminSlashCommands = new ArrayList<>(); diff --git a/src/main/java/com/github/mafelp/discord/commands/HelpListener.java b/src/main/java/com/github/mafelp/discord/commands/HelpListener.java new file mode 100644 index 0000000..09ebf62 --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/commands/HelpListener.java @@ -0,0 +1,57 @@ +package com.github.mafelp.discord.commands; + +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Permissions; +import org.javacord.api.entity.message.component.ActionRow; +import org.javacord.api.entity.message.component.SelectMenu; +import org.javacord.api.entity.message.component.SelectMenuOption; +import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.entity.user.User; +import org.javacord.api.event.interaction.SlashCommandCreateEvent; +import java.util.Arrays; +import java.util.List; + +/** + * The class used to listen in discord and unlinks your account. + */ +public class HelpListener { + /** + * The method that initializes the unlinking. + * @param event The event that hold information about this specific command. + */ + public static void onSlashCommand(SlashCommandCreateEvent event) { + User author = event.getSlashCommandInteraction().getUser(); + + List options = Arrays.asList( + SelectMenuOption.create("Account", "Account"), + SelectMenuOption.create("Help", "Help"), + SelectMenuOption.create("Link", "Link"), + SelectMenuOption.create("mcmsg", "mcmsg"), + SelectMenuOption.create("Unlink", "Unlink"), + SelectMenuOption.create("Whisper", "Whisper") + ); + if (CheckPermission.checkPermission(Permissions.discordBotAdmin, author.getId()) || CheckPermission.checkPermission(Permissions.discordServerAdmin, author.getId())) + options.addAll(Arrays.asList( + SelectMenuOption.create("Config", "Config"), + SelectMenuOption.create("Create Channel", "Create Channel"), + SelectMenuOption.create("Create Role", "Create Role"), + SelectMenuOption.create("Setup", "Setup") + )); + + event.getSlashCommandInteraction().createImmediateResponder() + .addEmbed(new EmbedBuilder() + .setTitle("Help Menu") + .setAuthor(author) + .setFooter("MCDC was created by: MaFeLP", "https://avatars.githubusercontent.com/u/60669873") + .setTimestampToNow() + .setDescription(""" + Please select an action from the menu below, you want to get help about! + + If you want to get more detailed information about the individual commands, you can check out our wiki page: https://mafelp.github.io/MCDC/""") + ) + .addComponents(ActionRow.of( + SelectMenu.create("helpSelectMenu", options) + )).respond().thenAccept(interactionOriginalResponseUpdater -> Logging.info("User \"" + author.getName() + "\" executed command \"help\"; Result: SelectMenu and normal help")); + } +} diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index 54cd27d..7606ed0 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -33,7 +33,8 @@ public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": no First option given!"); } } + case "help" -> HelpListener.onSlashCommand(slashCommandCreateEvent); default -> Logging.info(ChatColor.RED + "Wait. Wait? This command is not recognised: " + slashCommandCreateEvent.getSlashCommandInteraction().getCommandName() + " and this should not have happened!"); } } -} \ No newline at end of file +} From ebc0009e65e850175de31026458a08c3ce845451 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Fri, 10 Sep 2021 22:13:03 +0200 Subject: [PATCH 127/158] =?UTF-8?q?=F0=9F=96=8C=EF=B8=8F=20Changed=20Help?= =?UTF-8?q?=20Embed=20Color?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/github/mafelp/discord/commands/HelpListener.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/github/mafelp/discord/commands/HelpListener.java b/src/main/java/com/github/mafelp/discord/commands/HelpListener.java index 09ebf62..679ae29 100644 --- a/src/main/java/com/github/mafelp/discord/commands/HelpListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/HelpListener.java @@ -9,6 +9,8 @@ import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.user.User; import org.javacord.api.event.interaction.SlashCommandCreateEvent; + +import java.awt.*; import java.util.Arrays; import java.util.List; @@ -45,6 +47,7 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { .setAuthor(author) .setFooter("MCDC was created by: MaFeLP", "https://avatars.githubusercontent.com/u/60669873") .setTimestampToNow() + .setColor(new Color(0xAAFF00)) .setDescription(""" Please select an action from the menu below, you want to get help about! From 92602e118e148454f97c4a40ad794713d8df0ef6 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 19 Jan 2022 21:38:01 +0100 Subject: [PATCH 128/158] =?UTF-8?q?=E2=9E=95=20Added=20a=20help=20slash=20?= =?UTF-8?q?command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/mafelp/discord/DiscordMain.java | 8 +- .../MessageComponentCreationListener.java | 179 ++++++++++++++++++ 2 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index b8b7477..bbfbde4 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -88,6 +88,7 @@ public void run() { // register listeners .addListener(DiscordListener::new) .addListener(MainSlashCommandListener::new) + .addListener(MessageComponentCreationListener::new) // log the bot in and join the servers .login().join(); @@ -127,8 +128,11 @@ public void run() { * Method to register all slash commands (in bulk). */ private void registerSlashCommands() { - SlashCommand.with("help", "A command to give help about this bot and its commands").setDefaultPermission(true).createGlobal(discordApi).thenAccept(slashCommand -> - Logging.info("Added global slash command \"/" + slashCommand.getName() + "\"") + SlashCommand.with("help", "A command to give help about this bot and its commands") + .setDefaultPermission(true) + .createGlobal(discordApi) + .thenAccept(slashCommand -> + Logging.info("Added global slash command \"/" + slashCommand.getName() + "\"") ); List accountSlashCommands = new ArrayList<>(); diff --git a/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java b/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java new file mode 100644 index 0000000..946b6bf --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java @@ -0,0 +1,179 @@ +package com.github.mafelp.discord; + +import com.github.mafelp.utils.Logging; +import org.javacord.api.entity.message.component.ActionRow; +import org.javacord.api.entity.message.component.Button; +import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.event.interaction.MessageComponentCreateEvent; +import org.javacord.api.interaction.MessageComponentInteraction; +import org.javacord.api.interaction.callback.InteractionImmediateResponseBuilder; +import org.javacord.api.listener.interaction.MessageComponentCreateListener; + +import java.awt.*; + +public class MessageComponentCreationListener implements MessageComponentCreateListener { + @Override + public void onComponentCreate(MessageComponentCreateEvent event) { + MessageComponentInteraction interaction = event.getMessageComponentInteraction(); + + switch (interaction.getCustomId()) { + case "helpSelectMenu" -> helpSelectMenu(interaction); + default -> {} + } + } + + private static void helpSelectMenu(MessageComponentInteraction interaction) { + if (interaction.asSelectMenuInteraction().isEmpty()) + return; + interaction.getMessage().ifPresent(message -> { + if (message.canYouDelete()) + message.delete("Message no longer needed, as the help command continues.").thenAccept(none -> + Logging.debug("Removed original help message.")); + }); + + InteractionImmediateResponseBuilder message = interaction.createImmediateResponder() + .append("Your requested help page(s):") + .addComponents(ActionRow.of(Button.link("https://mafelp.github.io/MCDC/", "View on the web"))); + EmbedBuilder embed = new EmbedBuilder() + .setAuthor(interaction.getUser()) + .setColor(new Color(0xDE9A4C)) + .setTimestampToNow() + ; + interaction.asSelectMenuInteraction().get().getChosenOptions().forEach(selectMenuOption -> { + switch (selectMenuOption.getLabel()) { + case "Account" -> { + message.addEmbed(embed + .setTitle("Account Help") + .setDescription("Here is the information about the custom accounts\n\nFor more account controls, please log in to the Minecraft Server and use tab completion on the `/account` command") + .addField("/link", "Links your discord account to your Minecraft Account on this server.") + .addField("/unlink", "Removes the discord - Minecraft account link") + ); + Logging.debug("Added Account embed to the help message."); + } + case "Config" -> { + message.addEmbed(embed + .setTitle("Config Help") + .setDescription(""" + Administrators can change the configuration of this bot. + + This feature is currently only available as a server command! + As an administrator, you can also use the minecraft server console. + + To see available options, please use the `Tab` Key when typing `/config `. + """) + ); + Logging.debug("Added Config embed to the help message."); + } + case "Create Channel" -> { + message.addEmbed(embed + .setTitle("Create Channel Help") + .setDescription(""" + Takes one argument: + - The channel name + + What does this command do? It creates a channel with the specified name and adds it to its configuration to send all the minecraft messages to. + + It is advised to not use this command, but use the `/setup` command instead! + + This command can only be used by Server/Bot Admins!""") + ); + Logging.debug("Added createChannel embed to the help message."); + } + case "Create Role" -> { + message.addEmbed(embed + .setTitle("Create Role Help") + .setDescription(""" + Takes one argument: + - The role name + + What does this command do? It creates a new role with the specified name, so you can grant this role access to the minecraft related channels. + + It is advised to not use this command, but use the `/setup` command instead! + + This command can only be used by Server/Bot Admins!""") + ); + Logging.debug("Added createRole embed to the help message."); + } + case "Help" -> { + message.addEmbed(embed + .setTitle("Help") + .setDescription(""" + Gets you a menu, with which you can get further information on all the commands. + + If you still need further help, please write the developers an email (mafelp@protonmail.ch)!""") + ); + Logging.debug("Added Help embed to the help message."); + } + case "Link" -> { + message.addEmbed(embed + .setTitle("Link Help") + .setDescription(""" + This command either takes one optional argument: A link token. + You can obtain a link token, by running `/link` in minecraft. + If you leave the token field blank, this command will generate you a link token, which you can then use as an argument in minecraft to link your accounts. + + Linking of your account enables you for whisper messages between discord users and minecraft users (and the other way round as well), as well as getting clickable mentions if mentioned with `@` in the minecraft chat.""") + ); + Logging.debug("Added Link embed to the help message."); + } + case "mcmsg" -> { + message.addEmbed(embed + .setTitle("mcmsg Help") + .setDescription(""" + Send a private message to a person on discord, that just they can see! + + This command takes two arguments: + - The first argument is the user(name) that you want to send the message to. + - The second argument is the message you want to send them.""") + ); + Logging.debug("Added mcmsg embed to the help message."); + } + case "Setup" -> { + message.addEmbed(embed + .setTitle("Setup Help") + .setDescription(""" + Setup a new channel for incoming messages and a new role to manage permissions with. + + This command takes one argument: The name of the new channel and role (it will be the same name)""") + ); + Logging.debug("Added Setup embed to the help message."); + } + case "Unlink" -> { + message.addEmbed(embed + .setTitle("Unlink Help") + .setDescription("Unlinks your discord and minecraft accounts. If you want to link your accounts, run `/link` either in discord or in minecraft.") + ); + Logging.debug("Added Unlink embed to the help message."); + } + case "Whisper" -> { + message.addEmbed(embed + .setTitle("Whisper Help") + .setDescription(""" + Send a private message to a person on discord, that just they can see! + + This command takes two arguments: + - The first argument is the user(name) that you want to send the message to. + - The second argument is the message you want to send them.""") + ); + Logging.debug("Added Whisper embed to the help message."); + } + default -> { + message.addEmbed(new EmbedBuilder() + .setColor(new Color(0xFF0048)) + .setTitle("Error!") + .setAuthor(interaction.getApi().getYourself()) + .setDescription(""" + An internal server error occurred! + + Please create an issue here: https://github.com/MaFeLP/MCDC/issues/new + and reference the following error message: + + MessageComponentCreationListener.java: Unrecognised selectMenuLabel \"""" + selectMenuOption.getLabel() + "\"") + ); + Logging.debug("Added Account embed to the help message."); + } + } + }); + message.respond(); + } +} From a888ae7add3b19226968f32f4aa9b736e4015d80 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:11:17 +0100 Subject: [PATCH 129/158] =?UTF-8?q?=E2=9E=95=20Added=20Events=20configurat?= =?UTF-8?q?ion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- defaultConfiguration.yml | 9 ++++++ .../com/github/mafelp/utils/Settings.java | 31 ++++++++++++------- 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/defaultConfiguration.yml b/defaultConfiguration.yml index 47e5ce1..46004fe 100644 --- a/defaultConfiguration.yml +++ b/defaultConfiguration.yml @@ -66,6 +66,15 @@ sendCommandToDiscord: # ... the server. server: false +# Server events that will trigger a message in discord +events: + - JoinEvent # When a player joins the Server + - LeaveEvent # When a player leaves the Server + - PlayerAdvancementEvent # When a player gets a new Advancement + - PlayerDeathEvent # When a Player dies + - ServerStartupEvent # When the minecraft server starts + - ServerShutdownEvent # When the minecraft server stops + # Permission section for setting permission levels permission: # The permissions on linking and editing accounts. diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 1debd4f..f6704ce 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -6,10 +6,9 @@ import org.javacord.api.DiscordApi; import org.javacord.api.event.message.MessageCreateEvent; -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; +import java.io.File; +import java.io.IOException; +import java.util.*; import static com.github.mafelp.utils.Logging.info; import static com.github.mafelp.utils.Logging.logIOException; @@ -23,7 +22,7 @@ * ] */ public class Settings { - // Internal variables:: + // Internal variables: /** * communication API with Discord, defined in DiscordMain.init() */ @@ -70,6 +69,11 @@ public class Settings { */ public static volatile String serverName; + /** + * The events the server admin has subscribed to. + */ + public static volatile List events; + /** * API token used to authenticate the bot to discord - * defined in config.yml - @@ -232,6 +236,7 @@ public static void init() { shortMsg = configuration.getBoolean("useShortMessageFormat"); prefix = configuration.getString("pluginPrefix"); serverName = configuration.getString("serverName"); + events = configuration.getStringList("events"); debug = configuration.getBoolean("debug"); discordCommandPrefix = configuration.getString("discordCommandPrefix"); } @@ -251,12 +256,16 @@ public static YamlConfiguration createDefaultConfig() { defaultConfiguration.set("debug", false); defaultConfiguration.set("discordCommandPrefix", "."); defaultConfiguration.set("deleteDiscordCommandMessages", false); - List channelIDs = new ArrayList<>(); - channelIDs.add(1234L); - defaultConfiguration.set("channelIDs", channelIDs); - List roleIDs = new ArrayList<>(); - roleIDs.add(1234L); - defaultConfiguration.set("roleIDs", roleIDs); + defaultConfiguration.set("events", Arrays.asList( + "JoinEvent", + "LeaveEvent", + "PlayerAdvancementEvent", + "PlayerDeathEvent", + "ServerShutdownEvent", + "ServerStartupEvent" + )); + defaultConfiguration.set("channelIDs", Collections.singletonList(1234L)); + defaultConfiguration.set("roleIDs", Collections.singletonList(1234L)); defaultConfiguration.set("enableLinking", true); defaultConfiguration.set("allowListAllAccounts", true); defaultConfiguration.set("showFooterInMessages", true); From 294b7cc0422b0f2eca3dc68989f60eb7166fcf5a Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:46:02 +0100 Subject: [PATCH 130/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20/help=20slash=20?= =?UTF-8?q?command=20not=20showing=20up?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- .../github/mafelp/discord/DiscordMain.java | 24 +++++++++------- .../mafelp/discord/commands/HelpListener.java | 28 ++++++++++++------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index bbfbde4..b2b4598 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -1,7 +1,7 @@ package com.github.mafelp.discord; import com.github.mafelp.accounts.AccountManager; -import com.github.mafelp.discord.commands.*; +import com.github.mafelp.discord.commands.MainSlashCommandListener; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; import org.bukkit.ChatColor; @@ -13,7 +13,7 @@ import org.javacord.api.entity.server.Server; import org.javacord.api.interaction.*; -import java.io.*; +import java.io.IOException; import java.util.*; import java.util.concurrent.CompletionException; @@ -128,16 +128,15 @@ public void run() { * Method to register all slash commands (in bulk). */ private void registerSlashCommands() { - SlashCommand.with("help", "A command to give help about this bot and its commands") - .setDefaultPermission(true) - .createGlobal(discordApi) - .thenAccept(slashCommand -> - Logging.info("Added global slash command \"/" + slashCommand.getName() + "\"") - ); - List accountSlashCommands = new ArrayList<>(); List adminSlashCommands = new ArrayList<>(); + // global help command. Is always enabled, but needs to be added to the account slash commands list, + // as the list will be the list of global commands and overwrite any others created before. + accountSlashCommands.add(SlashCommand.with("help", "A command to give help about this bot and its commands") + .setDefaultPermission(true) + ); + // Link command accountSlashCommands.add(SlashCommand.with("link", "A command to link your discord and minecraft accounts", Collections.singletonList( @@ -188,7 +187,12 @@ private void registerSlashCommands() { // If linking is NOT enabled, set the default permission for all the slash commands to false. No one can use them then if (!Settings.getConfiguration().getBoolean("enableLinking", true)) { Logging.info("Linking is not enabled. Setting permission for all slash commands to false."); - accountSlashCommands.forEach(slashCommandBuilder -> slashCommandBuilder.setDefaultPermission(false)); + int i = 0; + for (SlashCommandBuilder slashCommandBuilder : accountSlashCommands) { + if ( i != 0) + slashCommandBuilder.setDefaultPermission(false); + i++; + } } discordApi.bulkOverwriteGlobalSlashCommands(accountSlashCommands).thenAccept(slashCommands -> slashCommands.forEach(slashCommand -> { diff --git a/src/main/java/com/github/mafelp/discord/commands/HelpListener.java b/src/main/java/com/github/mafelp/discord/commands/HelpListener.java index 679ae29..37a7621 100644 --- a/src/main/java/com/github/mafelp/discord/commands/HelpListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/HelpListener.java @@ -25,21 +25,29 @@ public class HelpListener { public static void onSlashCommand(SlashCommandCreateEvent event) { User author = event.getSlashCommandInteraction().getUser(); - List options = Arrays.asList( - SelectMenuOption.create("Account", "Account"), - SelectMenuOption.create("Help", "Help"), - SelectMenuOption.create("Link", "Link"), - SelectMenuOption.create("mcmsg", "mcmsg"), - SelectMenuOption.create("Unlink", "Unlink"), - SelectMenuOption.create("Whisper", "Whisper") - ); + List options; if (CheckPermission.checkPermission(Permissions.discordBotAdmin, author.getId()) || CheckPermission.checkPermission(Permissions.discordServerAdmin, author.getId())) - options.addAll(Arrays.asList( + options = Arrays.asList( + SelectMenuOption.create("Account", "Account"), + SelectMenuOption.create("Help", "Help"), + SelectMenuOption.create("Link", "Link"), + SelectMenuOption.create("mcmsg", "mcmsg"), + SelectMenuOption.create("Unlink", "Unlink"), + SelectMenuOption.create("Whisper", "Whisper"), SelectMenuOption.create("Config", "Config"), SelectMenuOption.create("Create Channel", "Create Channel"), SelectMenuOption.create("Create Role", "Create Role"), SelectMenuOption.create("Setup", "Setup") - )); + ); + else + options = Arrays.asList( + SelectMenuOption.create("Account", "Account"), + SelectMenuOption.create("Help", "Help"), + SelectMenuOption.create("Link", "Link"), + SelectMenuOption.create("mcmsg", "mcmsg"), + SelectMenuOption.create("Unlink", "Unlink"), + SelectMenuOption.create("Whisper", "Whisper") + ); event.getSlashCommandInteraction().createImmediateResponder() .addEmbed(new EmbedBuilder() From 80cf2d00087495ad4bb27386031c626bb8ebcf3d Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 19 Jan 2022 22:50:22 +0100 Subject: [PATCH 131/158] =?UTF-8?q?=E2=87=A5=20Refactored=20the=20Minecraf?= =?UTF-8?q?t=20Listeners?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit They now have their own package Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- src/main/java/com/github/mafelp/minecraft/Main.java | 3 +++ .../mafelp/minecraft/{ => listeners}/CommandListener.java | 2 +- .../github/mafelp/minecraft/{ => listeners}/JoinListener.java | 2 +- .../minecraft/{ => listeners}/MinecraftChatListener.java | 2 +- 4 files changed, 6 insertions(+), 3 deletions(-) rename src/main/java/com/github/mafelp/minecraft/{ => listeners}/CommandListener.java (97%) rename src/main/java/com/github/mafelp/minecraft/{ => listeners}/JoinListener.java (98%) rename src/main/java/com/github/mafelp/minecraft/{ => listeners}/MinecraftChatListener.java (96%) diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 9be7a12..1b38eb0 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -2,6 +2,9 @@ import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.minecraft.commands.*; +import com.github.mafelp.minecraft.listeners.CommandListener; +import com.github.mafelp.minecraft.listeners.JoinListener; +import com.github.mafelp.minecraft.listeners.MinecraftChatListener; import com.github.mafelp.minecraft.tabCompleters.*; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; diff --git a/src/main/java/com/github/mafelp/minecraft/CommandListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/CommandListener.java similarity index 97% rename from src/main/java/com/github/mafelp/minecraft/CommandListener.java rename to src/main/java/com/github/mafelp/minecraft/listeners/CommandListener.java index db05770..864de3e 100644 --- a/src/main/java/com/github/mafelp/minecraft/CommandListener.java +++ b/src/main/java/com/github/mafelp/minecraft/listeners/CommandListener.java @@ -1,4 +1,4 @@ -package com.github.mafelp.minecraft; +package com.github.mafelp.minecraft.listeners; import com.github.mafelp.discord.DiscordMessageBroadcast; import com.github.mafelp.utils.Logging; diff --git a/src/main/java/com/github/mafelp/minecraft/JoinListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java similarity index 98% rename from src/main/java/com/github/mafelp/minecraft/JoinListener.java rename to src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java index c3cc9d1..b262c76 100644 --- a/src/main/java/com/github/mafelp/minecraft/JoinListener.java +++ b/src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java @@ -1,4 +1,4 @@ -package com.github.mafelp.minecraft; +package com.github.mafelp.minecraft.listeners; import com.github.mafelp.accounts.Account; import com.github.mafelp.utils.CheckPermission; diff --git a/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/MinecraftChatListener.java similarity index 96% rename from src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java rename to src/main/java/com/github/mafelp/minecraft/listeners/MinecraftChatListener.java index 608ee98..fef9e0b 100644 --- a/src/main/java/com/github/mafelp/minecraft/MinecraftChatListener.java +++ b/src/main/java/com/github/mafelp/minecraft/listeners/MinecraftChatListener.java @@ -1,4 +1,4 @@ -package com.github.mafelp.minecraft; +package com.github.mafelp.minecraft.listeners; import com.github.mafelp.accounts.Account; import com.github.mafelp.discord.ChannelAdmin; From fa204b9cbb671097ba4530a7368cf596394ebc62 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Wed, 19 Jan 2022 23:40:37 +0100 Subject: [PATCH 132/158] =?UTF-8?q?=E2=9E=95=20Added=20Advancement,=20Deat?= =?UTF-8?q?h,=20Leave=20and=20Join=20Listeners?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These listeners send a message to the discord channels, if one of these events is triggered. Fixes #41 Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- .../github/mafelp/discord/DiscordMain.java | 21 +++++++++ .../discord/DiscordMessageBroadcast.java | 45 +++++++++++++++++-- .../com/github/mafelp/minecraft/Main.java | 4 +- .../listeners/AdvancementListener.java | 22 +++++++++ .../minecraft/listeners/DeathListener.java | 22 +++++++++ .../minecraft/listeners/JoinListener.java | 13 +++++- .../minecraft/listeners/LeaveListener.java | 22 +++++++++ 7 files changed, 143 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java create mode 100644 src/main/java/com/github/mafelp/minecraft/listeners/DeathListener.java create mode 100644 src/main/java/com/github/mafelp/minecraft/listeners/LeaveListener.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index b2b4598..523a07e 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -122,8 +122,19 @@ public void run() { Logging.logIOException(e, "Could not load the Accounts in. The Account file is not present and it could not be created."); } } + + // Send an Event message that this player has joined + if (Settings.events.contains("ServerStartupEvent")) { + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( + "Server Startup", + "The server has been started and is now ready to connect!", + null); + discordMessageBroadcast.setName("StartupEventBroadcaster"); + discordMessageBroadcast.start(); + } } + /** * Method to register all slash commands (in bulk). */ @@ -244,6 +255,16 @@ private void registerSlashCommands() { * Shutdown method to disconnect the bot instance */ public static void shutdown() { + // Send an Event message that this player has joined + if (Settings.events.contains("ServerShutdownEvent")) { + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( + "Server Stopped", + "The server has been stopped.", + null); + discordMessageBroadcast.setName("ShutdownEventBroadcaster"); + discordMessageBroadcast.start(); + } + // check if the bot is already logged out if (Settings.discordApi == null) { // if so, log a message and return diff --git a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java index 45dbbe5..126ad60 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMessageBroadcast.java @@ -2,12 +2,11 @@ import com.github.mafelp.accounts.Account; import com.github.mafelp.minecraft.skins.Skin; -import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; -import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.javacord.api.entity.channel.Channel; import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.List; @@ -77,6 +76,19 @@ public DiscordMessageBroadcast(String command, Player player) { this.message = null; } + /** + * The constructor to define this thread as an event broadcast for discord channel. + * @param event The event that has happened + * @param message The message to accompany this event + * @param messageAuthor The player that might be referenced in this event + */ + public DiscordMessageBroadcast(String event, String message, @Nullable Player messageAuthor) { + this.command = event; + this.message = message; + this.messageAuthor = messageAuthor; + this.broadcastType = BroadcastType.eventBroadcast; + } + /** * The executing method to run the thread and sent all the messages. */ @@ -86,6 +98,7 @@ public void run() { case chatMessageBroadcast -> messageBroadcast(); case playerCommandBroadcast -> playerCommandBroadcast(); case serverCommandBroadcast -> serverCommandBroadcast(); + case eventBroadcast -> eventBroadcast(); } } @@ -172,6 +185,27 @@ private void playerCommandBroadcast() { sendMessages(embed); } + + private void eventBroadcast() { + // create an embed for the message + EmbedBuilder embed = new EmbedBuilder() + .setColor(new Color(0x17A288)) + .setAuthor(Settings.discordApi.getYourself()) + .setTitle(command) + .setDescription(message); + + if (messageAuthor != null) { + if (Account.getByPlayer(messageAuthor).isPresent()) + embed.setAuthor(Account.getByPlayer(messageAuthor).get().getUser()); + else + embed.setAuthor(messageAuthor.getDisplayName(), "https://namemc.com/profile/" + messageAuthor.getName(), new Skin(messageAuthor, false).getHead(), ".png"); + } + + if (Settings.getConfiguration().getBoolean("showFooterInMessages", true)) + embed.setFooter("On " + Settings.serverName); + + sendMessages(embed); + } } /** @@ -189,5 +223,10 @@ enum BroadcastType { /** * A player sent a normal message. */ - chatMessageBroadcast + chatMessageBroadcast, + + /** + * If an event was emitted + */ + eventBroadcast } \ No newline at end of file diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 1b38eb0..9e1411a 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -1,14 +1,15 @@ package com.github.mafelp.minecraft; import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.discord.DiscordMain; import com.github.mafelp.minecraft.commands.*; import com.github.mafelp.minecraft.listeners.CommandListener; import com.github.mafelp.minecraft.listeners.JoinListener; +import com.github.mafelp.minecraft.listeners.LeaveListener; import com.github.mafelp.minecraft.listeners.MinecraftChatListener; import com.github.mafelp.minecraft.tabCompleters.*; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; -import com.github.mafelp.discord.DiscordMain; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -86,6 +87,7 @@ private void listenerRegistration() { pluginManager.registerEvents(new JoinListener(), this); pluginManager.registerEvents(new MinecraftChatListener(), this); pluginManager.registerEvents(new CommandListener(), this); + pluginManager.registerEvents(new LeaveListener(), this); } /** diff --git a/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java new file mode 100644 index 0000000..628eacb --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java @@ -0,0 +1,22 @@ +package com.github.mafelp.minecraft.listeners; + +import com.github.mafelp.discord.DiscordMessageBroadcast; +import com.github.mafelp.utils.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerAdvancementDoneEvent; + +public class AdvancementListener implements Listener { + @EventHandler + public void onAdvancement(PlayerAdvancementDoneEvent playerAdvancementDoneEvent) { + // Send an Event message that this player has joined + if (Settings.events.contains("PlayerAdvancementEvent")) { + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( + "Advancement unlocked by " + playerAdvancementDoneEvent.getPlayer().getDisplayName() + "!", + "Player " + playerAdvancementDoneEvent.getPlayer().getDisplayName() + " has earned the advancement " + playerAdvancementDoneEvent.getAdvancement() + "!", + playerAdvancementDoneEvent.getPlayer()); + discordMessageBroadcast.setName("AdvancementEventBroadcaster"); + discordMessageBroadcast.start(); + } + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/listeners/DeathListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/DeathListener.java new file mode 100644 index 0000000..6f73fc7 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/listeners/DeathListener.java @@ -0,0 +1,22 @@ +package com.github.mafelp.minecraft.listeners; + +import com.github.mafelp.discord.DiscordMessageBroadcast; +import com.github.mafelp.utils.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class DeathListener implements Listener { + @EventHandler + public void onDeath(PlayerDeathEvent playerDeathEvent) { + // Send an Event message that this player has joined + if (Settings.events.contains("PlayerDeathEvent")) { + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( + playerDeathEvent.getEntity().getDisplayName() + " died!", + playerDeathEvent.getDeathMessage(), + playerDeathEvent.getEntity()); + discordMessageBroadcast.setName("DeathEventBroadcaster"); + discordMessageBroadcast.start(); + } + } +} diff --git a/src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java index b262c76..452b52e 100644 --- a/src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java +++ b/src/main/java/com/github/mafelp/minecraft/listeners/JoinListener.java @@ -1,11 +1,12 @@ package com.github.mafelp.minecraft.listeners; import com.github.mafelp.accounts.Account; +import com.github.mafelp.discord.DiscordMessageBroadcast; +import com.github.mafelp.minecraft.skins.Skin; import com.github.mafelp.utils.CheckPermission; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Permissions; import com.github.mafelp.utils.Settings; -import com.github.mafelp.minecraft.skins.Skin; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -69,6 +70,14 @@ public void onJoin(PlayerJoinEvent playerJoinEvent) { "configEdit: " + CheckPermission.checkPermission(Permissions.configEdit, playerJoinEvent.getPlayer()) ); - // TODO add discord message updating with online players. + // Send an Event message that this player has joined + if (Settings.events.contains("JoinEvent")) { + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( + "Player " + playerJoinEvent.getPlayer().getDisplayName() + " joined", + "Player " + playerJoinEvent.getPlayer().getDisplayName() + " has joined the game!", + playerJoinEvent.getPlayer()); + discordMessageBroadcast.setName("JoinEventBroadcaster"); + discordMessageBroadcast.start(); + } } } diff --git a/src/main/java/com/github/mafelp/minecraft/listeners/LeaveListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/LeaveListener.java new file mode 100644 index 0000000..b4588e0 --- /dev/null +++ b/src/main/java/com/github/mafelp/minecraft/listeners/LeaveListener.java @@ -0,0 +1,22 @@ +package com.github.mafelp.minecraft.listeners; + +import com.github.mafelp.discord.DiscordMessageBroadcast; +import com.github.mafelp.utils.Settings; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; + +public class LeaveListener implements Listener { + @EventHandler + public void onLeave(PlayerQuitEvent playerQuitEvent) { + // Send an Event message that this player has joined + if (Settings.events.contains("LeaveEvent")) { + DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( + "Player " + playerQuitEvent.getPlayer().getDisplayName() + " left", + "Player " + playerQuitEvent.getPlayer().getDisplayName() + " has disconnected from the game!", + playerQuitEvent.getPlayer()); + discordMessageBroadcast.setName("LeaveEventBroadcaster"); + discordMessageBroadcast.start(); + } + } +} From 7539188d6411ab15943890b27d47b2b3c448c7e6 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 20 Jan 2022 22:51:36 +0100 Subject: [PATCH 133/158] Bumped required Java version to 17 Fixes #42 Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> # Conflicts: # pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f67b3ec..d4cd614 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ A Spigot plugin for cross communicating with a discord server - 16 + 17 UTF-8 https://github.com/MaFeLP/MCDC From 191acd93f3877ab8525508b3c2ef62099a1541aa Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 20 Jan 2022 22:58:03 +0100 Subject: [PATCH 134/158] Added Java info version to the README Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index cde6e65..de8c163 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +![Java Version](https://img.shields.io/badge/Java%20Version-17-blue) + # MCDC A [Minecraft](https://www.minecraft.net) plugin for [paper servers](https://papermc.io). From 9682dd5ce7ea106a8b2b72696457cb3ad4235a06 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 13 Jan 2022 03:25:07 +0000 Subject: [PATCH 135/158] Maven(deps): Bump maven-compiler-plugin from 3.8.1 to 3.9.0 Bumps [maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.8.1 to 3.9.0. - [Release notes](https://github.com/apache/maven-compiler-plugin/releases) - [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.8.1...maven-compiler-plugin-3.9.0) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-compiler-plugin dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d4cd614..ff171af 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + 3.9.0 ${java.version} ${java.version} From 36f47adc94e241b179bb0dcef02f27bf18cb6581 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 10 Dec 2021 20:41:25 +0000 Subject: [PATCH 136/158] Maven(deps): Bump annotations from RELEASE to 23.0.0 Bumps [annotations](https://github.com/JetBrains/java-annotations) from RELEASE to 23.0.0. - [Release notes](https://github.com/JetBrains/java-annotations/releases) - [Changelog](https://github.com/JetBrains/java-annotations/blob/master/CHANGELOG.md) - [Commits](https://github.com/JetBrains/java-annotations/commits/23.0.0) --- updated-dependencies: - dependency-name: org.jetbrains:annotations dependency-type: direct:production ... Signed-off-by: dependabot[bot] # Conflicts: # pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ff171af..eda2e62 100644 --- a/pom.xml +++ b/pom.xml @@ -94,7 +94,7 @@ org.jetbrains annotations - 21.0.1 + 23.0.0 compile From e8188a2ebde837d56dc5f4900880035607c3b227 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 20 Jan 2022 23:08:49 +0100 Subject: [PATCH 137/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20Project=20Versi?= =?UTF-8?q?on=20number=20to=200.12.0-beta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- pom.xml | 2 +- src/main/java/com/github/mafelp/utils/Settings.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index eda2e62..8c74d47 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.github.mafelp mcdc - 0.11.0-beta + 0.12.0-beta jar Mcdc diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index f6704ce..d605907 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -36,7 +36,7 @@ public class Settings { /** * version number of the plugin - displayed to users */ - public static final String version = "v0.11.0-beta"; + public static final String version = "v0.12.0-beta"; /** * enables more information being displayed while executing events @@ -322,4 +322,4 @@ public static String getApiToken() { public static File getConfigurationFileDirectory() { return configurationFileDirectory; } -} \ No newline at end of file +} From a362c50f709f7e86bde94ed69609d4edbb562833 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 20 Jan 2022 23:28:45 +0100 Subject: [PATCH 138/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20the=20Changelo?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b93bb..218e5bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,15 @@ # Changelog +## Help Command & Event Listeners +➕ Added a help command for discord with nice buttons
+➕ Added Event Listeners for the events: + +- Server starts/stops (plugin is loaded/unloaded) +- Player joins/leaves the Server +- Player gets an advancement +- Player dies + +--- + ## Tab Completions ### v0.11.0-beta ➕ Added Tab Completion to all Minecraft commands From 7e42061cc6768288fcc25c22dc342c46e860cce1 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 27 Jan 2022 00:06:19 +0100 Subject: [PATCH 139/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20bug=20where=20no?= =?UTF-8?q?t=20all=20Listeners=20are=20registered?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements more of #41 Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- src/main/java/com/github/mafelp/minecraft/Main.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/Main.java b/src/main/java/com/github/mafelp/minecraft/Main.java index 9e1411a..d7ffde0 100644 --- a/src/main/java/com/github/mafelp/minecraft/Main.java +++ b/src/main/java/com/github/mafelp/minecraft/Main.java @@ -3,10 +3,7 @@ import com.github.mafelp.accounts.AccountManager; import com.github.mafelp.discord.DiscordMain; import com.github.mafelp.minecraft.commands.*; -import com.github.mafelp.minecraft.listeners.CommandListener; -import com.github.mafelp.minecraft.listeners.JoinListener; -import com.github.mafelp.minecraft.listeners.LeaveListener; -import com.github.mafelp.minecraft.listeners.MinecraftChatListener; +import com.github.mafelp.minecraft.listeners.*; import com.github.mafelp.minecraft.tabCompleters.*; import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; @@ -85,9 +82,11 @@ private void listenerRegistration() { // All listeners // for more information read the Javadoc in the specific classes pluginManager.registerEvents(new JoinListener(), this); + pluginManager.registerEvents(new LeaveListener(), this); pluginManager.registerEvents(new MinecraftChatListener(), this); pluginManager.registerEvents(new CommandListener(), this); - pluginManager.registerEvents(new LeaveListener(), this); + pluginManager.registerEvents(new AdvancementListener(), this); + pluginManager.registerEvents(new DeathListener(), this); } /** From f1f457b2a8114ca3806e4b991ab5d9cd5fcade0e Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 27 Jan 2022 11:03:08 +0100 Subject: [PATCH 140/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20advancements=20n?= =?UTF-8?q?ot=20displaying=20correctly?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> #41 is therefore operational! --- .../listeners/AdvancementListener.java | 57 ++++++++++++++++++- .../com/github/mafelp/utils/Settings.java | 2 +- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java index 628eacb..b57631b 100644 --- a/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java +++ b/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java @@ -1,19 +1,70 @@ package com.github.mafelp.minecraft.listeners; import com.github.mafelp.discord.DiscordMessageBroadcast; +import com.github.mafelp.utils.Logging; import com.github.mafelp.utils.Settings; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerAdvancementDoneEvent; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.Scanner; + public class AdvancementListener implements Listener { + private final HashMap advancements = new HashMap<>(); + private final boolean fileDisabled; + + public AdvancementListener() { + // Check if the config file exists + final File file = new File(Settings.configurationFileDirectory, "advancements.json"); + if (! file.exists()) { + fileDisabled = true; + return; + } + + String contents = ""; + try { + Scanner reader = new Scanner(file); + while (reader.hasNextLine()) { + contents += reader.nextLine(); + } + reader.close(); + } catch (FileNotFoundException e) { + Logging.logIOException(e, "Could not read from the advancements.json config file!"); + fileDisabled = true; + return; + } + + try { + JsonParser parser = new JsonParser(); + JsonObject json = parser.parse(contents).getAsJsonObject(); + json.entrySet().forEach(stringJsonElementEntry -> { + String key = stringJsonElementEntry.getKey(); + key = key.replaceFirst("\\.", "/"); + String value = stringJsonElementEntry.getValue().getAsString(); + advancements.putIfAbsent(key, value); + }); + } catch (Exception exception) { + Logging.logException(exception, "Could parse the advancements.json file!"); + fileDisabled = true; + return; + } + fileDisabled = false; + } + @EventHandler public void onAdvancement(PlayerAdvancementDoneEvent playerAdvancementDoneEvent) { // Send an Event message that this player has joined - if (Settings.events.contains("PlayerAdvancementEvent")) { + if (Settings.events.contains("PlayerAdvancementEvent") && ! fileDisabled) { + String description_key = playerAdvancementDoneEvent.getAdvancement().getKey().getKey() + ".description"; + String title_key = playerAdvancementDoneEvent.getAdvancement().getKey().getKey() + ".title"; DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( - "Advancement unlocked by " + playerAdvancementDoneEvent.getPlayer().getDisplayName() + "!", - "Player " + playerAdvancementDoneEvent.getPlayer().getDisplayName() + " has earned the advancement " + playerAdvancementDoneEvent.getAdvancement() + "!", + "Advancement made: " + advancements.get(title_key) + "!", + advancements.get(description_key), playerAdvancementDoneEvent.getPlayer()); discordMessageBroadcast.setName("AdvancementEventBroadcaster"); discordMessageBroadcast.start(); diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index d605907..1f9b609 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -178,7 +178,7 @@ public static String consoleMessagePrefix(MessageCreateEvent event) { /** * Directory where the configuration files are in */ - private static final File configurationFileDirectory = new File("./plugins/MCDC"); + public static final File configurationFileDirectory = new File("./plugins/MCDC"); /** * The file in which the configurations are specified in From 0e0fee45d9a377ad43de288f12c5449c4ed29c06 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 27 Jan 2022 12:14:30 +0100 Subject: [PATCH 141/158] =?UTF-8?q?=F0=9F=86=99=20Bumped=20plugin=20versio?= =?UTF-8?q?n=20to=200.12.1-beta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- pom.xml | 2 +- src/main/java/com/github/mafelp/utils/Settings.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 8c74d47..d67f4f1 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.github.mafelp mcdc - 0.12.0-beta + 0.12.1-beta jar Mcdc diff --git a/src/main/java/com/github/mafelp/utils/Settings.java b/src/main/java/com/github/mafelp/utils/Settings.java index 1f9b609..c636ea3 100644 --- a/src/main/java/com/github/mafelp/utils/Settings.java +++ b/src/main/java/com/github/mafelp/utils/Settings.java @@ -36,7 +36,7 @@ public class Settings { /** * version number of the plugin - displayed to users */ - public static final String version = "v0.12.0-beta"; + public static final String version = "v0.12.1-beta"; /** * enables more information being displayed while executing events From 4124c8efc00209c64254a79eccbd251a14268533 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 27 Jan 2022 12:28:01 +0100 Subject: [PATCH 142/158] =?UTF-8?q?=F0=9F=90=9E=20Fixed=20Plugin=20throwin?= =?UTF-8?q?g=20an=20error=20on=20unknown=20achievement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This will now only print an error message, but not disable the plugin. Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- .../listeners/AdvancementListener.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java b/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java index b57631b..3c454df 100644 --- a/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java +++ b/src/main/java/com/github/mafelp/minecraft/listeners/AdvancementListener.java @@ -5,9 +5,11 @@ import com.github.mafelp.utils.Settings; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerAdvancementDoneEvent; +import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileNotFoundException; @@ -60,11 +62,20 @@ public AdvancementListener() { public void onAdvancement(PlayerAdvancementDoneEvent playerAdvancementDoneEvent) { // Send an Event message that this player has joined if (Settings.events.contains("PlayerAdvancementEvent") && ! fileDisabled) { - String description_key = playerAdvancementDoneEvent.getAdvancement().getKey().getKey() + ".description"; - String title_key = playerAdvancementDoneEvent.getAdvancement().getKey().getKey() + ".title"; + String advancementKey = playerAdvancementDoneEvent.getAdvancement().getKey().getKey(); + String description_key = advancementKey + ".description"; + String title_key = advancementKey + ".title"; + @Nullable + String title = advancements.get(title_key); + @Nullable + String description = advancements.get(description_key); + if (description == null || title == null) { + Logging.info(ChatColor.RED + "Could not get advancement for " + ChatColor.GRAY + advancementKey + ChatColor.RED +"!"); + return; + } DiscordMessageBroadcast discordMessageBroadcast = new DiscordMessageBroadcast( - "Advancement made: " + advancements.get(title_key) + "!", - advancements.get(description_key), + "Advancement made: " + title + "!", + description, playerAdvancementDoneEvent.getPlayer()); discordMessageBroadcast.setName("AdvancementEventBroadcaster"); discordMessageBroadcast.start(); From 15772ef459d0f4fdb88efd8f713ee5e1996ee66d Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Thu, 27 Jan 2022 12:28:59 +0100 Subject: [PATCH 143/158] =?UTF-8?q?=E2=9E=95=20Added=20packaging=20script?= =?UTF-8?q?=20for=20easier=20release?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- bash-scripts/package.sh | 141 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 bash-scripts/package.sh diff --git a/bash-scripts/package.sh b/bash-scripts/package.sh new file mode 100644 index 0000000..b275f24 --- /dev/null +++ b/bash-scripts/package.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash + +if [ -z "$2" ] +then + cat < Directory '/tmp/package/plugins/mcdc' and parents has been created!" +echo ":: Copying files" +cp -v defaultConfiguration.yml /tmp/package/plugins/mcdc/config.yml +cp -v LICENSE /tmp/package/plugins/mcdc/LICENSE +cp -v "target/mcdc-$2.jar" /tmp/package/plugins/ + +# Create the config file for the advancements +( + echo ":: Generating advancements.json file" + echo "==> Using Minecraft directory $1" + echo "==> Using Minecraft version 1.18" + echo "==> Using language: en_gb" + cd "$1/assets/" || exit 1 + HASH=$(jq -r '.objects."minecraft/lang/en_gb.json".hash' < "indexes/1.18.json") + DIRECTORY=$(echo "$HASH" | cut -c '-2') + echo "==> Hash for file is: $HASH" + echo "==> Directory of Hash file is: $DIRECTORY" + echo "==> Extracting all advancements from the file..." + echo -n "{" > /tmp/advancements.json + grep ' "advancements.' < "objects/$DIRECTORY/$HASH" | sed -e 's/ "advancements./"/g' | tr '\n' ' ' | tr '\n' ' ' >> /tmp/advancements.json + echo "}" >> /tmp/advancements.json + sed -i 's/, }/}/g' /tmp/advancements.json + jq > "/tmp/advancements_new.json" < "/tmp/advancements.json" + mv "/tmp/advancements_new.json" "/tmp/package/plugins/mcdc/advancements.json" + echo "==> Advancement configuration created at '/tmp/package/plugins/mcdc/advancements.json'" +) + +# Create the packages +( + cd /tmp/package/ || exit 1 + echo ":: Creating packages" + echo "==> Creating zip package" + zip -r -9 "mcdc-$2-package.zip" plugins + echo "==> Creating tar.gz package" + tar czfv "mcdc-$2-package.tar.gz" plugins + echo ":: Creating checksums" + cat > "ReleaseMessage.md" < +## Changes +- See the included Changelog +- **Full Changelog**: https://github.com/MaFeLP/MCDC/compare/vX.XX.X-beta...v$2 + +## Checksums: +
+Click to expand + +- mcdc-$2-package.tar.gz + - MD5: \`$(md5sum "mcdc-$2-package.tar.gz" | cut -d ' ' -f1)\` + - SHA1: \`$(sha1sum "mcdc-$2-package.tar.gz" | cut -d ' ' -f1)\` + - SHA256: \`$(sha256sum "mcdc-$2-package.tar.gz" | cut -d ' ' -f1)\` + - SHA512: \`$(sha512sum "mcdc-$2-package.tar.gz" | cut -d ' ' -f1)\` +- mcdc-$2-package.zip + - MD5: \`$(md5sum "mcdc-$2-package.zip" | cut -d ' ' -f1)\` + - SHA1: \`$(sha1sum "mcdc-$2-package.zip" | cut -d ' ' -f1)\` + - SHA256: \`$(sha256sum "mcdc-$2-package.zip" | cut -d ' ' -f1)\` + - SHA512: \`$(sha512sum "mcdc-$2-package.zip" | cut -d ' ' -f1)\` +- mcdc-$2.jar + - MD5: \`$(md5sum "plugins/mcdc-$2.jar" | cut -d ' ' -f1)\` + - SHA1: \`$(sha1sum "plugins/mcdc-$2.jar" | cut -d ' ' -f1)\` + - SHA256: \`$(sha256sum "plugins/mcdc-$2.jar" | cut -d ' ' -f1)\` + - SHA512: \`$(sha512sum "plugins/mcdc-$2.jar" | cut -d ' ' -f1)\` + +
+EOF + if [ -z "$EDITOR" ] + then + nano "ReleaseMessage.md" + else + "$EDITOR" "ReleaseMessage.md" + fi + echo "Done!" +) + +gh release view "$2" +echo ":: Uploading assets to GitHub" +gh release upload "v$2" "/tmp/package/plugins/mcdc/advancements.json" "/tmp/package/plugins/mcdc/config.yml" "/tmp/package/plugins/mcdc/LICENSE" "/tmp/package/plugins/mcdc-$2.jar" "/tmp/package/mcdc-0.12.0-beta-package.tar.gz" "/tmp/package/mcdc-0.12.0-beta-package.zip" +echo "Printing final Release Message:" +cat "/tmp/package/ReleaseMessage.md" From dd3fc100e60c9137aa6e0dd369ff8837142fa91b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 27 Jan 2022 03:23:04 +0000 Subject: [PATCH 144/158] Maven(deps): Bump javacord from 3.3.2 to 3.4.0 Bumps [javacord](https://github.com/Javacord/Javacord) from 3.3.2 to 3.4.0. - [Release notes](https://github.com/Javacord/Javacord/releases) - [Commits](https://github.com/Javacord/Javacord/compare/v3.3.2...v3.4.0) --- updated-dependencies: - dependency-name: org.javacord:javacord dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d67f4f1..061f76c 100644 --- a/pom.xml +++ b/pom.xml @@ -88,7 +88,7 @@ org.javacord javacord - 3.3.2 + 3.4.0 pom From 1445f01040beb6151b441166712a183e3135ea49 Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 8 Feb 2022 16:57:28 +0100 Subject: [PATCH 145/158] =?UTF-8?q?=F0=9F=86=99=20Updated=20deprecated=20m?= =?UTF-8?q?ethods=20to=20non-deprecated=20ones?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- .../com/github/mafelp/discord/DiscordMain.java | 16 ++++++++-------- .../MessageComponentCreationListener.java | 9 ++++----- .../discord/commands/CreateChannelListener.java | 6 +++--- .../discord/commands/CreateRoleListener.java | 6 +++--- .../mafelp/discord/commands/LinkListener.java | 2 +- .../commands/MainSlashCommandListener.java | 6 +++--- .../mafelp/discord/commands/SetupListener.java | 4 ++-- 7 files changed, 24 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index 523a07e..a7faa4a 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -151,7 +151,7 @@ private void registerSlashCommands() { // Link command accountSlashCommands.add(SlashCommand.with("link", "A command to link your discord and minecraft accounts", Collections.singletonList( - SlashCommandOption.create(SlashCommandOptionType.INTEGER, "token", "The token used to link your accounts", false) + SlashCommandOption.create(SlashCommandOptionType.LONG, "token", "The token used to link your accounts", false) ) ).setDefaultPermission(true)); @@ -205,13 +205,13 @@ private void registerSlashCommands() { i++; } } - discordApi.bulkOverwriteGlobalSlashCommands(accountSlashCommands).thenAccept(slashCommands -> + discordApi.bulkOverwriteGlobalApplicationCommands(accountSlashCommands).thenAccept(slashCommands -> slashCommands.forEach(slashCommand -> { Logging.info("Added global slash command \"/" + slashCommand.getName() + "\""); Logging.debug("Default-Permission for \"/" + slashCommand.getName() + "\": " + slashCommand.getDefaultPermission()); })); for (Server server : discordApi.getServers()) { - discordApi.bulkOverwriteServerSlashCommands(server, adminSlashCommands).thenAccept(slashCommands -> { + discordApi.bulkOverwriteServerApplicationCommands(server, adminSlashCommands).thenAccept(slashCommands -> { // Setup a list with all allowed Users, configured in the config file and the bot owner var allowedUserIDs = Settings.getConfiguration().getLongList("permission.discordServerAdmin.allowedUserIDs"); allowedUserIDs = Settings.getConfiguration().getLongList("permission.discordBotAdmin.allowedUserIDs"); @@ -220,8 +220,8 @@ private void registerSlashCommands() { allowedUserIDs.add(discordApi.getOwnerId()); // Register the slash commands for each server - List updatedSlashCommands = new ArrayList<>(); - List permissions = new ArrayList<>(); + List updatedSlashCommands = new ArrayList<>(); + List permissions = new ArrayList<>(); Logging.debug("Updating admin slash command permission for server " + server.getName()); // Check if the server owner of this server is in the allowed lists. // If not, add them only for this server and remove them afterwards. @@ -230,12 +230,12 @@ private void registerSlashCommands() { allowedUserIDs.add(server.getOwnerId()); // Create permission to use this slash command for each allowed user - allowedUserIDs.forEach(userID -> permissions.add(SlashCommandPermissions.create(userID, SlashCommandPermissionType.USER, true))); + allowedUserIDs.forEach(userID -> permissions.add(ApplicationCommandPermissions.create(userID, ApplicationCommandPermissionType.USER, true))); // Prepare the commands to have the new permissions: Allow all allowed users to use this slash command. - slashCommands.forEach(slashCommand -> updatedSlashCommands.add(new ServerSlashCommandPermissionsBuilder(slashCommand.getId(), permissions))); + slashCommands.forEach(slashCommand -> updatedSlashCommands.add(new ServerApplicationCommandPermissionsBuilder(slashCommand.getId(), permissions))); // Do the actual updates - discordApi.batchUpdateSlashCommandPermissions(server, updatedSlashCommands).thenAccept(serverSlashCommandPermissions -> + discordApi.batchUpdateApplicationCommandPermissions(server, updatedSlashCommands).thenAccept(serverSlashCommandPermissions -> Logging.info("Updated admin slash command permissions for server " + server.getName())); if (!serverOwnerIsAllowed) diff --git a/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java b/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java index 946b6bf..a1d4dc3 100644 --- a/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java +++ b/src/main/java/com/github/mafelp/discord/MessageComponentCreationListener.java @@ -25,11 +25,10 @@ public void onComponentCreate(MessageComponentCreateEvent event) { private static void helpSelectMenu(MessageComponentInteraction interaction) { if (interaction.asSelectMenuInteraction().isEmpty()) return; - interaction.getMessage().ifPresent(message -> { - if (message.canYouDelete()) - message.delete("Message no longer needed, as the help command continues.").thenAccept(none -> - Logging.debug("Removed original help message.")); - }); + if (interaction.getMessage().canYouDelete()) { + interaction.getMessage().delete("Message no longer needed, as the help command continues.").thenAccept(none -> + Logging.debug("Removed original help message.")); + } InteractionImmediateResponseBuilder message = interaction.createImmediateResponder() .append("Your requested help page(s):") diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java index 77f781a..d1ab5e2 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateChannelListener.java @@ -65,15 +65,15 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { ; // Checks if the first argument after the first argument exists. - if (event.getSlashCommandInteraction().getFirstOption().isEmpty() || - event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().isEmpty()) { + if (event.getSlashCommandInteraction().getOptionByIndex(0).isEmpty() || + event.getSlashCommandInteraction().getOptionByIndex(1).isEmpty()) { Logging.info("User \"" + author.getName() + "\" tried to execute command \"createChannel\"!"); event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } // Gets the first argument after the first argument and then gets the it as a string - var secondOption = event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().get(); + var secondOption = event.getSlashCommandInteraction().getOptionByIndex(1).get(); String name = secondOption.getStringValue().get(); if (secondOption.getStringValue().isEmpty()) { diff --git a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java index 01ed743..06e04fc 100644 --- a/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/CreateRoleListener.java @@ -80,15 +80,15 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { } // Checks if the first argument after the first argument exists. - if (event.getSlashCommandInteraction().getFirstOption().isEmpty() || - event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().isEmpty()) { + if (event.getSlashCommandInteraction().getOptionByIndex(0).isEmpty() || + event.getSlashCommandInteraction().getOptionByIndex(1).isEmpty()) { Logging.info("User \"" + author.getName() + "\" tried to execute command \"create role\"!"); event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } // Gets the first argument after the first argument and then gets the it as a string - var secondOption = event.getSlashCommandInteraction().getFirstOption().get().getFirstOption().get(); + var secondOption = event.getSlashCommandInteraction().getOptionByIndex(1).get(); String name = secondOption.getStringValue().get(); if (secondOption.getStringValue().isEmpty()) { diff --git a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java index eb663c6..d583446 100644 --- a/src/main/java/com/github/mafelp/discord/commands/LinkListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/LinkListener.java @@ -52,7 +52,7 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { return; } - int token = event.getSlashCommandInteraction().getFirstOptionIntValue().orElse(-1); + int token = event.getSlashCommandInteraction().getOptionLongValueByIndex(0).orElse(-1L).intValue(); // Checks if a number is given as the first argument. If not, send the user a new Link token. if (token == -1) { diff --git a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java index 7606ed0..646742a 100644 --- a/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/MainSlashCommandListener.java @@ -23,11 +23,11 @@ public void onSlashCommandCreate(SlashCommandCreateEvent slashCommandCreateEvent case "unlink" -> UnlinkListener.onSlashCommand(slashCommandCreateEvent); case "whisper", "mcmsg" -> WhisperListener.onSlashCommand(slashCommandCreateEvent); case "create" -> { - if (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().isPresent()) { - switch (slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().get().getName()) { + if (slashCommandCreateEvent.getSlashCommandInteraction().getOptionByIndex(0).isPresent()) { + switch (slashCommandCreateEvent.getSlashCommandInteraction().getOptionByIndex(0).get().getName()) { case "channel" -> CreateChannelListener.onSlashCommand(slashCommandCreateEvent); case "role" -> CreateRoleListener.onSlashCommand(slashCommandCreateEvent); - default -> Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": First option is: " + slashCommandCreateEvent.getSlashCommandInteraction().getFirstOption().get().getName()); + default -> Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": First option is: " + slashCommandCreateEvent.getSlashCommandInteraction().getOptionByIndex(0).get().getName()); } } else { Logging.info(ChatColor.RED + "Error in SlashCommand \"create\": no First option given!"); diff --git a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java index e63b962..930b5e7 100644 --- a/src/main/java/com/github/mafelp/discord/commands/SetupListener.java +++ b/src/main/java/com/github/mafelp/discord/commands/SetupListener.java @@ -92,13 +92,13 @@ public static void onSlashCommand(SlashCommandCreateEvent event) { } // If the first argument is empty, send the help message and exit. - if (event.getSlashCommandInteraction().getFirstOptionStringValue().isEmpty()) { + if (event.getSlashCommandInteraction().getOptionByIndex(0).isEmpty()) { info("Person " + ChatColor.GRAY + author.getName() + ChatColor.RESET + " used the command setup wrong. Sending help embed."); event.getSlashCommandInteraction().createImmediateResponder().addEmbed(helpMessage).respond(); return; } - String name = event.getSlashCommandInteraction().getFirstOptionStringValue().get(); + String name = event.getSlashCommandInteraction().getOptionStringValueByIndex(0).orElse(""); // try to create the role. try { From bcd9c259887db9cf3cf94bbbc03d3a268c2a85bc Mon Sep 17 00:00:00 2001 From: MaFeLP <60669873+MaFeLP@users.noreply.github.com> Date: Tue, 8 Feb 2022 18:44:05 +0100 Subject: [PATCH 146/158] =?UTF-8?q?=E2=9E=95=20Added=20account=20slash=20c?= =?UTF-8?q?ommand=20to=20discord?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: MaFeLP <60669873+MaFeLP@users.noreply.github.com> --- .../github/mafelp/discord/DiscordMain.java | 22 + .../discord/commands/AccountListener.java | 387 ++++++++++++++++++ .../mafelp/discord/commands/LinkListener.java | 38 +- .../commands/MainSlashCommandListener.java | 2 +- .../discord/commands/UnlinkListener.java | 12 +- .../minecraft/commands/AccountCommand.java | 9 +- 6 files changed, 438 insertions(+), 32 deletions(-) create mode 100644 src/main/java/com/github/mafelp/discord/commands/AccountListener.java diff --git a/src/main/java/com/github/mafelp/discord/DiscordMain.java b/src/main/java/com/github/mafelp/discord/DiscordMain.java index a7faa4a..eb3d97d 100644 --- a/src/main/java/com/github/mafelp/discord/DiscordMain.java +++ b/src/main/java/com/github/mafelp/discord/DiscordMain.java @@ -148,6 +148,28 @@ private void registerSlashCommands() { .setDefaultPermission(true) ); + // Account command + accountSlashCommands.add(SlashCommand.with("account", "A command for account management", + Arrays.asList( + SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "link", "Link your discord and minecraft accounts", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.LONG, "token", "The OPTIONAL token to link your accounts", false) + )), + SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "name", "Change or get your username for the accounts", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.STRING, "change to", "The string to change your name to. Leave blank to get current name.", false) + )), + SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "username", "Change or get your username for the accounts", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.STRING, "change to", "The string to change your name to. Leave blank to get current name.", false) + )), + SlashCommandOption.createWithOptions(SlashCommandOptionType.SUB_COMMAND, "get", "Gets information about an account", + Collections.singletonList( + SlashCommandOption.create(SlashCommandOptionType.USER, "account", "Get information about this user. Leave blank to get yourself.", false) + )), + SlashCommandOption.create(SlashCommandOptionType.SUB_COMMAND, "list", "List all currently linked accounts"), + SlashCommandOption.create(SlashCommandOptionType.SUB_COMMAND, "unlink", "Unlink your discord account from your minecraft account.") + ))); // Link command accountSlashCommands.add(SlashCommand.with("link", "A command to link your discord and minecraft accounts", Collections.singletonList( diff --git a/src/main/java/com/github/mafelp/discord/commands/AccountListener.java b/src/main/java/com/github/mafelp/discord/commands/AccountListener.java new file mode 100644 index 0000000..fe55aca --- /dev/null +++ b/src/main/java/com/github/mafelp/discord/commands/AccountListener.java @@ -0,0 +1,387 @@ +package com.github.mafelp.discord.commands; + +import com.github.mafelp.accounts.Account; +import com.github.mafelp.accounts.AccountManager; +import com.github.mafelp.utils.CheckPermission; +import com.github.mafelp.utils.Logging; +import com.github.mafelp.utils.Permissions; +import com.github.mafelp.utils.Settings; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.javacord.api.entity.message.embed.EmbedBuilder; +import org.javacord.api.entity.user.User; +import org.javacord.api.interaction.SlashCommandInteraction; +import org.javacord.api.interaction.SlashCommandInteractionOption; +import org.javacord.api.interaction.callback.InteractionOriginalResponseUpdater; +import org.jetbrains.annotations.NotNull; + +import java.awt.*; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.List; +import java.util.*; + +/** + * The class that listens to the discord chats, if the channel creation command is executed. - + * As discord announced just today, there will be an update to the bot API, that'll be adding + * slash command support. This class will be moved, if the update is available in this API. + */ +public class AccountListener { + /** + * The method called by the discord API, for every chat message. - + * This method will filter them and execute commands accordingly. + * @param event The event containing information about the message. + */ + public static void onSlashCommand(SlashCommandInteraction event) { + User author = event.getUser(); + // help message for wrong usage + EmbedBuilder helpMessage = new EmbedBuilder() + .setAuthor(author) + .setTitle("Error") + .addField("Usage", "/account (