Search in sources :

Example 11 with MessageCreateEvent

use of discord4j.core.event.domain.message.MessageCreateEvent in project KaellyBot by Kaysoro.

the class ServerCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    Guild guild = Guild.getGuild(message.getGuild().block());
    MessageChannel channel = message.getChannel().block();
    if (m.group(1) != null) {
        String serverName = m.group(1).toLowerCase().trim();
        if (serverName.equals("-list")) {
            String sb = Translator.getLabel(lg, "server.list") + "\n" + getServersList(lg);
            message.getChannel().flatMap(chan -> chan.createMessage(sb)).subscribe();
            return;
        }
        if (isUserHasEnoughRights(message)) {
            if (!serverName.startsWith("-channel")) {
                ServerUtils.ServerQuery query = ServerUtils.getServerDofusFromName(serverName, lg);
                if (query.hasSucceed()) {
                    guild.setServer(query.getServer());
                    message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "server.request.1").replace("{game}", Constants.game.getName()) + " " + guild.getName() + " " + Translator.getLabel(lg, "server.request.2") + " " + query.getServer().getLabel(lg) + ".")).subscribe();
                } else
                    query.getExceptions().forEach(exception -> exception.throwException(message, this, lg, query.getServersFound()));
            } else {
                ServerUtils.ServerQuery query = ServerUtils.getServerDofusFromName(serverName.replace("-channel", "").trim(), lg);
                ChannelServer channelServer = ChannelServer.getChannelServers().get(channel.getId().asLong());
                if (query.hasSucceed()) {
                    if (channelServer != null) {
                        if (channelServer.getServer().getName().equals(query.getServer().getName())) {
                            channelServer.removeToDatabase();
                            channel.createMessage(((GuildMessageChannel) channel).getName() + " " + Translator.getLabel(lg, "server.request.4").replace("{server}", guild.getServerDofus().toString())).subscribe();
                        } else {
                            channelServer.setServer(query.getServer());
                            message.getChannel().flatMap(salon -> salon.createMessage(((GuildMessageChannel) channel).getName() + " " + Translator.getLabel(lg, "server.request.4").replace("{server}", query.getServer().toString()))).subscribe();
                        }
                    } else {
                        final ChannelServer CHAN = new ChannelServer(query.getServer(), channel.getId().asLong());
                        CHAN.addToDatabase();
                        message.getChannel().flatMap(salon -> salon.createMessage(((GuildMessageChannel) channel).getName() + " " + Translator.getLabel(lg, "server.request.4").replace("{server}", query.getServer().toString()))).subscribe();
                    }
                } else
                    query.getExceptions().forEach(exception -> exception.throwException(message, this, lg, query.getServersFound()));
            }
        } else
            BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
    } else {
        String text = "**" + guild.getName() + "** " + (guild.getServerDofus() != null ? Translator.getLabel(lg, "server.request.4").replace("{server}", guild.getServerDofus().getLabel(lg)) : Translator.getLabel(lg, "server.request.5")).replace("{game}", Constants.game.getName());
        ChannelServer channelServer = ChannelServer.getChannelServers().get(channel.getId().asLong());
        if (channelServer != null)
            text += "\n" + Translator.getLabel(lg, "server.request.6").replace("{channel}", ((GuildMessageChannel) channel).getName()).replace("{server}", channelServer.getServer().getLabel(lg));
        channel.createMessage(text).subscribe();
    }
}
Also used : Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) data(data) ServerUtils(util.ServerUtils) Collectors(java.util.stream.Collectors) List(java.util.List) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) Game(enums.Game) BasicDiscordException(exceptions.BasicDiscordException) Translator(util.Translator) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) ServerUtils(util.ServerUtils) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel)

Example 12 with MessageCreateEvent

use of discord4j.core.event.domain.message.MessageCreateEvent in project KaellyBot by Kaysoro.

the class AbstractCommand method request.

