Search in sources :

Example 6 with Message

use of discord4j.core.object.entity.Message in project KaellyBot by Kaysoro.

the class GuildCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    String pseudo = m.group(1).trim().toLowerCase();
    String serverName = null;
    if (Pattern.compile("\\s+-serv\\s+").matcher(pseudo).find()) {
        String[] split = pseudo.split("\\s+-serv\\s+");
        pseudo = split[0];
        serverName = split[1];
    }
    StringBuilder url;
    try {
        url = new StringBuilder(Translator.getLabel(lg, "game.url")).append(Translator.getLabel(lg, "guild.url")).append("?").append(forPseudo).append(URLEncoder.encode(pseudo, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        ExceptionManager.manageException(e, message, this, lg);
        return;
    }
    if (serverName != null) {
        ServerUtils.ServerQuery serverQuery = ServerUtils.getServerDofusFromName(serverName, lg);
        if (serverQuery.hasSucceed()) {
            url.append("&").append(forServer).append(serverQuery.getServer());
        } else {
            serverQuery.getExceptions().stream().forEach(e -> e.throwException(message, this, lg, serverQuery.getServersFound()));
            return;
        }
    }
    try {
        Document doc = JSoupManager.getDocument(url.toString());
        Elements elems = doc.getElementsByClass("ak-bg-odd");
        elems.addAll(doc.getElementsByClass("ak-bg-even"));
        if (!elems.isEmpty()) {
            // on boucle jusqu'à temps de trouver la bonne guilde (ie la plus proche du nom donnée)
            List<String> result = new ArrayList<>();
            List<String> servers = new ArrayList<>();
            for (Element element : elems) if (pseudo.equals(element.child(1).text().trim().toLowerCase())) {
                result.add(element.child(1).select("a").attr("href"));
                servers.add(element.child(3).text());
            }
            if (result.size() == 1) {
                DofusGuild guildPage = DofusGuild.getDofusGuild(Translator.getLabel(lg, "game.url") + result.get(0), lg);
                message.getChannel().flatMap(chan -> chan.createEmbed(guildPage.decorateEmbedObject(lg))).subscribe();
            } else if (result.size() > 1)
                tooMuchGuilds.throwException(message, this, lg, servers);
            else
                notFoundGuild.throwException(message, this, lg);
        } else
            notFoundGuild.throwException(message, this, lg);
    } catch (IOException e) {
        ExceptionManager.manageIOException(e, message, this, lg, BasicDiscordException.GUILDPAGE_INACCESSIBLE);
    } catch (Exception e) {
        ExceptionManager.manageException(e, message, this, lg);
    }
}
Also used : Language(enums.Language) JSoupManager(util.JSoupManager) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) ServerUtils(util.ServerUtils) IOException(java.io.IOException) exceptions(exceptions) ArrayList(java.util.ArrayList) URLEncoder(java.net.URLEncoder) List(java.util.List) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) Document(org.jsoup.nodes.Document) Element(org.jsoup.nodes.Element) Elements(org.jsoup.select.Elements) Translator(util.Translator) Pattern(java.util.regex.Pattern) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DofusGuild(data.DofusGuild) DofusGuild(data.DofusGuild) Element(org.jsoup.nodes.Element) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServerUtils(util.ServerUtils) IOException(java.io.IOException) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 7 with Message

use of discord4j.core.object.entity.Message in project KaellyBot by Kaysoro.

the class HelpCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    String prefix = getPrefixMdEscaped(message);
    StringBuilder st = new StringBuilder();
    List<String> messages = new ArrayList<>();
    boolean argumentFound = m.group(1) != null && m.group(1).replaceAll("^\\s+", "").length() > 0;
    for (Command command : CommandManager.getCommands()) if (command.isPublic() && !command.isAdmin() && (!command.isHidden() || argumentFound) && (message.getChannel().block() instanceof PrivateChannel || !command.isForbidden(Guild.getGuild(message.getGuild().block())))) {
        if (!argumentFound) {
            String helpCmd = command.help(lg, prefix) + "\n";
            if (st.length() + helpCmd.length() > Message.MAX_CONTENT_LENGTH) {
                messages.add(st.toString());
                st.setLength(0);
            }
            st.append(helpCmd);
        } else if (command.getName().equals(m.group(1).trim())) {
            st.append(command.helpDetailed(lg, prefix));
            break;
        }
    }
    if (st.length() > 0)
        messages.add(st.toString());
    if (argumentFound && messages.isEmpty())
        notFoundCmd.throwException(message, this, lg);
    else
        for (String msg : messages) message.getChannel().flatMap(chan -> chan.createMessage(msg)).subscribe();
}
Also used : PrivateChannel(discord4j.core.object.entity.channel.PrivateChannel) Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) NotFoundDiscordException(exceptions.NotFoundDiscordException) Constants(data.Constants) Guild(data.Guild) ArrayList(java.util.ArrayList) List(java.util.List) Matcher(java.util.regex.Matcher) DiscordException(exceptions.DiscordException) Message(discord4j.core.object.entity.Message) PrivateChannel(discord4j.core.object.entity.channel.PrivateChannel) CommandManager(commands.CommandManager) Command(commands.model.Command) Translator(util.Translator) AbstractCommand(commands.model.AbstractCommand) Command(commands.model.Command) ArrayList(java.util.ArrayList)

