Search in sources :

Example 1 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class DiscordCommands method reload.

public void reload() {
    try {
        Guild guild = discordsrv.getMainGuild();
        String memberLabel = InteractiveChatDiscordSrvAddon.plugin.discordMemberLabel;
        String memberDescription = InteractiveChatDiscordSrvAddon.plugin.discordMemberDescription;
        String slotLabel = InteractiveChatDiscordSrvAddon.plugin.discordSlotLabel;
        String slotDescription = InteractiveChatDiscordSrvAddon.plugin.discordSlotDescription;
        guild.retrieveCommands().complete().forEach(each -> {
            switch(each.getName()) {
                case RESOURCEPACK_LABEL:
                    if (InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandIsMainServer) {
                        each.delete().complete();
                    }
                    break;
                case PLAYERLIST_LABEL:
                    if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandIsMainServer) {
                        each.delete().complete();
                    }
                    break;
                case ITEM_LABEL:
                case ITEM_OTHER_LABEL:
                    if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
                        each.delete().complete();
                    }
                    break;
                case INVENTORY_LABEL:
                case INVENTORY_OTHER_LABEL:
                    if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                        each.delete().complete();
                    }
                    break;
                case ENDERCHEST_LABEL:
                case ENDERCHEST_OTHER_LABEL:
                    if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
                        each.delete().complete();
                    }
                    break;
            }
        });
        if (InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandEnabled && InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandIsMainServer) {
            guild.upsertCommand(RESOURCEPACK_LABEL, ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandDescription)).setDefaultEnabled(false).queue(command -> {
                command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandRoles))).queue();
            });
        }
        if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandEnabled && InteractiveChatDiscordSrvAddon.plugin.playerlistCommandIsMainServer) {
            guild.upsertCommand(PLAYERLIST_LABEL, ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDescription)).setDefaultEnabled(false).queue(command -> {
                command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandRoles))).queue();
            });
        }
        Optional<ICPlaceholder> optItemPlaceholder = InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.itemPlaceholder)).findFirst();
        if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandEnabled && optItemPlaceholder.isPresent() && InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
            String itemDescription = ChatColorUtils.stripColor(optItemPlaceholder.get().getDescription());
            SubcommandData mainhandSubcommand = new SubcommandData("mainhand", itemDescription);
            SubcommandData offhandSubcommand = new SubcommandData("offhand", itemDescription);
            SubcommandData hotbarSubcommand = new SubcommandData("hotbar", itemDescription).addOptions(new OptionData(OptionType.INTEGER, slotLabel, slotDescription, true).setRequiredRange(1, 9));
            SubcommandData inventorySubcommand = new SubcommandData("inventory", itemDescription).addOptions(new OptionData(OptionType.INTEGER, slotLabel, slotDescription, true).setRequiredRange(1, 41));
            SubcommandData armorSubcommand = new SubcommandData("armor", itemDescription).addOptions(new OptionData(OptionType.STRING, slotLabel, slotDescription, true).addChoice("head", "head").addChoice("chest", "chest").addChoice("legs", "legs").addChoice("feet", "feet"));
            SubcommandData enderSubcommand = new SubcommandData("ender", itemDescription).addOptions(new OptionData(OptionType.INTEGER, slotLabel, slotDescription, true).setRequiredRange(1, 27));
            guild.upsertCommand(ITEM_LABEL, ChatColorUtils.stripColor(optItemPlaceholder.get().getDescription())).addSubcommands(mainhandSubcommand).addSubcommands(offhandSubcommand).addSubcommands(hotbarSubcommand).addSubcommands(inventorySubcommand).addSubcommands(armorSubcommand).addSubcommands(enderSubcommand).setDefaultEnabled(false).queue(command -> {
                command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.shareItemCommandSelfRoles))).queue();
            });
            if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandAsOthers) {
                SubcommandData mainhandOtherSubcommand = new SubcommandData("mainhand", itemDescription).addOption(OptionType.USER, memberLabel, memberDescription, true);
                SubcommandData offhandOtherSubcommand = new SubcommandData("offhand", itemDescription).addOption(OptionType.USER, memberLabel, memberDescription, true);
                SubcommandData hotbarOtherSubcommand = new SubcommandData("hotbar", itemDescription).addOptions(new OptionData(OptionType.INTEGER, slotLabel, slotDescription, true).setRequiredRange(1, 9)).addOption(OptionType.USER, memberLabel, memberDescription, true);
                SubcommandData inventoryOtherSubcommand = new SubcommandData("inventory", itemDescription).addOptions(new OptionData(OptionType.INTEGER, slotLabel, slotDescription, true).setRequiredRange(1, 41)).addOption(OptionType.USER, memberLabel, memberDescription, true);
                SubcommandData armorOtherSubcommand = new SubcommandData("armor", itemDescription).addOptions(new OptionData(OptionType.STRING, slotLabel, slotDescription, true).addChoice("head", "head").addChoice("chest", "chest").addChoice("legs", "legs").addChoice("feet", "feet")).addOption(OptionType.USER, memberLabel, memberDescription, true);
                SubcommandData enderOtherSubcommand = new SubcommandData("ender", itemDescription).addOptions(new OptionData(OptionType.INTEGER, slotLabel, slotDescription, true).setRequiredRange(1, 27)).addOption(OptionType.USER, memberLabel, memberDescription, true);
                guild.upsertCommand(ITEM_OTHER_LABEL, ChatColorUtils.stripColor(optItemPlaceholder.get().getDescription())).addSubcommands(mainhandOtherSubcommand).addSubcommands(offhandOtherSubcommand).addSubcommands(hotbarOtherSubcommand).addSubcommands(inventoryOtherSubcommand).addSubcommands(armorOtherSubcommand).addSubcommands(enderOtherSubcommand).setDefaultEnabled(false).queue(command -> {
                    command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.shareItemCommandOthersRoles))).queue();
                });
            }
        }
        Optional<ICPlaceholder> optInvPlaceholder = InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.invPlaceholder)).findFirst();
        if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandEnabled && optInvPlaceholder.isPresent() && InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
            guild.upsertCommand(INVENTORY_LABEL, ChatColorUtils.stripColor(optInvPlaceholder.get().getDescription())).setDefaultEnabled(false).queue(command -> {
                command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.shareInvCommandSelfRoles))).queue();
            });
            if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandAsOthers) {
                guild.upsertCommand(INVENTORY_OTHER_LABEL, ChatColorUtils.stripColor(optInvPlaceholder.get().getDescription())).addOption(OptionType.USER, memberLabel, memberDescription, true).setDefaultEnabled(false).queue(command -> {
                    command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.shareInvCommandOthersRoles))).queue();
                });
            }
        }
        Optional<ICPlaceholder> optEnderPlaceholder = InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.enderPlaceholder)).findFirst();
        if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandEnabled && optEnderPlaceholder.isPresent() && InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
            guild.upsertCommand(ENDERCHEST_LABEL, ChatColorUtils.stripColor(optEnderPlaceholder.get().getDescription())).setDefaultEnabled(false).queue(command -> {
                command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandSelfRoles))).queue();
            });
            if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandAsOthers) {
                guild.upsertCommand(ENDERCHEST_OTHER_LABEL, ChatColorUtils.stripColor(optEnderPlaceholder.get().getDescription())).addOption(OptionType.USER, memberLabel, memberDescription, true).setDefaultEnabled(false).queue(command -> {
                    command.updatePrivileges(guild, JDAUtils.toWhitelistedCommandPrivileges(guild, JDAUtils.toRoles(guild, InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandOthersRoles))).queue();
                });
            }
        }
    } catch (ErrorResponseException e) {
        if (e.getResponse().code == 50001) {
            throw new DiscordCommandRegistrationException("Scope \"applications.commands\" missing in discord bot application.\nCheck the Q&A section in https://www.spigotmc.org/resources/83917/ for more information", e);
        }
        throw new DiscordCommandRegistrationException(e);
    }
}
Also used : Color(java.awt.Color) Arrays(java.util.Arrays) InventoryUtils(com.loohp.interactivechat.utils.InventoryUtils) PlayerUtils(com.loohp.interactivechat.utils.PlayerUtils) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Map(java.util.Map) ComponentStringUtils(com.loohp.interactivechatdiscordsrvaddon.utils.ComponentStringUtils) Material(org.bukkit.Material) EquipmentSlot(org.bukkit.inventory.EquipmentSlot) DiscordToolTip(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordToolTip) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) Guild(github.scarsz.discordsrv.dependencies.jda.api.entities.Guild) Set(java.util.Set) OfflinePlayer(org.bukkit.OfflinePlayer) ItemStack(org.bukkit.inventory.ItemStack) InteractiveChat(com.loohp.interactivechat.InteractiveChat) MessageEmbed(github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed) CustomStringUtils(com.loohp.interactivechat.utils.CustomStringUtils) OptionData(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.build.OptionData) Chat(net.milkbowl.vault.chat.Chat) EmbedBuilder(github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder) ImageUtils(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageUtils) BungeeMessageSender(com.loohp.interactivechat.bungeemessaging.BungeeMessageSender) MCVersion(com.loohp.interactivechat.utils.MCVersion) HoverEvent(com.loohp.interactivechat.libs.net.kyori.adventure.text.event.HoverEvent) PostPacketComponentProcessEvent(com.loohp.interactivechat.api.events.PostPacketComponentProcessEvent) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) LanguageUtils(com.loohp.interactivechat.utils.LanguageUtils) ColorUtils(com.loohp.interactivechat.utils.ColorUtils) InteractiveChatDiscordSRVConfigReloadEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.InteractiveChatDiscordSRVConfigReloadEvent) OptionType(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.OptionType) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) DiscordDescription(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordDescription) IOException(java.io.IOException) WebhookMessageUpdateAction(github.scarsz.discordsrv.dependencies.jda.api.requests.restaction.WebhookMessageUpdateAction) Field(java.lang.reflect.Field) ExecutionException(java.util.concurrent.ExecutionException) ValueTrios(com.loohp.interactivechat.objectholders.ValueTrios) TextReplacementConfig(com.loohp.interactivechat.libs.net.kyori.adventure.text.TextReplacementConfig) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) LegacyComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) DiscordItemStackUtils(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils) VanishUtils(com.loohp.interactivechat.utils.VanishUtils) ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) ListenerAdapter(github.scarsz.discordsrv.dependencies.jda.api.hooks.ListenerAdapter) Player(org.bukkit.entity.Player) Inventory(org.bukkit.inventory.Inventory) ComponentModernizing(com.loohp.interactivechat.utils.ComponentModernizing) EventHandler(org.bukkit.event.EventHandler) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) SlashCommandEvent(github.scarsz.discordsrv.dependencies.jda.api.events.interaction.SlashCommandEvent) OptionMapping(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.OptionMapping) InventoryDisplay(com.loohp.interactivechat.modules.InventoryDisplay) TranslatableComponent(com.loohp.interactivechat.libs.net.kyori.adventure.text.TranslatableComponent) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) Bukkit(org.bukkit.Bukkit) BufferedImage(java.awt.image.BufferedImage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ClickEvent(com.loohp.interactivechat.libs.net.kyori.adventure.text.event.ClickEvent) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ImageGeneration(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageGeneration) List(java.util.List) ErrorResponseException(github.scarsz.discordsrv.dependencies.jda.api.exceptions.ErrorResponseException) SubcommandData(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.build.SubcommandData) TextDecoration(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.TextDecoration) JDAUtils(com.loohp.interactivechatdiscordsrvaddon.utils.JDAUtils) Entry(java.util.Map.Entry) Optional(java.util.Optional) NBTEditor(com.loohp.interactivechat.libs.io.github.bananapuncher714.nbteditor.NBTEditor) ArrayUtils(com.loohp.interactivechat.libs.org.apache.commons.lang3.ArrayUtils) Permission(net.milkbowl.vault.permission.Permission) ItemMeta(org.bukkit.inventory.meta.ItemMeta) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) InteractiveChatDiscordSrvAddon(com.loohp.interactivechatdiscordsrvaddon.InteractiveChatDiscordSrvAddon) SkinUtils(com.loohp.interactivechat.utils.SkinUtils) ComponentStyling(com.loohp.interactivechat.utils.ComponentStyling) HashSet(java.util.HashSet) PlainTextComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) SharedType(com.loohp.interactivechat.api.InteractiveChatAPI.SharedType) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) ChatColor(net.md_5.bungee.api.ChatColor) Listener(org.bukkit.event.Listener) ItemDisplay(com.loohp.interactivechat.modules.ItemDisplay) TimeUnit(java.util.concurrent.TimeUnit) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) TranslationKeyUtils(com.loohp.interactivechatdiscordsrvaddon.utils.TranslationKeyUtils) NamedTextColor(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.NamedTextColor) Comparator(java.util.Comparator) HashUtils(com.loohp.interactivechat.utils.HashUtils) ModelDisplayPosition(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelDisplay.ModelDisplayPosition) Collections(java.util.Collections) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) OptionData(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.build.OptionData) ErrorResponseException(github.scarsz.discordsrv.dependencies.jda.api.exceptions.ErrorResponseException) Guild(github.scarsz.discordsrv.dependencies.jda.api.entities.Guild) SubcommandData(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.build.SubcommandData)