@Override
public final void request(MessageCreateEvent event, Message message) {
    Language lg = Translator.getLanguageFrom(message.getChannel().block());
    try {
        Matcher m = getMatcher(message);
        boolean isFound = m.find();
        // Caché si la fonction est désactivée/réservée aux admin et que l'auteur n'est pas super-admin
        if ((!isPublic() || isAdmin()) && message.getAuthor().map(user -> user.getId().asLong() != Constants.authorId).orElse(false))
            return;
        // S'il s'agit d'une demande d'aide...
        if (message.getContent().matches(Pattern.quote(getPrefix(message)) + getName() + "\\s+help")) {
            message.getChannel().flatMap(chan -> chan.createMessage(helpDetailed(lg, getPrefix(message)))).subscribe();
            return;
        }
        // La commande est trouvée
        if (isFound) {
            // Mais n'est pas utilisable en MP
            MessageChannel channel = message.getChannel().block();
            if (!isUsableInMP() && channel instanceof PrivateChannel) {
                BasicDiscordException.NOT_USABLE_IN_MP.throwException(message, this, lg);
                return;
            } else // Mais est désactivée par la guilde
            if (!(channel instanceof PrivateChannel) && message.getAuthor().map(user -> user.getId().asLong() != Constants.authorId).orElse(false) && isForbidden(Guild.getGuild(message.getGuild().block()))) {
                BasicDiscordException.COMMAND_FORBIDDEN.throwException(message, this, lg);
                return;
            }
        } else // Mais est mal utilisée
        if (message.getContent().startsWith(getPrefix(message) + getName())) {
            badUse.throwException(message, this, lg);
            return;
        }
        if (isFound)
            request(event, message, m, lg);
    } catch (Exception e) {
        BasicDiscordException.UNKNOWN_ERROR.throwException(message, this, lg);
        Reporter.report(e);
        LOG.error("request", e);
    }
}
Also used : Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) Logger(org.slf4j.Logger) TextChannel(discord4j.core.object.entity.channel.TextChannel) LoggerFactory(org.slf4j.LoggerFactory) Permission(discord4j.rest.util.Permission) Constants(data.Constants) Snowflake(discord4j.common.util.Snowflake) Guild(data.Guild) PermissionSet(discord4j.rest.util.PermissionSet) Reporter(util.Reporter) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) Matcher(java.util.regex.Matcher) BadUseCommandDiscordException(exceptions.BadUseCommandDiscordException) DiscordException(exceptions.DiscordException) PrivateChannel(discord4j.core.object.entity.channel.PrivateChannel) BasicDiscordException(exceptions.BasicDiscordException) Translator(util.Translator) Pattern(java.util.regex.Pattern) discord4j.core.object.entity(discord4j.core.object.entity) PrivateChannel(discord4j.core.object.entity.channel.PrivateChannel) Language(enums.Language) MessageChannel(discord4j.core.object.entity.channel.MessageChannel) GuildMessageChannel(discord4j.core.object.entity.channel.GuildMessageChannel) Matcher(java.util.regex.Matcher) BadUseCommandDiscordException(exceptions.BadUseCommandDiscordException) DiscordException(exceptions.DiscordException) BasicDiscordException(exceptions.BasicDiscordException)

Example 13 with MessageCreateEvent

use of discord4j.core.event.domain.message.MessageCreateEvent in project KaellyBot by Kaysoro.