Example 8 with Message

use of discord4j.core.object.entity.Message in project KaellyBot by Kaysoro.

the class JobCommand method request.

@Override
protected void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    String content = m.group(1).trim().replaceAll(",", "");
    // Filter Initialisation
    Optional<discord4j.core.object.entity.Guild> guild = message.getGuild().blockOptional();
    Optional<Member> user = message.getAuthorAsMember().blockOptional();
    if (guild.isPresent() && user.isPresent()) {
        ServerDofus server = ServerUtils.getDofusServerFrom(Guild.getGuild(guild.get()), message.getChannel().block());
        // Concerned user is the author?
        if (Pattern.compile("^<@[!|&]?\\d+>").matcher(content).find()) {
            content = content.replaceFirst("<@[!|&]?\\d+>", "").trim();
            Optional<Snowflake> memberId = message.getUserMentionIds().stream().findFirst();
            if (!memberId.isPresent()) {
                BasicDiscordException.USER_NEEDED.throwException(message, this, lg);
                return;
            }
            user = guild.get().getMemberById(memberId.get()).blockOptional();
        }
        // user data consultation
        ServerUtils.ServerQuery serverQuery = ServerUtils.getServerDofusFromName(content, lg);
        if (!serverQuery.getServersFound().isEmpty() && Pattern.compile("(.+)").matcher(content).matches() || content.isEmpty()) {
            if (serverQuery.hasSucceed())
                server = serverQuery.getServer();
            else if (server == null) {
                if (!content.isEmpty())
                    serverQuery.getExceptions().forEach(e -> e.throwException(message, this, lg, serverQuery.getServersFound()));
                else
                    notFoundServer.throwException(message, this, lg);
                return;
            }
            if (user.isPresent()) {
                List<EmbedCreateSpec> embeds = JobUser.getJobsFromUser(user.get(), server, lg);
                for (EmbedCreateSpec embed : embeds) message.getChannel().flatMap(chan -> chan.createEmbed(embed)).subscribe();
            }
        } else // Data recording
        if ((m = Pattern.compile("-list|(-all|\\p{L}+(?:\\s+\\p{L}+)*)\\s+(\\d{1,3})(\\s+.+)?").matcher(content)).matches()) {
            if (user.isPresent() && message.getAuthor().isPresent() && user.get().getId().equals(message.getAuthor().get().getId())) {
                if (!m.group(0).equals("-list")) {
                    // Data Parsing and exceptions processing
                    Set<Job> jobs;
                    StringBuilder found = new StringBuilder();
                    StringBuilder notFound = new StringBuilder();
                    StringBuilder tooMuch = new StringBuilder();
                    if (!m.group(1).equals("-all")) {
                        jobs = new HashSet<>();
                        String[] proposals = m.group(1).split("\\s+");
                        for (String proposal : proposals) if (!proposal.trim().isEmpty()) {
                            List<Job> tmp = getJob(lg, proposal);
                            if (tmp.size() == 1) {
                                jobs.add(tmp.get(0));
                                found.append(tmp.get(0).getLabel(lg)).append(", ");
                            } else if (tmp.isEmpty())
                                notFound.append("*").append(proposal).append("*, ");
                            else
                                tooMuch.append("*").append(proposal).append("*, ");
                        }
                    } else
                        jobs = new HashSet<>(Arrays.asList(Job.values()));
                    // Check existing jobs
                    if (jobs.isEmpty()) {
                        message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "job.noone"))).subscribe();
                        return;
                    }
                    if (found.length() > 0)
                        found.setLength(found.length() - 2);
                    if (notFound.length() > 0)
                        notFound.setLength(notFound.length() - 2);
                    if (tooMuch.length() > 0)
                        tooMuch.setLength(tooMuch.length() - 2);
                    int level = Integer.parseInt(m.group(2));
                    if (m.group(3) != null) {
                        ServerUtils.ServerQuery query = ServerUtils.getServerDofusFromName(m.group(3), lg);
                        if (serverQuery.hasSucceed())
                            server = serverQuery.getServer();
                        else
                            serverQuery.getExceptions().forEach(e -> e.throwException(message, this, lg, query.getServersFound()));
                    } else if (server == null) {
                        notFoundServer.throwException(message, this, lg);
                        return;
                    }
                    for (Job job : jobs) if (JobUser.containsKeys(user.get().getId().asLong(), server, job))
                        JobUser.get(user.get().getId().asLong(), server, job).get(0).setLevel(level);
                    else
                        new JobUser(user.get().getId().asLong(), server, job, level).addToDatabase();
                    StringBuilder sb = new StringBuilder();
                    if (jobs.size() < Job.values().length)
                        sb.append(Translator.getLabel(lg, level > 0 ? "job.save" : "job.reset").replace("{jobs}", found.toString()));
                    else
                        sb.append(Translator.getLabel(lg, level > 0 ? "job.all_save" : "job.all_reset"));
                    if (notFound.length() > 0)
                        sb.append("\n").append(Translator.getLabel(lg, "job.not_found").replace("{jobs}", notFound.toString()));
                    if (tooMuch.length() > 0)
                        sb.append("\n").append(Translator.getLabel(lg, "job.too_much").replace("{jobs}", tooMuch.toString()));
                    final String CONTENT = sb.toString();
                    message.getChannel().flatMap(chan -> chan.createMessage(CONTENT)).subscribe();
                } else {
                    String sb = Translator.getLabel(lg, "job.list") + "\n" + getJobsList(lg);
                    message.getChannel().flatMap(chan -> chan.createMessage(sb)).subscribe();
                }
            } else
                badUse.throwException(message, this, lg);
        } else if ((m = Pattern.compile("(?:>\\s*(\\d{1,3})\\s+)?(\\p{L}+(?:\\s+\\p{L}+)*)").matcher(content)).matches()) {
            List<String> proposals = new LinkedList<>(Arrays.asList(m.group(2).split("\\s+")));
            if (proposals.size() > 1) {
                String potentialServer = proposals.get(proposals.size() - 1);
                ServerUtils.ServerQuery query = ServerUtils.getServerDofusFromName(potentialServer, lg);
                if (query.hasSucceed()) {
                    server = query.getServer();
                    proposals.remove(potentialServer);
                } else {
                    query.getExceptions().forEach(e -> e.throwException(message, this, lg, query.getServersFound()));
                    return;
                }
            } else if (server == null) {
                notFoundServer.throwException(message, this, lg);
                return;
            }
            Set<Job> jobs = new HashSet<>();
            for (String proposal : proposals) if (jobs.size() < MAX_JOB_DISPLAY) {
                if (!proposal.trim().isEmpty()) {
                    List<Job> tmp = getJob(lg, proposal);
                    if (tmp.size() == 1)
                        jobs.add(tmp.get(0));
                }
            }
            // Check if a job is found
            if (jobs.isEmpty()) {
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "job.noone"))).subscribe();
                return;
            }
            int level = -1;
            if (m.group(1) != null)
                level = Integer.parseInt(m.group(1));
            List<EmbedCreateSpec> embeds = JobUser.getJobsFromFilters(guild.get().getMembers().collectList().blockOptional().orElse(Collections.emptyList()), server, jobs, level, guild.get(), lg);
            for (EmbedCreateSpec embed : embeds) message.getChannel().flatMap(chan -> chan.createEmbed(embed)).subscribe();
        } else
            badUse.throwException(message, this, lg);
    }
}
Also used : Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) java.util(java.util) AbstractCommand(commands.model.AbstractCommand) ServerUtils(util.ServerUtils) Job(enums.Job) NotFoundDiscordException(exceptions.NotFoundDiscordException) Snowflake(discord4j.common.util.Snowflake) Collectors(java.util.stream.Collectors) Guild(data.Guild) Normalizer(java.text.Normalizer) ServerDofus(data.ServerDofus) Consumer(java.util.function.Consumer) Matcher(java.util.regex.Matcher) DiscordException(exceptions.DiscordException) Message(discord4j.core.object.entity.Message) Member(discord4j.core.object.entity.Member) JobUser(data.JobUser) EmbedCreateSpec(discord4j.core.spec.EmbedCreateSpec) BasicDiscordException(exceptions.BasicDiscordException) Translator(util.Translator) Pattern(java.util.regex.Pattern) ServerDofus(data.ServerDofus) Guild(data.Guild) JobUser(data.JobUser) Snowflake(discord4j.common.util.Snowflake) Job(enums.Job) Member(discord4j.core.object.entity.Member) EmbedCreateSpec(discord4j.core.spec.EmbedCreateSpec) ServerUtils(util.ServerUtils)

