Discord Module (#3844)

Co-authored-by: MD <1917406+mdcfe@users.noreply.github.com>
Co-authored-by: pop4959 <pop4959@gmail.com>
Co-authored-by: Riley Park <riley.park@meino.net>
Co-authored-by: Jason <11360596+jpenilla@users.noreply.github.com>
1.17
Josh Roy 2 years ago committed by GitHub
parent 9d3bf337e1
commit 0861427bf3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -3,5 +3,5 @@
<suppressions>
<suppress files=".*[\\/]test[\\/]java[\\/].*" checks="RequireExplicitVisibilityModifier"/>
<!-- TODO: don't suppress I-prefixed API interfaces under com.earth2me.essentials -->
<suppress files="(com[\\/]earth2me[\\/]essentials[\\/]|net[\\/]ess3[\\/])(?:[^\\/]+$|(?!api)[^\\/]+[\\/])" checks="MissingJavadoc(Method|Type)"/>
<suppress files="(com[\\/]earth2me[\\/]essentials[\\/]|net[\\/]ess3[\\/]|net[\\/]essentialsx[\\/])(?:[^\\/]+$|(?!api)[^\\/]+[\\/])" checks="MissingJavadoc(Method|Type)"/>
</suppressions>

@ -58,6 +58,7 @@ jobs:
mv Essentials/build/docs/javadoc/ javadocs/
cp -r EssentialsAntiBuild/build/docs/javadoc/ javadocs/EssentialsAntiBuild/
cp -r EssentialsChat/build/docs/javadoc/ javadocs/EssentialsChat/
cp -r EssentialsDiscord/build/docs/javadoc/ javadocs/EssentialsDiscord/
cp -r EssentialsGeoIP/build/docs/javadoc/ javadocs/EssentialsGeoIP/
cp -r EssentialsProtect/build/docs/javadoc/ javadocs/EssentialsProtect/
cp -r EssentialsSpawn/build/docs/javadoc/ javadocs/EssentialsSpawn/

@ -21,6 +21,7 @@ import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.commands.PlayerNotFoundException;
import com.earth2me.essentials.commands.QuietAbortException;
import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.economy.vault.VaultEconomyProvider;
@ -38,6 +39,7 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.updatecheck.UpdateChecker;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.VersionUtil;
import io.papermc.lib.PaperLib;
import net.ess3.api.Economy;
@ -118,6 +120,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -895,6 +898,94 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
return user;
}
@Override
public User matchUser(final Server server, final User sourceUser, final String searchTerm, final Boolean getHidden, final boolean getOffline) throws PlayerNotFoundException {
final User user;
Player exPlayer;
try {
exPlayer = server.getPlayer(UUID.fromString(searchTerm));
} catch (final IllegalArgumentException ex) {
if (getOffline) {
exPlayer = server.getPlayerExact(searchTerm);
} else {
exPlayer = server.getPlayer(searchTerm);
}
}
if (exPlayer != null) {
user = getUser(exPlayer);
} else {
user = getUser(searchTerm);
}
if (user != null) {
if (!getOffline && !user.getBase().isOnline()) {
throw new PlayerNotFoundException();
}
if (getHidden || canInteractWith(sourceUser, user)) {
return user;
} else { // not looking for hidden and cannot interact (i.e is hidden)
if (getOffline && user.getName().equalsIgnoreCase(searchTerm)) { // if looking for offline and got an exact match
return user;
}
}
throw new PlayerNotFoundException();
}
final List<Player> matches = server.matchPlayer(searchTerm);
if (matches.isEmpty()) {
final String matchText = searchTerm.toLowerCase(Locale.ENGLISH);
for (final User userMatch : getOnlineUsers()) {
if (getHidden || canInteractWith(sourceUser, userMatch)) {
final String displayName = FormatUtil.stripFormat(userMatch.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (displayName.contains(matchText)) {
return userMatch;
}
}
}
} else {
for (final Player player : matches) {
final User userMatch = getUser(player);
if (userMatch.getDisplayName().startsWith(searchTerm) && (getHidden || canInteractWith(sourceUser, userMatch))) {
return userMatch;
}
}
final User userMatch = getUser(matches.get(0));
if (getHidden || canInteractWith(sourceUser, userMatch)) {
return userMatch;
}
}
throw new PlayerNotFoundException();
}
@Override
public boolean canInteractWith(final CommandSource interactor, final User interactee) {
if (interactor == null) {
return !interactee.isHidden();
}
if (interactor.isPlayer()) {
return canInteractWith(getUser(interactor.getPlayer()), interactee);
}
return true; // console
}
@Override
public boolean canInteractWith(final User interactor, final User interactee) {
if (interactor == null) {
return !interactee.isHidden();
}
if (interactor.equals(interactee)) {
return true;
}
return interactor.getBase().canSee(interactee.getBase());
}
//This will create a new user if there is not a match.
@Override
public User getUser(final Player base) {

@ -310,8 +310,6 @@ public class EssentialsPlayerListener implements Listener {
user.setDisplayNick();
updateCompass(user);
ess.runTaskAsynchronously(() -> ess.getServer().getPluginManager().callEvent(new AsyncUserDataLoadEvent(user)));
if (!ess.getVanishedPlayersNew().isEmpty() && !user.isAuthorized("essentials.vanish.see")) {
for (final String p : ess.getVanishedPlayersNew()) {
final Player toVanish = ess.getServer().getPlayerExact(p);
@ -328,12 +326,14 @@ public class EssentialsPlayerListener implements Listener {
user.getBase().setSleepingIgnored(true);
}
final String effectiveMessage;
if (ess.getSettings().allowSilentJoinQuit() && (user.isAuthorized("essentials.silentjoin") || user.isAuthorized("essentials.silentjoin.vanish"))) {
if (user.isAuthorized("essentials.silentjoin.vanish")) {
user.setVanished(true);
}
effectiveMessage = null;
} else if (message == null || hideJoinQuitMessages()) {
//NOOP
effectiveMessage = null;
} else if (ess.getSettings().isCustomJoinMessage()) {
final String msg = ess.getSettings().getCustomJoinMessage()
.replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName())
@ -345,10 +345,16 @@ public class EssentialsPlayerListener implements Listener {
if (!msg.isEmpty()) {
ess.getServer().broadcastMessage(msg);
}
effectiveMessage = msg.isEmpty() ? null : msg;
} else if (ess.getSettings().allowSilentJoinQuit()) {
ess.getServer().broadcastMessage(message);
effectiveMessage = message;
} else {
effectiveMessage = message;
}
ess.runTaskAsynchronously(() -> ess.getServer().getPluginManager().callEvent(new AsyncUserDataLoadEvent(user, effectiveMessage)));
final int motdDelay = ess.getSettings().getMotdDelay() / 50;
final DelayMotdTask motdTask = new DelayMotdTask(user);
if (motdDelay > 0) {

@ -4,6 +4,7 @@ import com.earth2me.essentials.api.IItemDb;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.api.IWarps;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.PlayerNotFoundException;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.updatecheck.UpdateChecker;
import net.ess3.provider.ContainerProvider;
@ -17,6 +18,7 @@ import net.ess3.provider.SpawnerBlockProvider;
import net.ess3.provider.SpawnerItemProvider;
import net.ess3.provider.SyncCommandsProvider;
import net.essentialsx.api.v2.services.BalanceTop;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@ -52,6 +54,12 @@ public interface IEssentials extends Plugin {
User getUser(Player base);
User matchUser(Server server, User sourceUser, String searchTerm, Boolean getHidden, boolean getOffline) throws PlayerNotFoundException;
boolean canInteractWith(CommandSource interactor, User interactee);
boolean canInteractWith(User interactor, User interactee);
I18n getI18n();
User getOfflineUser(String name);

@ -1,10 +1,12 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@ -127,4 +129,88 @@ public final class PlayerList {
return tl("listGroupTag", FormatUtil.replaceFormat(group)) +
message;
}
public static List<String> prepareGroupedList(final IEssentials ess, final String commandLabel, final Map<String, List<User>> playerList) {
final List<String> output = new ArrayList<>();
final Set<String> configGroups = ess.getSettings().getListGroupConfig().keySet();
final List<String> asterisk = new ArrayList<>();
// Loop through the custom defined groups and display them
for (final String oConfigGroup : configGroups) {
final String groupValue = ess.getSettings().getListGroupConfig().get(oConfigGroup).toString().trim();
final String configGroup = oConfigGroup.toLowerCase();
// If the group value is an asterisk, then skip it, and handle it later
if (groupValue.equals("*")) {
asterisk.add(oConfigGroup);
continue;
}
// If the group value is hidden, we don't need to display it
if (groupValue.equalsIgnoreCase("hidden")) {
playerList.remove(configGroup);
continue;
}
final List<User> outputUserList;
final List<User> matchedList = playerList.get(configGroup);
// If the group value is an int, then we might need to truncate it
if (NumberUtil.isInt(groupValue)) {
if (matchedList != null && !matchedList.isEmpty()) {
playerList.remove(configGroup);
outputUserList = new ArrayList<>(matchedList);
final int limit = Integer.parseInt(groupValue);
if (matchedList.size() > limit) {
output.add(outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup))));
} else {
output.add(outputFormat(oConfigGroup, listUsers(ess, outputUserList, ", ")));
}
continue;
}
}
outputUserList = getMergedList(ess, playerList, configGroup);
// If we have no users, than we don't need to continue parsing this group
if (outputUserList.isEmpty()) {
continue;
}
output.add(outputFormat(oConfigGroup, listUsers(ess, outputUserList, ", ")));
}
final Set<String> var = playerList.keySet();
String[] onlineGroups = var.toArray(new String[0]);
Arrays.sort(onlineGroups, String.CASE_INSENSITIVE_ORDER);
// If we have an asterisk group, then merge all remaining groups
if (!asterisk.isEmpty()) {
final List<User> asteriskUsers = new ArrayList<>();
for (final String onlineGroup : onlineGroups) {
asteriskUsers.addAll(playerList.get(onlineGroup));
}
for (final String key : asterisk) {
playerList.put(key, asteriskUsers);
}
onlineGroups = asterisk.toArray(new String[0]);
}
// If we have any groups remaining after the custom groups loop through and display them
for (final String onlineGroup : onlineGroups) {
final List<User> users = playerList.get(onlineGroup);
String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup;
if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) {
groupName = tl("connectedPlayers");
}
if (users == null || users.isEmpty()) {
continue;
}
output.add(outputFormat(groupName, listUsers(ess, users, ", ")));
}
return output;
}
}

@ -115,7 +115,11 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public boolean isPermissionSet(final String node) {
return isPermSetCheck(node);
final boolean result = isPermSetCheck(node);
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " (set-explicit) - " + result);
}
return result;
}
/**

@ -58,11 +58,13 @@ public class Commandessentials extends EssentialsCommand {
"UltraPermissions",
"PermissionsEx", // permissions (unsupported)
"GroupManager", // permissions (unsupported)
"bPermissions" // permissions (unsupported)
"bPermissions", // permissions (unsupported)
"DiscordSRV" // potential for issues if EssentialsXDiscord is installed
);
private static final List<String> officialPlugins = Arrays.asList(
"EssentialsAntiBuild",
"EssentialsChat",
"EssentialsDiscord",
"EssentialsGeoIP",
"EssentialsProtect",
"EssentialsSpawn",

@ -3,18 +3,12 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.PlayerList;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Server;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
public class Commandlist extends EssentialsCommand {
public Commandlist() {
@ -41,83 +35,8 @@ public class Commandlist extends EssentialsCommand {
// Output the standard /list output, when no group is specified
private void sendGroupedList(final CommandSource sender, final String commandLabel, final Map<String, List<User>> playerList) {
final Set<String> configGroups = ess.getSettings().getListGroupConfig().keySet();
final List<String> asterisk = new ArrayList<>();
// Loop through the custom defined groups and display them
for (final String oConfigGroup : configGroups) {
final String groupValue = ess.getSettings().getListGroupConfig().get(oConfigGroup).toString().trim();
final String configGroup = oConfigGroup.toLowerCase();
// If the group value is an asterisk, then skip it, and handle it later
if (groupValue.equals("*")) {
asterisk.add(oConfigGroup);
continue;
}
// If the group value is hidden, we don't need to display it
if (groupValue.equalsIgnoreCase("hidden")) {
playerList.remove(configGroup);
continue;
}
final List<User> outputUserList;
final List<User> matchedList = playerList.get(configGroup);
// If the group value is an int, then we might need to truncate it
if (NumberUtil.isInt(groupValue)) {
if (matchedList != null && !matchedList.isEmpty()) {
playerList.remove(configGroup);
outputUserList = new ArrayList<>(matchedList);
final int limit = Integer.parseInt(groupValue);
if (matchedList.size() > limit) {
sender.sendMessage(PlayerList.outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup))));
} else {
sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", ")));
}
continue;
}
}
outputUserList = PlayerList.getMergedList(ess, playerList, configGroup);
// If we have no users, than we don't need to continue parsing this group
if (outputUserList.isEmpty()) {
continue;
}
sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", ")));
}
final Set<String> var = playerList.keySet();
String[] onlineGroups = var.toArray(new String[0]);
Arrays.sort(onlineGroups, String.CASE_INSENSITIVE_ORDER);
// If we have an asterisk group, then merge all remaining groups
if (!asterisk.isEmpty()) {
final List<User> asteriskUsers = new ArrayList<>();
for (final String onlineGroup : onlineGroups) {
asteriskUsers.addAll(playerList.get(onlineGroup));
}
for (final String key : asterisk) {
playerList.put(key, asteriskUsers);
}
onlineGroups = asterisk.toArray(new String[0]);
}
// If we have any groups remaining after the custom groups loop through and display them
for (final String onlineGroup : onlineGroups) {
final List<User> users = playerList.get(onlineGroup);
String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup;
if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) {
groupName = tl("connectedPlayers");
}
if (users == null || users.isEmpty()) {
continue;
}
sender.sendMessage(PlayerList.outputFormat(groupName, PlayerList.listUsers(ess, users, ", ")));
for (final String str : PlayerList.prepareGroupedList(ess, commandLabel, playerList)) {
sender.sendMessage(str);
}
}

@ -4,7 +4,6 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.IEssentialsModule;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@ -14,7 +13,6 @@ import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginIdentifiableCommand;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.StringUtil;
@ -23,10 +21,8 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -94,16 +90,8 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
return bldr.toString();
}
private static boolean canInteractWith(final User interactor, final User interactee) {
if (interactor == null) {
return !interactee.isHidden();
}
if (interactor.equals(interactee)) {
return true;
}
return interactor.getBase().canSee(interactee.getBase());
private boolean canInteractWith(final User interactor, final User interactee) {
return ess.canInteractWith(interactor, interactee);
}
@Override
@ -165,64 +153,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
}
private User getPlayer(final Server server, final User sourceUser, final String searchTerm, final boolean getHidden, final boolean getOffline) throws PlayerNotFoundException {
final User user;
Player exPlayer;
try {
exPlayer = server.getPlayer(UUID.fromString(searchTerm));
} catch (final IllegalArgumentException ex) {
if (getOffline) {
exPlayer = server.getPlayerExact(searchTerm);
} else {
exPlayer = server.getPlayer(searchTerm);
}
}
if (exPlayer != null) {
user = ess.getUser(exPlayer);
} else {
user = ess.getUser(searchTerm);
}
if (user != null) {
if (!getOffline && !user.getBase().isOnline()) {
throw new PlayerNotFoundException();
}
if (getHidden || canInteractWith(sourceUser, user)) {
return user;
} else { // not looking for hidden and cannot interact (i.e is hidden)
if (getOffline && user.getName().equalsIgnoreCase(searchTerm)) { // if looking for offline and got an exact match
return user;
}
}
throw new PlayerNotFoundException();
}
final List<Player> matches = server.matchPlayer(searchTerm);
if (matches.isEmpty()) {
final String matchText = searchTerm.toLowerCase(Locale.ENGLISH);
for (final User userMatch : ess.getOnlineUsers()) {
if (getHidden || canInteractWith(sourceUser, userMatch)) {
final String displayName = FormatUtil.stripFormat(userMatch.getDisplayName()).toLowerCase(Locale.ENGLISH);
if (displayName.contains(matchText)) {
return userMatch;
}
}
}
} else {
for (final Player player : matches) {
final User userMatch = ess.getUser(player);
if (userMatch.getDisplayName().startsWith(searchTerm) && (getHidden || canInteractWith(sourceUser, userMatch))) {
return userMatch;
}
}
final User userMatch = ess.getUser(matches.get(0));
if (getHidden || canInteractWith(sourceUser, userMatch)) {
return userMatch;
}
}
throw new PlayerNotFoundException();
return ess.matchUser(server, sourceUser, searchTerm, getHidden, getOffline);
}
@Override
@ -284,15 +215,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
}
boolean canInteractWith(final CommandSource interactor, final User interactee) {
if (interactor == null) {
return !interactee.isHidden();
}
if (interactor.isPlayer()) {
return canInteractWith(ess.getUser(interactor.getPlayer()), interactee);
}
return true; // console
return ess.canInteractWith(interactor, interactee);
}
/**

@ -45,6 +45,13 @@ public final class ConfigurateUtil {
return map;
}
public static Map<String, Object> getRawMap(final EssentialsConfiguration config, final String key) {
if (config == null || key == null) {
return Collections.emptyMap();
}
return getRawMap(config.getSection(key));
}
public static Map<String, Object> getRawMap(final CommentedConfigurationNode node) {
if (node == null || !node.isMap()) {
return Collections.emptyMap();

@ -0,0 +1,142 @@
package com.earth2me.essentials.utils;
/**
* Most of this code was "borrowed" from KyoriPowered/Adventure and is subject to their MIT license;
*
* MIT License
*
* Copyright (c) 2017-2020 KyoriPowered
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
public final class DownsampleUtil {
private final static NamedTextColor[] VALUES = new NamedTextColor[] {new NamedTextColor("0", 0x000000), new NamedTextColor("1", 0x0000aa), new NamedTextColor("2", 0x00aa00), new NamedTextColor("3", 0x00aaaa), new NamedTextColor("4", 0xaa0000), new NamedTextColor("5", 0xaa00aa), new NamedTextColor("6", 0xffaa00), new NamedTextColor("7", 0xaaaaaa), new NamedTextColor("8", 0x555555), new NamedTextColor("9", 0x5555ff), new NamedTextColor("a", 0x55ff55), new NamedTextColor("b", 0x55ffff), new NamedTextColor("c", 0xff5555), new NamedTextColor("d", 0xff55ff), new NamedTextColor("e", 0xffff55), new NamedTextColor("f", 0xffffff)};
private DownsampleUtil() {
}
public static String nearestTo(final int rgb) {
final HSVLike any = HSVLike.fromRGB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff);
float matchedDistance = Float.MAX_VALUE;
NamedTextColor match = VALUES[0];
for (final NamedTextColor potential : VALUES) {
final float distance = distance(any, potential.hsv);
if (distance < matchedDistance) {
match = potential;
matchedDistance = distance;
}
if (distance == 0) {
break;
}
}
return match.code;
}
private static float distance(final HSVLike self, final HSVLike other) {
final float hueDistance = 3 * Math.abs(self.h() - other.h());
final float saturationDiff = self.s() - other.s();
final float valueDiff = self.v() - other.v();
return hueDistance * hueDistance + saturationDiff * saturationDiff + valueDiff * valueDiff;
}
private static final class NamedTextColor {
private final String code;
private final int value;
private final HSVLike hsv;
private NamedTextColor(final String code, final int value) {
this.code = code;
this.value = value;
this.hsv = HSVLike.fromRGB(this.red(), this.green(), this.blue());
}
private int red() {
return (value >> 16) & 0xff;
}
private int green() {
return (value >> 8) & 0xff;
}
private int blue() {
return value & 0xff;
}
}
private static final class HSVLike {
private final float h;
private final float s;
private final float v;
private HSVLike(float h, float s, float v) {
this.h = h;
this.s = s;
this.v = v;
}
public float h() {
return this.h;
}
public float s() {
return this.s;
}
public float v() {
return this.v;
}
static HSVLike fromRGB(final int red, final int green, final int blue) {
final float r = red / 255.0f;
final float g = green / 255.0f;
final float b = blue / 255.0f;
final float min = Math.min(r, Math.min(g, b));
final float max = Math.max(r, Math.max(g, b)); // v
final float delta = max - min;
final float s;
if(max != 0) {
s = delta / max; // s
} else {
// r = g = b = 0
s = 0;
}
if(s == 0) { // s = 0, h is undefined
return new HSVLike(0, s, max);
}
float h;
if(r == max) {
h = (g - b) / delta; // between yellow & magenta
} else if(g == max) {
h = 2 + (b - r) / delta; // between cyan & yellow
} else {
h = 4 + (r - g) / delta; // between magenta & cyan
}
h *= 60; // degrees
if(h < 0) {
h += 360;
}
return new HSVLike(h / 360.0f, s, max);
}
}
}

@ -25,6 +25,8 @@ public final class FormatUtil {
//Used to prepare xmpp output
private static final Pattern LOGCOLOR_PATTERN = Pattern.compile("\\x1B\\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]");
private static final Pattern URL_PATTERN = Pattern.compile("((?:(?:https?)://)?[\\w-_\\.]{2,})\\.([a-zA-Z]{2,3}(?:/\\S+)?)");
//Used to strip ANSI control codes from console
private static final Pattern ANSI_CONTROL_PATTERN = Pattern.compile("\u001B(?:\\[0?m|\\[38;2(?:;\\d{1,3}){3}m|\\[([0-9]{1,2}[;m]?){3})");
private FormatUtil() {
}
@ -45,6 +47,13 @@ public final class FormatUtil {
return stripColor(input, REPLACE_ALL_PATTERN);
}
public static String stripAnsi(final String input) {
if (input == null) {
return null;
}
return stripColor(input, ANSI_CONTROL_PATTERN);
}
//This is the general permission sensitive message format function, checks for urls.
public static String formatMessage(final IUser user, final String permBase, final String input) {
if (input == null) {

@ -83,6 +83,10 @@ public final class VersionUtil {
private VersionUtil() {
}
public static boolean isPaper() {
return PaperLib.isPaper();
}
public static BukkitVersion getServerBukkitVersion() {
if (serverVersion == null) {
serverVersion = BukkitVersion.fromString(Bukkit.getServer().getBukkitVersion());

@ -12,16 +12,28 @@ public class AsyncUserDataLoadEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final IUser user;
private final String joinMessage;
public AsyncUserDataLoadEvent(IUser user) {
public AsyncUserDataLoadEvent(IUser user, String joinMessage) {
super(true);
this.user = user;
this.joinMessage = joinMessage;
}
/**
* @return The user whose data has been loaded.
*/
public IUser getUser() {
return user;
}
/**
* @return The join message of this user who joined or null if none was displayed.
*/
public String getJoinMessage() {
return joinMessage;
}
@Override
public HandlerList getHandlers() {
return handlers;

@ -232,6 +232,27 @@ destinationNotSet=Destination not set\!
disabled=disabled
disabledToSpawnMob=\u00a74Spawning this mob was disabled in the config file.
disableUnlimited=\u00a76Disabled unlimited placing of\u00a7c {0} \u00a76for\u00a7c {1}\u00a76.
discordCommandExecuteDescription=Executes a console command on the Minecraft server.
discordCommandExecuteArgumentCommand=The command to be executed
discordCommandExecuteReply=Executing command: "/{0}"
discordCommandListDescription=Gets a list of online players.
discordCommandListArgumentGroup=A specific group to limit your search by
discordCommandMessageDescription=Messages a player on the Minecraft server.
discordCommandMessageArgumentUsername=The player to send the message to
discordCommandMessageArgumentMessage=The message to send to the player
discordErrorCommand=You added your bot to your server incorrectly. Please follow the tutorial in the config and add your bot using https://essentialsx.net/discord.html!
discordErrorCommandDisabled=That command is disabled!
discordErrorLogin=An error occurred while logging into Discord, which has caused the plugin to disable itself: \n{0}
discordErrorLoggerInvalidChannel=Discord console logging has been disabled due to an invalid channel definition! If you intend to disable it, set the channel ID to "none"; otherwise check that your channel ID is correct.
discordErrorLoggerNoPerms=Discord console logger has been disabled due to insufficient permissions! Please make sure your bot has the "Manage Webhooks" permissions on the server. After fixing that, run "/ess reload".
discordErrorNoGuild=Invalid or missing server ID! Please follow the tutorial in the config in order to setup the plugin.
discordErrorNoGuildSize=Your bot is not in any servers! Please follow the tutorial in the config in order to setup the plugin.
discordErrorNoPerms=Your bot cannot see or talk in any channel! Please make sure your bot has read and write permissions in all channels you wish to use.
discordErrorNoToken=No token provided! Please follow the tutorial in the config in order to setup the plugin.
discordErrorWebhook=An error occurred while sending messages to your console channel\! This was likely caused by accidentally deleting your console webhook. This can usually by fixed by ensuring your bot has the "Manage Webhooks" permission and running "/ess reload".
discordLoggingIn=Attempting to login to Discord...
discordLoggingInDone=Successfully logged in as {0}
discordNoSendPermission=Cannot send message in channel: #{0} Please ensure the bot has "Send Messages" permission in that channel\!
disposal=Disposal
disposalCommandDescription=Opens a portable disposal menu.
disposalCommandUsage=/<command>
@ -950,6 +971,7 @@ repairCommandUsage2Description=Repairs all items in your inventory
repairEnchanted=\u00a74You are not allowed to repair enchanted items.
repairInvalidType=\u00a74This item cannot be repaired.
repairNone=\u00a74There were no items that needed repairing.
replyFromDiscord=**Reply from {0}\:** `{1}`
replyLastRecipientDisabled=\u00a76Replying to last message recipient \u00a7cdisabled\u00a76.
replyLastRecipientDisabledFor=\u00a76Replying to last message recipient \u00a7cdisabled \u00a76for \u00a7c{0}\u00a76.
replyLastRecipientEnabled=\u00a76Replying to last message recipient \u00a7cenabled\u00a76.

@ -0,0 +1,462 @@
# EssentialsX Discord
EssentialsX Discord is a module that brings a simple, lightweight, easy-to-use, and bloat-free
bridge between Discord and Minecraft.
EssentialsX Discord offers *essential* features you'd want from a Discord bridge such as:
* MC Chat -> Discord Channel
* Discord Channel -> MC Chat
* Basic MC -> Discord Event Monitoring (Join/Leave/Death/Mute)
* MC Console -> Discord Relay
* Discord Slash Commands
* /execute - Execute console commands from Discord
* /msg - Message Minecraft players from Discord
* /list - List players currently online on Minecraft
* & more...
---
## Table of Contents
> * [Initial Setup](#initial-setup)
> * [Console Relay](#console-relay)
> * [Configuring Messages](#configuring-messages)
> * [Receive Discord Messages in Minecraft](#receive-discord-messages-in-minecraft)
> * [Discord Commands](#discord-commands)
> * [Misc Permissions](#misc-permissions)
> * [Developer API](#developer-api)
---
## Initial Setup
0. Before starting your server, there are a few steps you have to take. First, you must create a new
Discord bot at [discord.com/developers/applications](https://discord.com/developers/applications/).
1. Once on that page, click on "New Application" button on the top right, give your bot a name, and
then click "Create".
> ![Creating Application](https://i.imgur.com/8ffp4R1.gif)
> `New Application` -> Give Application a Name -> `Create`
2. Once you create the application, you'll be directed to its overview. From this screen, you'll
need to copy your "Client ID"/"Application ID" and save it for a later step. To copy your
Client ID, click the upper-left most blue "Copy" button. Make sure to save it for a later step.
> ![Copy Client ID](https://i.imgur.com/W3OMTu5.gif)
> `Copy` -> Paste into Notepad for later step
3. Optionally, you can set an icon for your application as it will be the icon for the bot too.
> ![Avatar](https://i.imgur.com/NuFS9kT.png)
4. The next step is actually creating a bot user for your application. From the overview screen,
this is done by going to the "Bot" tab on the left, then clicking the "Add Bot" on the right,
and finally then clicking "Yes, do it!".
> ![Create Bot](https://i.imgur.com/S14iAFS.gif)
> `Bot` -> `Add Bot` -> `Yes, do it!`
5. Once on this screen, you'll need to uncheck the "Public Bot" setting and then click "Save Changes",
so other people can't add your bot to servers that are not your own.
> ![Disable Public Bot](https://i.imgur.com/HHqWvQ1.gif)
> Uncheck `Public Bot` -> `Save Changes`
6. Finally, you'll need to copy your bot's token and save it for a later step. To copy your bot's token,
click the blue "Copy" button right of your bot's icon. Make sure to save it for a later step.
> ![Copy Token](https://i.imgur.com/OqpaSQH.gif)
> `Copy` -> Paste into Notepad for later step
7. Next up is adding your bot to your Discord server. First, go to [essentialsx.net/discord.html](https://essentialsx.net/discord.html)
and paste your Client ID you copied from step 2 into the text box on that page. Once you do that, click
the "Authorize" button next to the text box. This will redirect you to Discord's authorization website
to chose which server to add the bot to.
Note for advanced users: **Please use the `essentialsx.net` link above even if you already know how
to invite bots.** EssentialsX Discord requires more than just the `bot` scope to work.
> ![OAuth Link Gen](https://i.imgur.com/u6MFJgQ.gif)
> Paste Client ID -> `Authorize`
8. Once on the Discord authorization website, select the server from the "Select a server" dropdown
that you want to add the bot to. Then click the "Authorize" button. You may be prompted to confirm
you are not a bot, proceed with that like you would any other captcha.
> ![Authorize](https://i.imgur.com/KXkESqC.gif)
> Select Server -> `Authorize`
9. For the next few steps, you're going to need to do some stuff in Discord, so start up your
Discord desktop/web client.
10. Once in your Discord client, you'll need to enable Developer Mode. Do this by going into the
Settings, then go to the "Appearance" tab and check on the "Developer Mode" at the bottom of the
page. Once you've checked "Developer Mode" on, click the `X` at the top right to exit Settings.
> ![Developer Mode](https://i.imgur.com/CrW31Up.gif)
> `User Settings` -> `Appearance` -> Check `Developer Mode` -> Exit Settings
11. Next is copying a few IDs. First up, you'll want to copy the server (aka guild) id. Do this by
finding the server you added the bot to, right click its icon, and click "Copy ID". Once you copied
it, make sure to save it for a later step.
> ![Guild ID](https://i.imgur.com/0mg2yT3.gif)
> Right click server -> `Copy ID` -> Paste into Notepad for later step
12. The other ID you need to copy is the ID of the channel you wish to be your primary channel.
In other words, this will be the channel that, by default, receives messages for player chat/join/leave/death
messages as well as mute/kicks. To see how to further configure message types, see [Configuring Messages](#configuring-messages).
> ![Primary Channel ID](https://i.imgur.com/uMODfiQ.gif)
> Right click your 'primary' channel -> `Copy ID` -> Paste into Notepad for later step
13. You've successfully copied all the necessary IDs needed for a basic setup. Next up is generating the
default config for EssentialsX Discord, so you can start setting it up! Do this by putting the
EssentialsX Discord jar (you can download it [here](https://essentialsx.net/downloads.html) if you do not
already have one) in your plugins folder, starting your server, and then stopping it as soon as it finishes
starting up.
> ![Start/Stop Server](https://i.imgur.com/JQX6hqM.gif)
> Drag EssentialsXDiscord jar into plugins folder -> Start Server -> Stop Server
14. Now you can start to configure the plugin with all the stuff you copied from earlier. Open the config
for EssentialsX Discord located at `plugins/EssentialsDiscord/config.yml`. When you open the config, the
first thing to configure is your bot's token. Replace `INSERT-TOKEN-HERE` in the config with the token you
copied earlier from step 6.
> ![Paste Token](https://i.imgur.com/EnD31Wg.gif)
> Re-Copy Token from Step 6 -> Paste as token value
15. Next is the guild ID. Replace the zeros for the guild value in the config with the guild ID you copied
from step 13.
> ![Paste Guild](https://i.imgur.com/YxkHykd.gif)
16. Finally, you'll need to paste the primary channel ID you copied from step 14 and paste it as the
primary value in the channels section and once you've done that save the config file!
> ![Paste Primary](https://i.imgur.com/4xaHMfO.gif)
17. Congratulations, you've completed the initial setup guide! When you start up your server, you should
notice that chat and other messages start showing up in the channel you requested they be. Now that you
completed the initial, go back up to the [Table Of Contents](#table-of-contents) to see what other cool things you can do!
---
## Console Relay
The console relay is pretty self-explanatory: it relays everything on your console into a Discord channel of
your choosing. The console relay is ridiculously easy to setup and if your server is already running, you don't
need to reload it!
0. This assumes you've already done the initial setup.
1. Go to the Discord server that your bot is in and find the channel you wish to use for console output.
Right click on the channel and click "Copy ID". Save this ID for the next step.
> ![Copy ID](https://i.imgur.com/qvDfSLv.gif)
> Find console channel -> Right Click -> `Copy ID`
2. Now that you have that copied, open the EssentialsX Discord config and find the `console` section. In that
section, replace the zeros for the `channel` value with the channel ID you copied from the last step. Once
you paste it, make sure you save the config.
> ![Paste ID](https://i.imgur.com/NicdpGw.gif)
3. Finally, if your server is running, run `ess reload` from your console, otherwise start up your server. You
should notice console output being directed to that channel! That is all you need if you're okay with the default
settings. Otherwise, if you'd like to see what other options you can use to customize console output, stick around.
4. The first thing you can customize is the format of the message sent to Discord. By default, the timestamp,
level (info/warn/error/etc), and message are shown for each console message. Let's say you wanted to make the
timestamp and level bold: since this message would be using Discord's markdown, we can just add \*\* to both sides of
level and timestamp. Then once you've done that, just do `/ess reload` and you should see your changes on Discord.
> ![Bold Format](https://i.imgur.com/jD9mH14.gif)
5. Next, you can also configure the name you wish the to show above console messages. By default, it's "EssX Console
Relay" but can be switched to anything you want.
> ![Change Name](https://i.imgur.com/xtrt1Jt.gif)
6. Finally, you can also choose to enable an option to treat any message by a user in the console channel as a
console command. This will mean that anyone who can send messages in your console channel **will be able to execute
commands as the console**. It is suggested that you stick to the regular `/execute` command
(see [Discord Commands](#discord-commands)) as those can be restricted to specific roles/users and are also not
restricted to the console channel.
> ![Command Relay](https://i.imgur.com/w3cfVUw.gif)
7. That's all the options for the command relay!
---
## Configuring Messages
EssentialsX Discord aims to keep its message-type system basic enough that simple things take little changes, while
giving more fine grain control to those you want it.
To give you a general overview of the system, EssentialsX Discord allows you to define different channel IDs in the
`channels` section of the config. By default, two channels are pre-populated in the `channels` section, `primary`
and `staff`. If you only completed the initial setup, the `staff` channel definition is all zeros. This is fine in
most situations however, as the message system will always fallback to the `primary` channel if a channel ID is
invalid.
Now on the to the types of messages you can receive themselves (which is where you're going to use these channel
definitions). In the `message-types` section of the config, you can see a list of message types (join/leave/chat/etc)
on the left (as the key), and on the right there is a channel definition.
For the sake of example lets say we want to send all chat messages to their own channel. We can do this by creating
a new channel definition and setting the `chat` message type to said channel definition. Below are step-by-step
instructions for said example, you can follow along to get the gist of how to apply this to other use cases
1. Find the channel on Discord you want to only send chat messages to, and then right click the channel and click
"Copy ID".
> ![Copy ID](https://i.imgur.com/ri7NZkD.gif)
2. Next you need to create the actual channel definition, for this example we'll call it `chat`. You create a
channel definition by adding a new entry to the `channels` section with the key as its name and the ID as the one
you copied in the last step.
> ![New Def](https://i.imgur.com/dc7kIkl.gif)
3. Finally, scroll down to the `message-types` section and change the `chat` message type to your newly created
channel definition. Once you do that, save and either run `/ess reload` if your server is running or start your
server.
> ![Move](https://i.imgur.com/qPVWkWF.gif)
4. That's all you need to know about the basics of the message system!
---
## Receive Discord Messages in Minecraft
After reading the [configuring messages section](#configuring-messages), you should now have a few Discord
channels defined in the `channels` of your config. You're probably wondering how you can let your players start
to see messages from Discord in Minecraft chat. Say I defined a channel named `chat` in the `channels` section
of your config, and I wanted to let players see Discord messages from that channel in Minecraft chat; This can
be accomplished very simply by giving players the `essentials.discord.receive.chat` permission. This would relay
all Discord messages from the `chat` channel to players with that permission. Another example: say I have a staff
channel in Discord that I want only staff members in the Minecraft server to see. Provided there is a `staff`
channel defined in the `channels` section of the config, I can give staff members the
`essentials.discord.receive.staff` permission, and they will start to see messages from that channel.
---
## Discord Commands
EssentialsX Discord uses Discord's slash command system to let you type commands into Discord without it being
seen by other people in the server. With this system, you are able to execute console commands, message players,
and see the current player list.
For example, here's what the `/execute` command looks like by default:
> ![/execute](https://i.imgur.com/yPN22bV.gif)
As you can see, you can seamlessly run commands without people seeing the content of your commands or their
response. Additionally, you can also delete the responses once you're done looking at them, so they don't clutter
your chat.
However, this is all configurable! In the `commands` section of the config, lies a ton of options to configure
settings on a per-command basis. Below are explanations of what all the configuration options mean and how to use
them.
* `enabled`
* Default: `true`
* Description: `Whether or not the command should be enabled and therefore shown on Discord. Note that you
must restart your Minecraft server before this option takes effect.`
* `hide-command`
* Default: `true`
* Description: `Whether other people should not be able to see what commands you execute. Setting to false
would allow people in the same channel as you to see exactly what command you execute. In the example below,
you can see how disabling this option shows a message of the user and the command they executed.`
* Example: ![Show Command](https://i.imgur.com/Q61iP4n.gif)
* `allowed-roles`
* Description: `A list of user IDs or role names/IDs that are allowed to use the command. You can also use '*'
in order to allow everyone to use the command.`
* `admin-roles`
* `A list of user IDs or role names/IDs that have extra features in the command. For example, in the list
command, admin-roles allows people to see vanished players.`
---
## Misc Permissions
EssentialsX Discord has a few other permissions that may be important to know about:
* `essentials.discord.markdown` - Allows players to bypass the Markdown filter, so that they can
bold/underline/italic/etc their Minecraft chat messages for Discord.
* `essentials.discord.ping` - Allows players to bypass the ping filter, so that they can ping @everyone/@here
from Minecraft chat.
---
## Developer API
EssentialsX Discord has a pretty extensive API which allows any third party plugin to build
their own integrations into it. Outside the specific examples below, you can also view
javadocs for EssentialsX Discord [here](https://jd-v2.essentialsx.net/EssentialsDiscord).
### Sending Messages to Discord
EssentialsX Discord organizes the types of messages that can be sent along with their
destination on Discord under the `message-types` section of the `config.yml`. The
EssentialsX Discord API uses `message-types` to resolve the channel id you want to send your
message to.
#### Using a built-in message channel
EssentialsX Discord defines a few built in `message-types` which you may fit your use case
already (such as sending a message to the MC->Discord chat relay channel). The list of
built-in message types can be found at [`MessageType.DefaultTypes`](https://github.com/EssentialsX/Essentials/blob/2.x/EssentialsDiscord/src/main/java/net/essentialsx/api/v2/services/discord/MessageType.java#L47-L67).
Here is an example of what sending a message to the built-in chat channel would look like:
```java
// The built in channel you want to send your message to, in this case the chat channel.
final MessageType channel = MessageType.DefaultTypes.CHAT;
// Set to true if your message should be allowed to ping @everyone, @here, or roles.
// If you are sending user-generated content, you probably should keep this as false.
final boolean allowGroupMentions = false;
// Send the actual message
final DiscordService api = Bukkit.getServicesManager().load(DiscordService.class);
api.sendMessage(channel, "My Epic Message", allowGroupMentions);
```
#### Using your own message channel
If you want to create your own message type to allow your users to explicitly separate your
messages from our other built-in ones, you can do that also by creating a new
[`MessageType`](https://github.com/EssentialsX/Essentials/blob/2.x/EssentialsDiscord/src/main/java/net/essentialsx/api/v2/services/discord/MessageType.java).
The key provided in the constructor should be the key you'd like your users to use in the
`message-types` section of our config. This key should also be all lowercase and may contain
numbers or dashes. You *can* also put a Discord channel ID as the key if you'd like to
have your users define the channel id in your config rather than ours. Once you create the
`MessageType`, you will also need to register it with Essentialsx Discord by calling
[`DiscordService#registerMessageType`](https://github.com/EssentialsX/Essentials/blob/2.x/EssentialsDiscord/src/main/java/net/essentialsx/api/v2/services/discord/DiscordService.java#L24-L30).
Here is an example of what sending a message using your own message type:
```java
public class CustomTypeExample {
private final DiscordService api;
private final MessageType type;
public CustomTypeExample(final Plugin plugin) {
// Gets the the EssentialsX Discord API service so we can register our type and
// send a message with it later.
api = Bukkit.getServicesManager().load(DiscordService.class);
// Create a new message type for the user to define in our config.
// Unless you're putting a discord channel id as the type key, it's probably
// a good idea to store this object so you don't create it every time.
type = new MessageType("my-awesome-channel");
// Registers the type we just created with EssentialsX Discord.
api.registerMessageType(plugin, type);
}
@EventHandler()
public void onAwesomeEvent(AwesomeEvent event) {
// Set to true if your message should be allowed to ping @everyone, @here, or roles.
// If you are sending user-generated content, you probably should keep this as false.
final boolean allowGroupMentions = false;
// Send the actual message
api.sendMessage(type, "The player, " + event.getPlayer() + ", did something awesome!", allowPing);
}
}
```
### Prevent certain messages from being sent as chat
Depending on how your plugin sends certain types of chat messages to players, there may be
times when EssentialsX Discord accidentally broadcasts a message that was only intended for a
small group of people. In order for your plugin to stop this from happening you have to
listen to `DiscordChatMessageEvent`.
Here is an example of how a staff chat plugin would cancel a message:
```java
public class StaffChatExample {
private final StaffChatPlugin plugin = ...;
@EventHandler()
public void onDiscordChatMessage(DiscordChatMessageEvent event) {
// Checks if the player is in staff chat mode in this theoretical plugin.
if (plugin.isPlayerInStaffChat(event.getPlayer()) ||
// or we could check if their message started with a # if we use that
// to indicate typing in a specific channel.
event.getMessage().startsWith("#")) {
event.setCanceled(true);
}
}
}
```
Additionally, you can also look at [TownyChat's EssentialsX Discord hook](https://github.com/TownyAdvanced/TownyChat/commit/5bee9611aa4200e3cde1a28af48c25caa4aec649).
### Registering a Discord slash command
EssentialsX Discord also allows you to register slash commands directly with Discord itself
in order to provide your users with a way to interface with your plugins on Discord!
To start writing slash commands, the first thing you'll need to do is create a slash command
class. For the sake of this tutorial, I'm going to use an economy plugin as the
hypothetical plugin creating this slash command.
For this slash command, I'll create a simple command to a string (for player name) and
check their balance.
```java
public class BalanceSlashCommand extends InteractionCommand {
private final MyEconomyPlugin plugin = ...;
@Override
public void onCommand(InteractionEvent event) {
// The name of the argument here has to be the same you used in getArguments()
final String playerName = event.getStringArgument("player");
final Player player = Bukkit.getPlayerExact(playerName);
if (player == null) {
event.reply("A player by that name could not be found!");
return;
}
final int balance = plugin.getBalance(player);
// It is important you reply to the InteractionEvent at least once as discord
// will show your bot is 'thinking' until you do so.
event.reply("The balance of " + player.getName() + " is $" + balance);
}
@Override
public String getName() {
// This should return the name of the command as you want it to appear in discord.
// This method should never return different values.
return "balance";
}
@Override
public String getDescription() {
// This should return the description of the command as you want it
// to appear in discord.
// This method should never return different values.
return "Checks the balance of the given player";
}
@Override
public List<InteractionCommandArgument> getArguments() {
// Should return a list of arguments that will be used in your command.
// If you don't want any arguments, you can return null here.
return List.of(
new InteractionCommandArgument(
// This should be the name of the command argument.
// Keep it a single world, all lower case.
"player",
// This is the description of the argument.
"The player to check the balance of",
// This is the type of the argument you'd like to receive from
// discord.
InteractionCommandArgumentType.STRING,
// Should be set to true if the argument is required to send
// the command from discord.
true));
}
@Override
public boolean isEphemeral() {
// Whether or not the command and response should be hidden to other users on discord.
// Return true here in order to hide command/responses from other discord users.
return false;
}
@Override
public boolean isDisabled() {
// Whether or not the command should be prevented from being registered/executed.
// Return true here in order to mark the command as disabled.
return false;
}
}
```
Once you have created your slash command, it's now time to register it. It is best
practice to register them in your plugin's `onEnable` so your commands make it in the
initial batch of commands sent to Discord.
You can register your command with EssentialsX Discord by doing the following:
```java
...
import net.essentialsx.api.v2.services.discord.DiscordService;
...
public class MyEconomyPlugin {
@Override
public void onEnable() {
final DiscordService api = Bukkit.getServicesManager().load(DiscordService.class);
api.getInteractionController().registerCommand(new BalanceSlashCommand());
}
}
```
---

@ -0,0 +1,58 @@
plugins {
id("essentials.shadow-module")
}
dependencies {
compileOnly project(':EssentialsX')
implementation('net.dv8tion:JDA:4.3.0_277') {
//noinspection GroovyAssignabilityCheck
exclude module: 'opus-java'
}
implementation 'com.vdurmont:emoji-java:5.1.1'
implementation 'club.minnced:discord-webhooks:0.5.6'
compileOnly 'org.apache.logging.log4j:log4j-core:2.0-beta9'
compileOnly 'me.clip:placeholderapi:2.10.9'
}
shadowJar {
dependencies {
// JDA
include(dependency('net.dv8tion:JDA'))
include(dependency('com.neovisionaries:nv-websocket-client'))
include(dependency('com.squareup.okhttp3:okhttp'))
include(dependency('com.squareup.okio:okio'))
include(dependency('org.apache.commons:commons-collections4'))
include(dependency('net.sf.trove4j:trove4j'))
include(dependency('com.fasterxml.jackson.core:jackson-databind'))
include(dependency('com.fasterxml.jackson.core:jackson-core'))
include(dependency('com.fasterxml.jackson.core:jackson-annotations'))
include(dependency('org.slf4j:slf4j-api'))
// Emoji
include(dependency('com.vdurmont:emoji-java'))
include(dependency('org.json:json'))
// discord-webhooks
include(dependency('club.minnced:discord-webhooks'))
}
minimize()
// JDA
relocate 'net.dv8tion.jda', 'net.essentialsx.dep.net.dv8tion.jda'
relocate 'com.neovisionaries.ws', 'net.essentialsx.dep.com.neovisionaries.ws'
relocate 'okhttp3', 'net.essentialsx.dep.okhttp3'
relocate 'okio', 'net.essentialsx.dep.okio'
relocate 'com.iwebpp.crypto', 'net.essentialsx.dep.com.iwebpp.crypto'
relocate 'org.apache.commons.collections4', 'net.essentialsx.dep.org.apache.commons.collections4'
relocate 'com.fasterxml.jackson.databind', 'net.essentialsx.dep.com.fasterxml.jackson.databind'
relocate 'com.fasterxml.jackson.core', 'net.essentialsx.dep.com.fasterxml.jackson.core'
relocate 'com.fasterxml.jackson.annotation', 'net.essentialsx.dep.com.fasterxml.jackson.annotation'
relocate 'gnu.trove', 'net.essentialsx.dep.gnu.trove'
// Emoji
relocate 'com.vdurmont.emoji', 'net.essentialsx.dep.com.vdurmont.emoji'
relocate 'org.json', 'net.essentialsx.dep.org.json'
// discord-webhooks
relocate 'club.minnced.discord.webhook', 'net.essentialsx.dep.club.minnced.discord.webhook'
}

@ -0,0 +1,72 @@
package net.essentialsx.api.v2.events.discord;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
/**
* Fired before a chat message is about to be sent to a Discord channel.
* Should be used to block chat messages (such as staff channels) from appearing in Discord.
*/
public class DiscordChatMessageEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Player player;
private String message;
private boolean cancelled = false;
/**
* @param player The player which caused this event.
* @param message The message of this event.
*/
public DiscordChatMessageEvent(Player player, String message) {
this.player = player;
this.message = message;
}
/**