Search in sources :

Example 1 with TextChannel

use of github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class OutboundToDiscordEvents method onAdvancementSend.

@Subscribe(priority = ListenerPriority.HIGHEST)
public void onAdvancementSend(AchievementMessagePostProcessEvent event) {
    if (event.isCancelled()) {
        return;
    }
    Debug.debug("Triggered onAdvancementSend");
    Message message = event.getDiscordMessage();
    if (!message.getContentRaw().contains("<ICA=")) {
        return;
    }
    String text = message.getContentRaw();
    Set<Integer> matches = new LinkedHashSet<>();
    synchronized (RESEND_WITH_ATTACHMENT) {
        for (int key : RESEND_WITH_ATTACHMENT.keySet()) {
            if (text.contains("<ICA=" + key + ">")) {
                matches.add(key);
            }
        }
    }
    event.setCancelled(true);
    DiscordMessageContent content = new DiscordMessageContent(message);
    for (int key : matches) {
        AttachmentData data = RESEND_WITH_ATTACHMENT.remove(key);
        if (data != null) {
            content.addAttachment(data.getName(), data.getData());
        }
    }
    TextChannel destinationChannel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(event.getChannel());
    Debug.debug("onAdvancementSend sending message to discord");
    if (event.isUsingWebhooks()) {
        String webHookUrl = WebhookUtil.getWebhookUrlToUseForChannel(destinationChannel);
        WebhookClient client = WebhookClient.withUrl(webHookUrl);
        if (client == null) {
            throw new NullPointerException("Unable to get the Webhook client URL for the TextChannel " + destinationChannel.getName());
        }
        client.send(content.toWebhookMessageBuilder().setUsername(event.getWebhookName()).setAvatarUrl(event.getWebhookAvatarUrl()).build());
        client.close();
    } else {
        content.toJDAMessageRestAction(destinationChannel).queue();
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) WebhookClient(club.minnced.discord.webhook.WebhookClient) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) DiscordMessageContent(com.loohp.interactivechatdiscordsrvaddon.objectholders.DiscordMessageContent) AttachmentData(com.loohp.interactivechatdiscordsrvaddon.objectholders.AttachmentData) Subscribe(github.scarsz.discordsrv.api.Subscribe)

Example 2 with TextChannel

use of github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class OutboundToDiscordEvents method onDeathMessageSend.