Example 9 with Message

use of discord4j.core.object.entity.Message in project KaellyBot by Kaysoro.

the class RSSCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    // On check si la personne a bien les droits pour exécuter cette commande
    if (isUserHasEnoughRights(message)) {
        String value = m.group(1);
        String guildId = message.getGuild().blockOptional().map(Guild::getId).map(Snowflake::asString).orElse("");
        String channelId = message.getChannel().blockOptional().map(MessageChannel::getId).map(Snowflake::asString).orElse("");
        if (value.matches("\\s+true") || value.matches("\\s+0") || value.matches("\\s+on")) {
            if (!RSSFinder.getRSSFinders().containsKey(channelId)) {
                new RSSFinder(guildId, channelId).addToDatabase();
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "rss.request.1").replace("{game.url}", Translator.getLabel(lg, "game.url")))).subscribe();
            } else
                rssFound.throwException(message, this, lg);
        } else if (value.matches("\\s+false") || value.matches("\\s+1") || value.matches("\\s+off"))
            if (RSSFinder.getRSSFinders().containsKey(channelId)) {
                RSSFinder.getRSSFinders().get(channelId).removeToDatabase();
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "rss.request.2").replace("{game.url}", Translator.getLabel(lg, "game.url")))).subscribe();
            } else
                rssNotFound.throwException(message, this, lg);
        else
            badUse.throwException(message, this, lg);
    } else
        BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
}
Also used : Guild(discord4j.core.object.entity.Guild) Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) Translator(util.Translator) Constants(data.Constants) Snowflake(discord4j.common.util.Snowflake) exceptions(exceptions) RSSFinder(finders.RSSFinder) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) RSSFinder(finders.RSSFinder) Guild(discord4j.core.object.entity.Guild)