the class RandomCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    Random r = new Random();
    Matcher tmp;
    if (m.group(1) == null || m.group(1).trim().isEmpty()) {
        boolean value = r.nextBoolean();
        message.getChannel().flatMap(chan -> chan.createMessage(value ? Translator.getLabel(lg, "random.request.1") : Translator.getLabel(lg, "random.request.2") + " !")).subscribe();
    } else if (m.group(1).matches("\\s+-?\\d+")) {
        try {
            int limit = Integer.parseInt(m.group(1).trim());
            if (limit > 0)
                message.getChannel().flatMap(chan -> chan.createMessage(r.nextInt(limit) + " !")).subscribe();
            else
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "random.request.3"))).subscribe();
        } catch (NumberFormatException e) {
            message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "random.request.4") + " " + Integer.MAX_VALUE + ").")).subscribe();
        }
    } else if ((tmp = Pattern.compile("\\s+-dj(\\s+\\d{1,3})?(\\s+\\d{1,3})?").matcher(m.group(1))).matches()) {
        int level = DEFAULT_LEVEL;
        int tolerance = DEFAULT_TOLERANCE;
        if (tmp.group(1) != null) {
            level = Integer.parseInt(tmp.group(1).trim());
            level = level - level % 10;
            if (level > DEFAULT_LEVEL)
                level = DEFAULT_LEVEL;
            if (level < MIN_LEVEL)
                level = MIN_LEVEL;
        }
        if (tmp.group(2) != null)
            tolerance = Integer.parseInt(tmp.group(2).trim());
        else if (tmp.group(1) == null)
            tolerance = MAX_TOLERANCE;
        final int finalLevel = level;
        final int finalTolerance = tolerance;
        List<Dungeon> djs = Arrays.stream(Dungeon.values()).filter(dj -> dj.filterByLevel(finalLevel, finalTolerance)).collect(Collectors.toList());
        Dungeon selected = djs.get(r.nextInt(djs.size()));
        if (selected.isEvent() && djs.size() > 1) {
            Dungeon selected2 = selected;
            while (selected == selected2 || selected2.isEvent()) selected2 = djs.get(r.nextInt(djs.size()));
            final Dungeon SELECTED2 = selected2;
            message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "random.request.6").replace("{dj}", selected.getLabel(lg)).replace("{dj2}", SELECTED2.getLabel(lg)).replace("{size}", String.valueOf(djs.size())))).subscribe();
        } else
            message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "random.request.5").replace("{dj}", selected.getLabel(lg)).replace("{size}", String.valueOf(djs.size())))).subscribe();
    } else if (m.group(1).matches("\\s+-dj(\\s+\\d+)?(\\s+\\d+)?"))
        badUse.throwException(message, this, lg);
    else {
        String value = m.group(1).trim();
        String[] values = value.split("\\s+");
        message.getChannel().flatMap(chan -> chan.createMessage(values[r.nextInt(values.length)] + " !")).subscribe();
    }
}
Also used : Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) Arrays(java.util.Arrays) List(java.util.List) AbstractCommand(commands.model.AbstractCommand) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) Random(java.util.Random) Translator(util.Translator) Pattern(java.util.regex.Pattern) Dungeon(enums.Dungeon) Collectors(java.util.stream.Collectors) Random(java.util.Random) Matcher(java.util.regex.Matcher) Dungeon(enums.Dungeon)

Example 14 with MessageCreateEvent

use of discord4j.core.event.domain.message.MessageCreateEvent in project KaellyBot by Kaysoro.