@Subscribe(priority = ListenerPriority.HIGHEST)
public void onDeathMessageSend(DeathMessagePostProcessEvent event) {
    if (event.isCancelled()) {
        return;
    }
    if (!InteractiveChatDiscordSrvAddon.plugin.deathMessageItem) {
        return;
    }
    Debug.debug("Triggered onDeathMessageSend");
    ItemStack item = DEATH_BY.remove(event.getPlayer().getUniqueId());
    if (item == null || item.getType().equals(Material.AIR)) {
        return;
    }
    if (!item.hasItemMeta()) {
        return;
    }
    ItemMeta meta = item.getItemMeta();
    if (meta == null || !meta.hasDisplayName() || meta.getDisplayName().length() <= 0) {
        return;
    }
    Color color = null;
    if (!event.getDiscordMessage().getEmbeds().isEmpty()) {
        color = event.getDiscordMessage().getEmbeds().get(0).getColor();
    }
    if (color == null) {
        color = Color.black;
    }
    Player player = event.getPlayer();
    DiscordMessageContent content = new DiscordMessageContent(ChatColorUtils.stripColor(meta.getDisplayName()), "attachment://Item.png", color);
    try {
        BufferedImage image = ImageGeneration.getItemStackImage(item, ICPlayerFactory.getICPlayer(player), InteractiveChatDiscordSrvAddon.plugin.itemAltAir);
        byte[] itemData = ImageUtils.toArray(image);
        DiscordDescription description = DiscordItemStackUtils.getDiscordDescription(item, player);
        content.addAttachment("Item.png", itemData);
        if (InteractiveChatDiscordSrvAddon.plugin.itemUseTooltipImage) {
            DiscordToolTip discordToolTip = DiscordItemStackUtils.getToolTip(item, player);
            if (!discordToolTip.isBaseItem() || InteractiveChatDiscordSrvAddon.plugin.itemUseTooltipImageOnBaseItem) {
                BufferedImage tooltip = ImageGeneration.getToolTipImage(discordToolTip.getComponents());
                byte[] tooltipData = ImageUtils.toArray(tooltip);
                content.addAttachment("ToolTip.png", tooltipData);
                content.addImageUrl("attachment://ToolTip.png");
            } else {
                content.addDescription(description.getDescription().orElse(null));
            }
        } else {
            content.addDescription(description.getDescription().orElse(null));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    Bukkit.getScheduler().runTaskLaterAsynchronously(InteractiveChat.plugin, () -> {
        Debug.debug("onDeathMessageSend sending item to discord");
        TextChannel destinationChannel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(event.getChannel());
        if (event.isUsingWebhooks()) {
            String webHookUrl = WebhookUtil.getWebhookUrlToUseForChannel(destinationChannel);
            WebhookClient client = WebhookClient.withUrl(webHookUrl);
            if (client == null) {
                throw new NullPointerException("Unable to get the Webhook client URL for the TextChannel " + destinationChannel.getName());
            }
            client.send(content.toWebhookMessageBuilder().setUsername(event.getWebhookName()).setAvatarUrl(event.getWebhookAvatarUrl()).build());
            client.close();
        } else {
            content.toJDAMessageRestAction(destinationChannel).queue();
        }
    }, 5);
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Player(org.bukkit.entity.Player) MineverseChatPlayer(mineverse.Aust1n46.chat.api.MineverseChatPlayer) DiscordDescription(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordDescription) WebhookClient(club.minnced.discord.webhook.WebhookClient) DiscordMessageContent(com.loohp.interactivechatdiscordsrvaddon.objectholders.DiscordMessageContent) Color(java.awt.Color) DiscordToolTip(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordToolTip) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) ItemStack(org.bukkit.inventory.ItemStack) ItemMeta(org.bukkit.inventory.meta.ItemMeta) Subscribe(github.scarsz.discordsrv.api.Subscribe)

Example 3 with TextChannel

use of github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel in project Foundation by kangarko.

the class ItemsAdderHook method sendMessage.

boolean sendMessage(final CommandSender sender, final String channel, final String message) {
    final TextChannel textChannel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(channel);
    // Channel not configured in DiscordSRV config.yml, ignore
    if (textChannel == null) {
        Debugger.debug("discord", "[MC->Discord] Could not find Discord channel '" + channel + "'. Available: " + String.join(", ", getChannels()) + ". Not sending: " + message);
        return false;
    }
    if (sender instanceof Player) {
        Debugger.debug("discord", "[MC->Discord] " + sender.getName() + " send message to '" + channel + "' channel. Message: '" + message + "'");
        final DiscordSRV instance = JavaPlugin.getPlugin(DiscordSRV.class);
        // Dirty: We have to temporarily unset value in DiscordSRV to enable the processChatMessage method to function
        final File file = new File(SimplePlugin.getData().getParent(), "DiscordSRV/config.yml");
        if (file.exists()) {
            final FileConfiguration discordConfig = YamlConfiguration.loadConfiguration(file);
            if (discordConfig != null) {
                final String outMessageKey = "DiscordChatChannelMinecraftToDiscord";
                final boolean outMessageOldValue = discordConfig.getBoolean(outMessageKey);
                discordConfig.set(outMessageKey, true);
                try {
                    instance.processChatMessage((Player) sender, message, channel, false);
                } finally {
                    discordConfig.set(outMessageKey, outMessageOldValue);
                }
            }
        }
    } else {
        Debugger.debug("discord", "[MC->Discord] " + (sender == null ? "No sender " : sender.getName() + " (generic)") + "sent message to '" + channel + "' channel. Message: '" + message + "'");
        DiscordUtil.sendMessage(textChannel, message);
    }
    return true;
}
Also used : FileConfiguration(org.bukkit.configuration.file.FileConfiguration) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) McMMOPlayer(com.gmail.nossr50.datatypes.player.McMMOPlayer) OfflinePlayer(org.bukkit.OfflinePlayer) MPlayer(com.massivecraft.factions.entity.MPlayer) TemporaryPlayer(com.comphenix.protocol.injector.server.TemporaryPlayer) Player(org.bukkit.entity.Player) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) File(java.io.File)