Example 2 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class OutboundToDiscordEvents method onDiscordToGame.

@Subscribe(priority = ListenerPriority.LOW)
public void onDiscordToGame(DiscordGuildMessagePostProcessEvent event) {
    Debug.debug("Triggering onDiscordToGame");
    InteractiveChatDiscordSrvAddon.plugin.messagesCounter.incrementAndGet();
    github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component component = event.getMinecraftMessage();
    if (InteractiveChatDiscordSrvAddon.plugin.escapePlaceholdersFromDiscord) {
        Debug.debug("onDiscordToGame escaping placeholders");
        for (ICPlaceholder placeholder : InteractiveChat.placeholderList.values()) {
            component = component.replaceText(github.scarsz.discordsrv.dependencies.kyori.adventure.text.TextReplacementConfig.builder().match(placeholder.getKeyword()).replacement("\\" + placeholder.getKeyword()).build());
        }
        event.setMinecraftMessage(component);
    }
}
Also used : ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Subscribe(github.scarsz.discordsrv.api.Subscribe)

Example 3 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class InteractiveChatVelocity method onBungeeChat.

@Subscribe(order = PostOrder.LATE)
public void onBungeeChat(PlayerChatEvent event) {
    if (!event.getResult().isAllowed()) {
        return;
    }
    Player player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    String message = event.getMessage();
    if (!player.getCurrentServer().isPresent()) {
        return;
    }
    String newMessage = event.getMessage();
    boolean hasInteractiveChat = false;
    BackendInteractiveChatData data = serverInteractiveChatInfo.get(player.getCurrentServer().get().getServerInfo().getName());
    if (data != null) {
        hasInteractiveChat = data.hasInteractiveChat();
    }
    boolean usage = false;
    outer: for (List<ICPlaceholder> serverPlaceholders : placeholderList.values()) {
        for (ICPlaceholder icplaceholder : serverPlaceholders) {
            if (icplaceholder.getKeyword().matcher(message).find()) {
                usage = true;
                break outer;
            }
        }
    }
    if (newMessage.startsWith("/")) {
        if (usage && hasInteractiveChat) {
            for (String parsecommand : InteractiveChatVelocity.parseCommands) {
                if (newMessage.matches(parsecommand)) {
                    String command = newMessage.trim();
                    outer: for (List<ICPlaceholder> serverPlaceholders : placeholderList.values()) {
                        for (ICPlaceholder icplaceholder : serverPlaceholders) {
                            Pattern placeholder = icplaceholder.getKeyword();
                            Matcher matcher = placeholder.matcher(command);
                            if (matcher.find()) {
                                String uuidmatch = "<cmd=" + uuid + ":" + Registry.ID_ESCAPE_PATTERN.matcher(command.substring(matcher.start(), matcher.end())).replaceAll("\\>") + ":>";
                                command = command.substring(0, matcher.start()) + uuidmatch + command.substring(matcher.end());
                                if (command.length() > 256) {
                                    command = command.substring(0, 256);
                                }
                                event.setResult(ChatResult.message(command));
                                break outer;
                            }
                        }
                    }
                    break;
                }
            }
        }
    } else {
        if (usage && InteractiveChatBungee.useAccurateSenderFinder && hasInteractiveChat) {
            outer: for (List<ICPlaceholder> serverPlaceholders : placeholderList.values()) {
                for (ICPlaceholder icplaceholder : serverPlaceholders) {
                    Pattern placeholder = icplaceholder.getKeyword();
                    Matcher matcher = placeholder.matcher(message);
                    if (matcher.find()) {
                        String uuidmatch = "<chat=" + uuid + ":" + Registry.ID_ESCAPE_PATTERN.matcher(message.substring(matcher.start(), matcher.end())).replaceAll("\\>") + ":>";
                        message = message.substring(0, matcher.start()) + uuidmatch + message.substring(matcher.end());
                        if (message.length() > 256) {
                            message = message.substring(0, 256);
                        }
                        event.setResult(ChatResult.message(message));
                        break outer;
                    }
                }
            }
        }
        proxyServer.getScheduler().buildTask(plugin, () -> {
            Map<String, Long> messages = forwardedMessages.get(uuid);
            if (messages != null && messages.remove(newMessage) != null) {
                try {
                    PluginMessageSendingVelocity.sendMessagePair(uuid, newMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).delay(100, TimeUnit.MILLISECONDS).schedule();
    }
}
Also used : Pattern(java.util.regex.Pattern) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) Player(com.velocitypowered.api.proxy.Player) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Matcher(java.util.regex.Matcher) BackendInteractiveChatData(com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UUID(java.util.UUID) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 4 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class Commands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (!label.equalsIgnoreCase("interactivechat") && !label.equalsIgnoreCase("ic")) {
        return true;
    }
    if (args.length == 0) {
        sender.sendMessage(ChatColor.AQUA + "InteractiveChat written by LOOHP!");
        sender.sendMessage(ChatColor.GOLD + "You are running InteractiveChat version: " + InteractiveChat.plugin.getDescription().getVersion());
        return true;
    }
    if (args[0].equalsIgnoreCase("reload")) {
        if (sender.hasPermission("interactivechat.reload")) {
            InteractiveChat.closeSharedInventoryViews();
            ConfigManager.reloadConfig();
            InteractiveChat.placeholderCooldownManager.reloadPlaceholders();
            PlayerUtils.resetAllPermissionCache();
            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> InteractiveChat.playerDataManager.reload());
            if (InteractiveChat.bungeecordMode) {
                try {
                    BungeeMessageSender.reloadBungeeConfig(System.currentTimeMillis());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sender.sendMessage(InteractiveChat.reloadPluginMessage);
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("update")) {
        if (sender.hasPermission("interactivechat.update")) {
            sender.sendMessage(ChatColor.AQUA + "[InteractiveChat] InteractiveChat written by LOOHP!");
            sender.sendMessage(ChatColor.GOLD + "[InteractiveChat] You are running InteractiveChat version: " + InteractiveChat.plugin.getDescription().getVersion());
            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> {
                UpdaterResponse version = Updater.checkUpdate();
                if (version.getResult().equals("latest")) {
                    if (version.isDevBuildLatest()) {
                        sender.sendMessage(ChatColor.GREEN + "[InteractiveChat] You are running the latest version!");
                    } else {
                        Updater.sendUpdateMessage(sender, version.getResult(), version.getSpigotPluginId(), true);
                    }
                } else {
                    Updater.sendUpdateMessage(sender, version.getResult(), version.getSpigotPluginId());
                }
            });
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("mentiontoggle")) {
        if (sender.hasPermission("interactivechat.mention.toggle")) {
            if (args.length == 1) {
                if (sender instanceof Player) {
                    Player player = (Player) sender;
                    PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                    if (pd.isMentionDisabled()) {
                        pd.setMentionDisabled(false);
                        Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                        sender.sendMessage(InteractiveChat.mentionEnable);
                    } else {
                        pd.setMentionDisabled(true);
                        Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                        sender.sendMessage(InteractiveChat.mentionDisable);
                    }
                    if (InteractiveChat.bungeecordMode) {
                        try {
                            BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    sender.sendMessage(InteractiveChat.noConsoleMessage);
                }
            } else {
                if (sender.hasPermission("interactivechat.mention.toggle.others")) {
                    Player player = Bukkit.getPlayer(args[1]);
                    if (player != null) {
                        PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                        if (pd.isMentionDisabled()) {
                            pd.setMentionDisabled(false);
                            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                            sender.sendMessage(InteractiveChat.mentionEnable);
                        } else {
                            pd.setMentionDisabled(true);
                            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                            sender.sendMessage(InteractiveChat.mentionDisable);
                        }
                        if (InteractiveChat.bungeecordMode) {
                            try {
                                BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        sender.sendMessage(InteractiveChat.invalidPlayerMessage);
                    }
                } else {
                    sender.sendMessage(InteractiveChat.noPermissionMessage);
                }
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("setinvdisplaylayout")) {
        if (sender.hasPermission("interactivechat.module.inventory.setlayout")) {
            try {
                if (args.length == 1) {
                    sender.sendMessage(InteractiveChat.notEnoughArgs);
                } else if (args.length == 2) {
                    if (sender instanceof Player) {
                        int layout = Integer.parseInt(args[1]);
                        if (!InventoryDisplay.LAYOUTS.contains(layout)) {
                            throw new NumberFormatException();
                        }
                        Player player = (Player) sender;
                        PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                        pd.setInventoryDisplayLayout(layout);
                        Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                        sender.sendMessage(InteractiveChat.setInvDisplayLayout.replace("{Layout}", layout + ""));
                        if (InteractiveChat.bungeecordMode) {
                            try {
                                BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        sender.sendMessage(InteractiveChat.noConsoleMessage);
                    }
                } else {
                    if (sender.hasPermission("interactivechat.module.inventory.setlayout.others")) {
                        Player player = Bukkit.getPlayer(args[2]);
                        if (player != null) {
                            int layout = Integer.parseInt(args[1]);
                            if (!InventoryDisplay.LAYOUTS.contains(layout)) {
                                throw new NumberFormatException();
                            }
                            PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                            pd.setInventoryDisplayLayout(layout);
                            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                            sender.sendMessage(InteractiveChat.setInvDisplayLayout.replace("{Layout}", layout + ""));
                            if (InteractiveChat.bungeecordMode) {
                                try {
                                    BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            sender.sendMessage(InteractiveChat.invalidPlayerMessage);
                        }
                    } else {
                        sender.sendMessage(InteractiveChat.noPermissionMessage);
                    }
                }
            } catch (NumberFormatException e) {
                sender.sendMessage(InteractiveChat.invalidArgs);
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("list")) {
        try {
            if (sender.hasPermission("interactivechat.list")) {
                int start = 0;
                int end = InteractiveChat.placeholderList.size();
                if (args.length > 1) {
                    start = Integer.parseInt(args[1]) - 1;
                    if (start < 0) {
                        start = 0;
                    }
                }
                if (args.length > 2) {
                    end = Integer.parseInt(args[2]);
                    if (end < 0) {
                        end = InteractiveChat.placeholderList.size();
                    }
                }
                InteractiveChatAPI.sendMessageUnprocessed(sender, LegacyComponentSerializer.legacySection().deserialize(InteractiveChat.listPlaceholderHeader));
                String body = InteractiveChat.listPlaceholderBody;
                List<Component> items = new ArrayList<>();
                if (sender.hasPermission("interactivechat.list.all")) {
                    int i = 0;
                    for (ICPlaceholder placeholder : InteractiveChat.placeholderList.values()) {
                        i++;
                        String text = body.replace("{Order}", i + "").replace("{Keyword}", placeholder.getName()).replace("{Description}", placeholder.getDescription());
                        items.add(LegacyComponentSerializer.legacySection().deserialize(text));
                    }
                } else {
                    int i = 0;
                    for (ICPlaceholder placeholder : InteractiveChat.placeholderList.values()) {
                        if ((placeholder.isBuildIn() && sender.hasPermission(placeholder.getPermission())) || (!placeholder.isBuildIn() && (sender.hasPermission(placeholder.getPermission()) || !InteractiveChat.useCustomPlaceholderPermissions))) {
                            i++;
                            String text = body.replace("{Order}", i + "").replace("{Keyword}", placeholder.getName()).replace("{Description}", placeholder.getDescription());
                            items.add(LegacyComponentSerializer.legacySection().deserialize(text));
                        }
                    }
                }
                for (int i = start; i < end && i < items.size(); i++) {
                    InteractiveChatAPI.sendMessageUnprocessed(sender, items.get(i));
                }
            } else {
                sender.sendMessage(InteractiveChat.noPermissionMessage);
            }
        } catch (Exception e) {
            sender.sendMessage(InteractiveChat.invalidArgs);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("parse")) {
        if (sender.hasPermission("interactivechat.parse")) {
            if (sender instanceof Player) {
                String str = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
                Player player = (Player) sender;
                Optional<ICPlayer> icplayer = Optional.of(ICPlayerFactory.getICPlayer(player));
                Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> {
                    String text = str;
                    try {
                        long unix = System.currentTimeMillis();
                        if (InteractiveChat.chatAltColorCode.isPresent() && player.hasPermission("interactivechat.chatcolor.translate")) {
                            text = ChatColorUtils.translateAlternateColorCodes(InteractiveChat.chatAltColorCode.get(), str);
                        }
                        Component component = Component.text(text);
                        if (InteractiveChat.usePlayerName) {
                            component = PlayernameDisplay.process(component, icplayer, player, unix);
                        }
                        if (InteractiveChat.useItem) {
                            component = ItemDisplay.process(component, icplayer, player, unix);
                        }
                        if (InteractiveChat.useInventory) {
                            component = InventoryDisplay.process(component, icplayer, player, unix);
                        }
                        if (InteractiveChat.useEnder) {
                            component = EnderchestDisplay.process(component, icplayer, player, unix);
                        }
                        component = CustomPlaceholderDisplay.process(component, icplayer, player, InteractiveChat.placeholderList.values(), unix);
                        if (InteractiveChat.clickableCommands) {
                            component = CommandsDisplay.process(component);
                        }
                        if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_16) && InteractiveChat.fontTags) {
                            if (PlayerUtils.hasPermission(player.getUniqueId(), "interactivechat.customfont.translate", true, 250)) {
                                component = ComponentFont.parseFont(component);
                            }
                        }
                        String json = InteractiveChatComponentSerializer.gson().serialize(component);
                        if (json.length() > InteractiveChat.packetStringMaxLength) {
                            InteractiveChatAPI.sendMessageUnprocessed(sender, Component.text(text));
                        } else {
                            InteractiveChatAPI.sendMessageUnprocessed(sender, component);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            } else {
                sender.sendMessage(String.join(" ", Arrays.copyOfRange(args, 1, args.length)));
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("chat")) {
        if (sender.hasPermission("interactivechat.chat")) {
            if (args.length > 1) {
                if (sender instanceof Player) {
                    String message = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
                    PacketContainer packet = InteractiveChat.protocolManager.createPacket(PacketType.Play.Client.CHAT);
                    packet.getStrings().write(0, message);
                    try {
                        InteractiveChat.protocolManager.recieveClientPacket((Player) sender, packet);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } else {
                    sender.sendMessage(InteractiveChat.noConsoleMessage);
                }
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (sender instanceof Player && args.length > 1) {
        Player player = (Player) sender;
        switch(args[0].toLowerCase()) {
            case "viewinv":
                {
                    PlayerData data = InteractiveChat.playerDataManager.getPlayerData(player);
                    String hash = args[1];
                    if (data == null || data.getInventoryDisplayLayout() == 0) {
                        Inventory inv = InteractiveChat.inventoryDisplay.get(hash);
                        if (inv != null) {
                            Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> player.openInventory(inv));
                        } else {
                            player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                        }
                    } else {
                        Inventory inv = InteractiveChat.inventoryDisplay1Upper.get(hash);
                        Inventory inv2 = InteractiveChat.inventoryDisplay1Lower.get(hash);
                        if (inv != null && inv2 != null) {
                            Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> {
                                player.openInventory(inv);
                                InventoryUtils.sendFakePlayerInventory(player, inv2, true, false);
                                InteractiveChat.viewingInv1.put(player.getUniqueId(), hash);
                            });
                        } else {
                            player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                        }
                    }
                    break;
                }
            case "viewender":
                {
                    Inventory inv = InteractiveChat.enderDisplay.get(args[1]);
                    if (inv != null) {
                        Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> player.openInventory(inv));
                    } else {
                        player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                    }
                    break;
                }
            case "viewitem":
                {
                    Inventory inv = InteractiveChat.itemDisplay.get(args[1]);
                    if (inv != null) {
                        Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> player.openInventory(inv));
                    } else {
                        player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                    }
                    break;
                }
            case "viewmap":
                ItemStack map = InteractiveChat.mapDisplay.get(args[1]);
                if (map != null) {
                    Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> MapViewer.showMap(player, map));
                } else {
                    player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                }
                break;
        }
        return true;
    }
    sender.sendMessage(ChatColorUtils.translateAlternateColorCodes('&', Bukkit.spigot().getConfig().getString("messages.unknown-command")));
    return true;
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Player(org.bukkit.entity.Player) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) PacketContainer(com.comphenix.protocol.events.PacketContainer) ArrayList(java.util.ArrayList) UpdaterResponse(com.loohp.interactivechat.updater.Updater.UpdaterResponse) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Component(net.kyori.adventure.text.Component) ItemStack(org.bukkit.inventory.ItemStack) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) Inventory(org.bukkit.inventory.Inventory)

Example 5 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class InteractiveChatAPI method markSender.

/**
 * Marks a message with a tag that InteractiveChat understands which identifies the sender of the message.<br>
 * Only have an effect if UseAccurateSenderParser is enabled in the config.
 *
 * @param message
 * @param sender The {@link UUID} of the {@link Player} or {@link ICPlayer}
 * @return the sender marked message
 * @throws IllegalStateException if a sender is already marked in the given message
 */
public static String markSender(String message, UUID sender) {
    if (InteractiveChat.useAccurateSenderFinder) {
        if (Registry.ID_PATTERN.matcher(message).find()) {
            throw new IllegalStateException("Sender is already marked in the given message: " + message);
        }
        for (ICPlaceholder icplaceholder : InteractiveChat.placeholderList.values()) {
            Pattern placeholder = icplaceholder.getKeyword();
            Matcher matcher = placeholder.matcher(message);
            if (matcher.find()) {
                int start = matcher.start();
                if ((start < 1 || message.charAt(start - 1) != '\\') || (start > 1 && message.charAt(start - 1) == '\\' && message.charAt(start - 2) == '\\')) {
                    String uuidmatch = "<chat=" + sender + ":" + Registry.ID_ESCAPE_PATTERN.matcher(message.substring(matcher.start(), matcher.end())).replaceAll("\\>") + ":>";
                    message = message.substring(0, matcher.start()) + uuidmatch + message.substring(matcher.end());
                    break;
                }
            }
        }
    }
    return message;
}
Also used : Pattern(java.util.regex.Pattern) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Matcher(java.util.regex.Matcher)

Aggregations

ICPlaceholder (com.loohp.interactivechat.objectholders.ICPlaceholder)26 UUID (java.util.UUID)15 Pattern (java.util.regex.Pattern)13 IOException (java.io.IOException)12 Matcher (java.util.regex.Matcher)12 CustomPlaceholder (com.loohp.interactivechat.objectholders.CustomPlaceholder)11 ArrayList (java.util.ArrayList)11 List (java.util.List)10 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)9 ParsePlayer (com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer)8 Component (net.kyori.adventure.text.Component)8 Player (org.bukkit.entity.Player)8 InteractiveChat (com.loohp.interactivechat.InteractiveChat)7 ItemStack (org.bukkit.inventory.ItemStack)7 CustomPlaceholderClickEvent (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent)6 CustomPlaceholderHoverEvent (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent)6 CustomPlaceholderReplaceText (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText)6 BackendInteractiveChatData (com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData)6 ChatColorUtils (com.loohp.interactivechat.utils.ChatColorUtils)6 Field (java.lang.reflect.Field)6