<commit_before>package stream.flarebot.flarebot.util;

import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.exceptions.ErrorResponseException;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import stream.flarebot.flarebot.FlareBot;
import stream.flarebot.flarebot.commands.Command;

import java.awt.Color;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.Clock;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MessageUtils {

    private static FlareBot flareBot = FlareBot.getInstance();

    private static final Pattern INVITE_REGEX = Pattern
            .compile("(?i)discord(\\.(com|gg|io|me|net|org|xyz)|app\\.com/invite)/[a-z0-9-_.]+");
    private static final Pattern LINK_REGEX = Pattern
            .compile("((http(s)?://)(www\\.)?)[a-zA-Z0-9-]+\\.[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)?/?(.+)?");
    private static final Pattern YOUTUBE_LINK_REGEX = Pattern
            .compile("(http(s)?://)?(www\\.)?youtu(be\\.com)?(\\.be)?/(watch\\?v=)?[a-zA-Z0-9-_]+");

    private static final Pattern ESCAPE_MARKDOWN = Pattern.compile("[`~*_\\\\]");
    private static final Pattern SPACE = Pattern.compile(" ");

    private static final String ZERO_WIDTH_SPACE = "\u200B";

    private static JDA cachedJDA;
    private static EmbedBuilder defaultEmbed;

    public static void sendPM(User user, String message) {
        try {
            user.openPrivateChannel().complete()
                    .sendMessage(message.substring(0, Math.min(message.length(), 1999))).queue();
        } catch (ErrorResponseException ignored) {
        }
    }

    public static void sendPM(TextChannel channel, User user, String message) {
        try {
            user.openPrivateChannel().complete()
                    .sendMessage(message.substring(0, Math.min(message.length(), 1999))).queue();
        } catch (ErrorResponseException e) {
            channel.sendMessage(message).queue();
        }
    }

    public static void sendPM(TextChannel channel, User user, EmbedBuilder message) {
        try {
            user.openPrivateChannel().complete().sendMessage(message.build()).complete();
        } catch (ErrorResponseException e) {
            channel.sendMessage(message.build()).queue();
        }
    }

    public static void sendException(String s, Throwable e, TextChannel channel) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String trace = sw.toString();
        pw.close();
        sendErrorMessage(getEmbed().setDescription(s + "\n**Stack trace**: " + paste(trace)), channel);
    }

    public static void sendFatalException(String s, Throwable e, TextChannel channel) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String trace = sw.toString();
        pw.close();
        channel.sendMessage(new MessageBuilder().append(
                flareBot.getOfficialGuild().getRoleById(Constants.DEVELOPER_ID).getAsMention())
                .setEmbed(getEmbed().setColor(Color.red).setDescription(s + "\n**Stack trace**: " + paste(trace))
                        .build()).build()).queue();
    }

    public static String paste(String trace) {
        if (flareBot.getPasteKey() == null || flareBot.getPasteKey().isEmpty()) {
            FlareBot.LOGGER.warn("Paste server key is missing! Pastes will not work!");
            return null;
        }
        try {
            Response response = WebUtils.post(new Request.Builder().url("https://paste.flarebot.stream/documents")
                    .addHeader("Authorization", flareBot.getPasteKey()).post(RequestBody
                            .create(WebUtils.APPLICATION_JSON, trace)));
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            ResponseBody body = response.body();
            if (body != null) {
                String key = new JSONObject(body.string()).getString("key");
                body.close();
                return "https://paste.flarebot.stream/" + key;
            } else {
                FlareBot.LOGGER.error("Local instance of hastebin is down");
                return null;
            }
        } catch (IOException | JSONException e) {
            FlareBot.LOGGER.error("Could not make POST request to paste!", e);
            return null;
        }
    }

    public static void editMessage(Message message, String content) {
        message.editMessage(content).queue();
    }

    public static EmbedBuilder getEmbed() {
        if (cachedJDA == null || cachedJDA.getStatus() != JDA.Status.CONNECTED)
            cachedJDA = flareBot.getClient();

        if (defaultEmbed == null)
            defaultEmbed = new EmbedBuilder().setColor(ColorUtils.FLAREBOT_BLUE);
        
        // We really need to PR getAuthor and things into EmbedBuilder.
        if (cachedJDA != null)
            defaultEmbed.setAuthor("FlareBot", "https://flarebot.stream", cachedJDA.getSelfUser().getEffectiveAvatarUrl());
        
        // probably need a better way to reset but eh
        defaultEmbed.setThumbnail(null).setDescription(null).clearFields().setImage(null)
                .setFooter(null, null).setTimestamp(null);

        return defaultEmbed.setColor(ColorUtils.FLAREBOT_BLUE);
    }

    public static EmbedBuilder getEmbed(User user) {
        return getEmbed().setFooter("Requested by @" + getTag(user), user.getEffectiveAvatarUrl());
    }

    public static String getTag(User user) {
        return user.getName() + '#' + user.getDiscriminator();
    }

    public static String getUserAndId(User user) {
        return getTag(user) + " (" + user.getId() + ")";
    }

    public static String getAvatar(User user) {<commit_msg>Reset title<commit_after>package stream.flarebot.flarebot.util;

import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.exceptions.ErrorResponseException;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import stream.flarebot.flarebot.FlareBot;
import stream.flarebot.flarebot.commands.Command;

import java.awt.Color;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.Clock;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MessageUtils {

    private static FlareBot flareBot = FlareBot.getInstance();

    private static final Pattern INVITE_REGEX = Pattern
            .compile("(?i)discord(\\.(com|gg|io|me|net|org|xyz)|app\\.com/invite)/[a-z0-9-_.]+");
    private static final Pattern LINK_REGEX = Pattern
            .compile("((http(s)?://)(www\\.)?)[a-zA-Z0-9-]+\\.[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)?/?(.+)?");
    private static final Pattern YOUTUBE_LINK_REGEX = Pattern
            .compile("(http(s)?://)?(www\\.)?youtu(be\\.com)?(\\.be)?/(watch\\?v=)?[a-zA-Z0-9-_]+");

    private static final Pattern ESCAPE_MARKDOWN = Pattern.compile("[`~*_\\\\]");
    private static final Pattern SPACE = Pattern.compile(" ");

    private static final String ZERO_WIDTH_SPACE = "\u200B";

    private static JDA cachedJDA;
    private static EmbedBuilder defaultEmbed;

    public static void sendPM(User user, String message) {
        try {
            user.openPrivateChannel().complete()
                    .sendMessage(message.substring(0, Math.min(message.length(), 1999))).queue();
        } catch (ErrorResponseException ignored) {
        }
    }

    public static void sendPM(TextChannel channel, User user, String message) {
        try {
            user.openPrivateChannel().complete()
                    .sendMessage(message.substring(0, Math.min(message.length(), 1999))).queue();
        } catch (ErrorResponseException e) {
            channel.sendMessage(message).queue();
        }
    }

    public static void sendPM(TextChannel channel, User user, EmbedBuilder message) {
        try {
            user.openPrivateChannel().complete().sendMessage(message.build()).complete();
        } catch (ErrorResponseException e) {
            channel.sendMessage(message.build()).queue();
        }
    }

    public static void sendException(String s, Throwable e, TextChannel channel) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String trace = sw.toString();
        pw.close();
        sendErrorMessage(getEmbed().setDescription(s + "\n**Stack trace**: " + paste(trace)), channel);
    }

    public static void sendFatalException(String s, Throwable e, TextChannel channel) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String trace = sw.toString();
        pw.close();
        channel.sendMessage(new MessageBuilder().append(
                flareBot.getOfficialGuild().getRoleById(Constants.DEVELOPER_ID).getAsMention())
                .setEmbed(getEmbed().setColor(Color.red).setDescription(s + "\n**Stack trace**: " + paste(trace))
                        .build()).build()).queue();
    }

    public static String paste(String trace) {
        if (flareBot.getPasteKey() == null || flareBot.getPasteKey().isEmpty()) {
            FlareBot.LOGGER.warn("Paste server key is missing! Pastes will not work!");
            return null;
        }
        try {
            Response response = WebUtils.post(new Request.Builder().url("https://paste.flarebot.stream/documents")
                    .addHeader("Authorization", flareBot.getPasteKey()).post(RequestBody
                            .create(WebUtils.APPLICATION_JSON, trace)));
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            ResponseBody body = response.body();
            if (body != null) {
                String key = new JSONObject(body.string()).getString("key");
                body.close();
                return "https://paste.flarebot.stream/" + key;
            } else {
                FlareBot.LOGGER.error("Local instance of hastebin is down");
                return null;
            }
        } catch (IOException | JSONException e) {
            FlareBot.LOGGER.error("Could not make POST request to paste!", e);
            return null;
        }
    }

    public static void editMessage(Message message, String content) {
        message.editMessage(content).queue();
    }

    public static EmbedBuilder getEmbed() {
        if (cachedJDA == null || cachedJDA.getStatus() != JDA.Status.CONNECTED)
            cachedJDA = flareBot.getClient();

        if (defaultEmbed == null)
            defaultEmbed = new EmbedBuilder().setColor(ColorUtils.FLAREBOT_BLUE);
        
        // We really need to PR getAuthor and things into EmbedBuilder.
        if (cachedJDA != null)
            defaultEmbed.setAuthor("FlareBot", "https://flarebot.stream", cachedJDA.getSelfUser().getEffectiveAvatarUrl());
        
        // probably need a better way to reset but eh
        defaultEmbed.setTitle(null).setThumbnail(null).setDescription(null).clearFields().setImage(null)
                .setFooter(null, null).setTimestamp(null);

        return defaultEmbed.setColor(ColorUtils.FLAREBOT_BLUE);
    }

    public static EmbedBuilder getEmbed(User user) {
        return getEmbed().setFooter("Requested by @" + getTag(user), user.getEffectiveAvatarUrl());
    }

    public static String getTag(User user) {
        return user.getName() + '#' + user.getDiscriminator();
    }

    public static String getUserAndId(User user) {
        return getTag(user) + " (" + user.getId() + ")";
    }

    public static String getAvatar(User user) {
{'fraction_non_alphanumeric': 0.1308360895315745, 'fraction_numerical': 0.00569186985616491, 'mean_word_length': 2.825242718446602, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 6, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4152488', 'n_tokens_mistral': 3865, 'n_tokens_neox': 3684, 'n_words': 763}