the class WhoisCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    String pseudo = m.group(2).trim().toLowerCase();
    ServerDofus server = null;
    StringBuilder url;
    try {
        url = new StringBuilder(Translator.getLabel(lg, "game.url")).append(Translator.getLabel(lg, "character.url")).append("?").append(forPseudo).append(URLEncoder.encode(pseudo, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        ExceptionManager.manageException(e, message, this, lg);
        return;
    }
    if (m.group(3) != null) {
        String serverName = m.group(3).trim().toLowerCase();
        ServerUtils.ServerQuery serverQuery = ServerUtils.getServerDofusFromName(serverName, lg);
        if (serverQuery.hasSucceed()) {
            url.append("&").append(forServer).append(serverQuery.getServer().getId());
            server = serverQuery.getServer();
        } else {
            serverQuery.getExceptions().forEach(e -> e.throwException(message, this, lg, serverQuery.getServersFound()));
            return;
        }
    }
    try {
        Document doc = JSoupManager.getDocument(url.toString());
        Elements elements = doc.getElementsByClass("ak-bg-odd");
        elements.addAll(doc.getElementsByClass("ak-bg-even"));
        if (!elements.isEmpty()) {
            // loop until finding the nearest character
            List<CharacterQuery> result = elements.stream().filter(e -> pseudo.equals(e.child(1).text().trim().toLowerCase())).map(e -> new CharacterQuery().withUrl(e.child(1).select("a").attr("href")).withServer(e.child(e.children().size() - 2).text())).collect(Collectors.toList());
            // Ankama bug workaround
            if (server != null && result.size() > 1) {
                List<CharacterQuery> filteredResult = new ArrayList<>();
                for (CharacterQuery query : result) try {
                    JSoupManager.getResponse(Translator.getLabel(lg, "game.url") + query.getUrl());
                    filteredResult.add(query);
                } catch (IOException e) {
                    LOG.warn("Not distinct character for same server: " + query.getUrl());
                }
                result = filteredResult;
                if (result.isEmpty()) {
                    BasicDiscordException.CHARACTERPAGE_INACCESSIBLE.throwException(message, this, lg);
                    return;
                }
            }
            if (result.size() == 1) {
                Connection.Response response = JSoupManager.getResponse(Translator.getLabel(lg, "game.url") + result.get(0).getUrl());
                final List<CharacterQuery> RESULT = result;
                if (!response.url().getPath().endsWith(Translator.getLabel(lg, "whois.request"))) {
                    if (m.group(1) == null) {
                        try {
                            EmbedCreateSpec embed = Character.getCharacter(Translator.getLabel(lg, "game.url") + RESULT.get(0).getUrl(), lg).decorateEmbedObject(lg);
                            message.getChannel().flatMap(chan -> chan.createEmbed(embed)).subscribe();
                        } catch (IOException e) {
                            ExceptionManager.manageIOException(e, message, this, lg, BasicDiscordException.CHARACTERPAGE_INACCESSIBLE);
                        }
                    } else {
                        try {
                            EmbedCreateSpec embed = Character.getCharacterStuff(Translator.getLabel(lg, "game.url") + RESULT.get(0).getUrl() + Translator.getLabel(lg, "character.stuff.url"), lg).decorateMoreEmbedObject(lg);
                            message.getChannel().flatMap(chan -> chan.createEmbed(embed)).subscribe();
                        } catch (IOException e) {
                            ExceptionManager.manageIOException(e, message, this, lg, BasicDiscordException.CHARACTERPAGE_INACCESSIBLE);
                        }
                    }
                } else
                    BasicDiscordException.CHARACTER_TOO_OLD.throwException(message, this, lg);
            } else if (result.size() > 1)
                tooMuchCharacters.throwException(message, this, lg, result.stream().map(CharacterQuery::getServer).distinct().collect(Collectors.toList()));
            else
                notFoundCharacter.throwException(message, this, lg);
        } else
            notFoundCharacter.throwException(message, this, lg);
    } catch (IOException e) {
        ExceptionManager.manageIOException(e, message, this, lg, BasicDiscordException.CHARACTERPAGE_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) Logger(org.slf4j.Logger) ServerUtils(util.ServerUtils) LoggerFactory(org.slf4j.LoggerFactory) Character(data.Character) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) exceptions(exceptions) Exception(java.lang.Exception) ArrayList(java.util.ArrayList) ServerDofus(data.ServerDofus) URLEncoder(java.net.URLEncoder) List(java.util.List) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) Document(org.jsoup.nodes.Document) EmbedCreateSpec(discord4j.core.spec.EmbedCreateSpec) Connection(org.jsoup.Connection) Elements(org.jsoup.select.Elements) Translator(util.Translator) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServerDofus(data.ServerDofus) EmbedCreateSpec(discord4j.core.spec.EmbedCreateSpec) ArrayList(java.util.ArrayList) Connection(org.jsoup.Connection) 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) Exception(java.lang.Exception) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 15 with MessageCreateEvent

use of discord4j.core.event.domain.message.MessageCreateEvent in project KaellyBot by Kaysoro.

the class SendNudeCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    if (message.getChannel().blockOptional().map(chan -> chan instanceof PrivateChannel).orElse(false) || message.getChannel().blockOptional().map(chan -> ((TextChannel) chan).isNsfw()).orElse(false)) {
        int position = RANDOM.nextInt(Nude.values().length);
        Nude nude = Nude.values()[position];
        message.getChannel().flatMap(chan -> chan.createEmbed(spec -> spec.setTitle(Translator.getLabel(lg, "sendnude.title")).setDescription(Translator.getLabel(lg, "sendnude.author").replace("{author}", nude.getAuthor()).replace("{url}", nude.getUrl())).setColor(discord4j.rest.util.Color.PINK).setFooter(Translator.getLabel(lg, "sendnude.footer").replace("{position}", String.valueOf(position + 1)).replace("{number}", String.valueOf(Nude.values().length)), null).setImage(nude.getImage()))).subscribe();
    } else
        // Exception NSFW
        BasicDiscordException.NO_NSFW_CHANNEL.throwException(message, this, lg);
}
Also used : PrivateChannel(discord4j.core.object.entity.channel.PrivateChannel) Language(enums.Language) java.awt(java.awt) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) TextChannel(discord4j.core.object.entity.channel.TextChannel) PrivateChannel(discord4j.core.object.entity.channel.PrivateChannel) Nude(enums.Nude) BasicDiscordException(exceptions.BasicDiscordException) Random(java.util.Random) Translator(util.Translator) Nude(enums.Nude)

Aggregations

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