Example 4 with TextChannel

use of github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel in project MissileWars by Leomelonseeds.

the class Arena method endGame.

/**
 * End a MissileWars game with a winning team
 *
 * @param winningTeam the winning team
 */
public void endGame(MissileWarsTeam winningTeam) {
    // Ignore if game isn't running
    if (!running) {
        return;
    }
    MissileWarsPlugin plugin = MissileWarsPlugin.getPlugin();
    // Cancel all tasks
    for (BukkitTask task : tasks) {
        task.cancel();
    }
    running = false;
    resetting = true;
    waitingForTie = false;
    redTeam.stopDeckItems();
    blueTeam.stopDeckItems();
    // Produce winner/discord messages
    TextChannel discordChannel = DiscordSRV.getPlugin().getMainTextChannel();
    String discordMessage;
    String winner;
    // Notify players and discord users of win
    if (winningTeam == null) {
        // Send titles
        redTeam.sendTitle("tie");
        blueTeam.sendTitle("tie");
        // Set notify messages
        discordMessage = ":pencil: A game was tied in arena " + this.getName();
        winner = "&e&lNONE";
    } else if (winningTeam == blueTeam) {
        // Send titles
        blueTeam.sendTitle("victory");
        redTeam.sendTitle("defeat");
        // Set notify messages
        List<String> blueList = new ArrayList<>();
        for (MissileWarsPlayer player : players) {
            if (blueTeam.containsPlayer(player.getMCPlayerId())) {
                blueList.add(player.getMCPlayer().getName());
            }
        }
        String blueWinners = String.join(", ", blueList);
        discordMessage = ":tada: Team **blue** (" + blueWinners + ") has won a game in arena " + this.getName();
        winner = "&9&lBLUE";
    } else {
        // Send titles
        redTeam.sendTitle("victory");
        blueTeam.sendTitle("defeat");
        // Set notify messages
        List<String> redList = new ArrayList<>();
        for (MissileWarsPlayer player : players) {
            if (redTeam.containsPlayer(player.getMCPlayerId())) {
                redList.add(player.getMCPlayer().getName());
            }
        }
        String redWinners = String.join(", ", redList);
        discordMessage = ":tada: Team **red** (" + redWinners + ") has won a game in arena " + this.getName();
        winner = "&c&lRED";
    }
    discordChannel.sendMessage(discordMessage).queue();
    // Setup player variables
    List<String> winningMessages = ConfigUtils.getConfigTextList("messages.classic-end", null, null, null);
    String earnMessage = ConfigUtils.getConfigText("messages.earn-currency", null, null, null);
    FileConfiguration ranksConfig = ConfigUtils.getConfigFile(MissileWarsPlugin.getPlugin().getDataFolder().toString(), "ranks.yml");
    int spawn_missile = ranksConfig.getInt("experience.spawn_missile");
    int use_utility = ranksConfig.getInt("experience.use_utility");
    int kill = ranksConfig.getInt("experience.kill");
    int portal_broken = ranksConfig.getInt("experience.portal_broken");
    int shield_health = ranksConfig.getInt("experience.shield_health");
    int win = ranksConfig.getInt("experience.win");
    int red_portal_amount = (blueTeam.getFirstPortalStatus() ? portal_broken : 0) + (blueTeam.getSecondPortalStatus() ? portal_broken : 0);
    int blue_portal_amount = (redTeam.getFirstPortalStatus() ? portal_broken : 0) + (redTeam.getSecondPortalStatus() ? portal_broken : 0);
    int red_shield_health_amount = ((int) ((100 - blueTeam.getShieldHealth())) / 10) * shield_health;
    int blue_shield_health_amount = ((int) ((100 - redTeam.getShieldHealth())) / 10) * shield_health;
    // Find players with most deaths and kills
    List<MissileWarsPlayer> mostKills = new ArrayList<>();
    List<MissileWarsPlayer> mostDeaths = new ArrayList<>();
    for (MissileWarsPlayer player : players) {
        if (!getTeam(player.getMCPlayerId()).equals("no team")) {
            if (mostKills.isEmpty() || mostKills.get(0).getKills() < player.getKills()) {
                mostKills.clear();
                mostKills.add(player);
            } else if (mostKills.get(0).getKills() == player.getKills()) {
                mostKills.add(player);
            }
            if (mostDeaths.isEmpty() || mostDeaths.get(0).getDeaths() < player.getDeaths()) {
                mostDeaths.clear();
                mostDeaths.add(player);
            } else if (mostDeaths.get(0).getDeaths() == player.getDeaths()) {
                mostDeaths.add(player);
            }
        }
    }
    // Produce most kills/deaths list
    List<String> mostKillsList = new ArrayList<>();
    for (MissileWarsPlayer player : mostKills) {
        mostKillsList.add(ConfigUtils.getFocusName(player.getMCPlayer()));
    }
    String most_kills = String.join(", ", mostKillsList);
    List<String> mostDeathsList = new ArrayList<>();
    for (MissileWarsPlayer player : mostDeaths) {
        mostDeathsList.add(ConfigUtils.getFocusName(player.getMCPlayer()));
    }
    String most_deaths = String.join(", ", mostDeathsList);
    int most_kills_amount = mostKills.isEmpty() ? 0 : mostKills.get(0).getKills();
    int most_deaths_amount = mostDeaths.isEmpty() ? 0 : mostDeaths.get(0).getDeaths();
    Economy econ = MissileWarsPlugin.getPlugin().getEconomy();
    LocalDateTime endTime = LocalDateTime.now();
    long gameTime = Duration.between(startTime, endTime).toSeconds();
    // Update stats for each player
    for (MissileWarsPlayer player : players) {
        player.getMCPlayer().setGameMode(GameMode.SPECTATOR);
        // Send win message
        for (String s : winningMessages) {
            s = s.replaceAll("%umw_winning_team%", winner);
            s = s.replaceAll("%umw_most_kills_amount%", Integer.toString(most_kills_amount));
            s = s.replaceAll("%umw_most_deaths_amount%", Integer.toString(most_deaths_amount));
            s = s.replaceAll("%umw_most_kills%", most_kills);
            s = s.replaceAll("%umw_most_deaths%", most_deaths);
            player.getMCPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', s));
        }
        // -1 = TIE, 0 = LOST, 1 = WIN
        int won = winningTeam == null ? -1 : 0;
        // Calculate currency gain per-game
        int amountEarned = 0;
        int playerAmount = 0;
        int teamAmount = 0;
        UUID uuid = player.getMCPlayerId();
        if (!getTeam(uuid).equals("no team")) {
            playerAmount = spawn_missile * player.getMissiles() + use_utility * player.getUtility() + kill * player.getKills();
            if (blueTeam.containsPlayer(uuid)) {
                teamAmount = blue_portal_amount + blue_shield_health_amount;
                if (winningTeam == blueTeam) {
                    teamAmount += win;
                    won = 1;
                }
            } else {
                teamAmount = red_portal_amount + red_shield_health_amount;
                if (winningTeam == redTeam) {
                    teamAmount += win;
                    won = 1;
                }
            }
            long playTime = Duration.between(player.getJoinTime(), endTime).toSeconds();
            double percentPlayed = (double) playTime / gameTime;
            amountEarned = playerAmount + (int) (percentPlayed * teamAmount);
            // Update player stats
            SQLManager sql = MissileWarsPlugin.getPlugin().getSQL();
            sql.updateClassicStats(uuid, won, 1, player.getKills(), player.getMissiles(), player.getUtility(), player.getDeaths());
            sql.updateWinstreak(uuid, mapType, won);
            sql.updateExp(uuid, amountEarned);
            String earnMessagePlayer = earnMessage.replaceAll("%umw_amount_earned%", Integer.toString(amountEarned));
            player.getMCPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', earnMessagePlayer));
        }
        econ.depositPlayer(player.getMCPlayer(), amountEarned);
    }
    long waitTime = plugin.getConfig().getInt("victory-wait-time") * 20L;
    // Remove all players after a short time or immediately if none exist
    if (plugin.isEnabled() && players.size() > 0) {
        new BukkitRunnable() {

            @Override
            public void run() {
                removePlayers();
                startTime = null;
            }
        }.runTaskLater(plugin, waitTime);
        new BukkitRunnable() {

            @Override
            public void run() {
                resetWorld();
            }
        }.runTaskLater(plugin, waitTime + 40L);
    } else {
        removePlayers();
        resetWorld();
        startTime = null;
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) BukkitTask(org.bukkit.scheduler.BukkitTask) ArrayList(java.util.ArrayList) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) MissileWarsPlugin(com.leomelonseeds.missilewars.MissileWarsPlugin) SQLManager(com.leomelonseeds.missilewars.utilities.SQLManager) FileConfiguration(org.bukkit.configuration.file.FileConfiguration) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) MissileWarsPlayer(com.leomelonseeds.missilewars.teams.MissileWarsPlayer) Economy(net.milkbowl.vault.economy.Economy) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) UUID(java.util.UUID)