Example 10 with Message

use of discord4j.core.object.entity.Message in project KaellyBot by Kaysoro.

the class TwitterCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    // On check si la personne a bien les droits pour exécuter cette commande
    if (isUserHasEnoughRights(message)) {
        String value = m.group(1);
        Long guildId = message.getGuild().blockOptional().map(Guild::getId).map(Snowflake::asLong).orElse(0L);
        Long channelId = message.getChannel().blockOptional().map(MessageChannel::getId).map(Snowflake::asLong).orElse(0L);
        if (value.matches("\\s+true") || value.matches("\\s+0") || value.matches("\\s+on")) {
            if (!TwitterFinder.getTwitterChannels().containsKey(channelId)) {
                new TwitterFinder(guildId, channelId).addToDatabase();
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "twitter.request.1").replace("{twitter.name}", Translator.getLabel(lg, "twitter.name")))).subscribe();
            } else
                twitterFound.throwException(message, this, lg);
        } else if (value.matches("\\s+false") || value.matches("\\s+1") || value.matches("\\s+off")) {
            if (TwitterFinder.getTwitterChannels().containsKey(channelId)) {
                TwitterFinder.getTwitterChannels().get(channelId).removeToDatabase();
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "twitter.request.2").replace("{twitter.name}", Translator.getLabel(lg, "twitter.name")))).subscribe();
            } else
                twitterNotFound.throwException(message, this, lg);
        } else
            badUse.throwException(message, this, lg);
    } else
        BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
}
Also used : Guild(discord4j.core.object.entity.Guild) Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) TwitterFinder(finders.TwitterFinder) Translator(util.Translator) Snowflake(discord4j.common.util.Snowflake) exceptions(exceptions) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) Guild(discord4j.core.object.entity.Guild) TwitterFinder(finders.TwitterFinder)

Aggregations

Message (discord4j.core.object.entity.Message)20 MessageCreateEvent (discord4j.core.event.domain.message.MessageCreateEvent)17 Language (enums.Language)17 Translator (util.Translator)17 Matcher (java.util.regex.Matcher)15 AbstractCommand (commands.model.AbstractCommand)14 List (java.util.List)9 exceptions (exceptions)7 EmbedCreateSpec (discord4j.core.spec.EmbedCreateSpec)5 ArrayList (java.util.ArrayList)5 Collectors (java.util.stream.Collectors)5 ServerUtils (util.ServerUtils)5 Command (commands.model.Command)4 Guild (data.Guild)4 Snowflake (discord4j.common.util.Snowflake)4 Pattern (java.util.regex.Pattern)4 Constants (data.Constants)3 ServerDofus (data.ServerDofus)3 MessageChannel (discord4j.core.object.entity.channel.MessageChannel)3 IOException (java.io.IOException)3