Example 5 with TextChannel

use of github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel in project Foundation by kangarko.

the class DiscordListener method sendWebhookMessage.

/**
 * Sends a webhook message from the given sender in case he's a valid Player
 *
 * @param sender
 * @param channelName
 * @param message
 */
protected final void sendWebhookMessage(CommandSender sender, String channelName, String message) {
    final List<TextChannel> channels = this.findChannels(channelName);
    final TextChannel channel = channels.isEmpty() ? null : channels.get(0);
    if (channel == null)
        return;
    // Send the message
    Common.runAsync(() -> {
        try {
            Debugger.debug("discord", "[Minecraft > Discord] Send MC message from '" + channelName + "' to Discord's '" + channel.getName() + "' channel: " + message);
            // You can remove this if you don't want to use webhooks
            if (sender instanceof Player)
                WebhookUtil.deliverMessage(channel, (Player) sender, message);
            else
                channel.sendMessage(message).complete();
        } catch (final ErrorResponseException ex) {
            Debugger.debug("discord", "Unable to send message to Discord channel " + channelName + ", message: " + message);
        }
    });
}
Also used : TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) Player(org.bukkit.entity.Player) ErrorResponseException(github.scarsz.discordsrv.dependencies.jda.api.exceptions.ErrorResponseException)

Aggregations

TextChannel (github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel)12 Player (org.bukkit.entity.Player)7 Subscribe (github.scarsz.discordsrv.api.Subscribe)5 Message (github.scarsz.discordsrv.dependencies.jda.api.entities.Message)5 ArrayList (java.util.ArrayList)4 MissileWarsPlayer (com.leomelonseeds.missilewars.teams.MissileWarsPlayer)3 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)3 DiscordSRV (github.scarsz.discordsrv.DiscordSRV)3 BufferedImage (java.awt.image.BufferedImage)3 IOException (java.io.IOException)3 List (java.util.List)3 UUID (java.util.UUID)3 ItemStack (org.bukkit.inventory.ItemStack)3 WebhookClient (club.minnced.discord.webhook.WebhookClient)2 Component (com.loohp.interactivechat.libs.net.kyori.adventure.text.Component)2 ClickEvent (com.loohp.interactivechat.libs.net.kyori.adventure.text.event.ClickEvent)2 HoverEvent (com.loohp.interactivechat.libs.net.kyori.adventure.text.event.HoverEvent)2 LegacyComponentSerializer (com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer)2 ComponentReplacing (com.loohp.interactivechat.utils.ComponentReplacing)2 CustomStringUtils (com.loohp.interactivechat.utils.CustomStringUtils)2