Search in sources :

Example 11 with Message

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

the class CommandCommand method request.

@Override
public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
    if (isUserHasEnoughRights(message)) {
        Guild guild = Guild.getGuild(message.getGuild().block());
        List<Command> potentialCmds = new ArrayList<>();
        String commandName = m.group(1).trim();
        for (Command command : CommandManager.getCommands()) if (command.isPublic() && !command.isAdmin() && command.getName().contains(commandName))
            potentialCmds.add(command);
        if (potentialCmds.size() == 1) {
            Command command = potentialCmds.get(0);
            String value = m.group(2);
            if (command instanceof CommandCommand) {
                message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "command.request.1"))).subscribe();
                return;
            }
            if (value.matches("false") || value.matches("1") || value.matches("off")) {
                if (!guild.getForbiddenCommands().containsKey(command.getName())) {
                    new CommandForbidden(command, guild).addToDatabase();
                    message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "command.request.2") + " *" + commandName + "* " + Translator.getLabel(lg, "command.request.3"))).subscribe();
                } else
                    BasicDiscordException.FORBIDDEN_COMMAND_FOUND.throwException(message, this, lg);
            } else if (value.matches("true") || value.matches("0") || value.matches("on")) {
                if (guild.getForbiddenCommands().containsKey(command.getName())) {
                    guild.getForbiddenCommands().get(command.getName()).removeToDatabase();
                    message.getChannel().flatMap(chan -> chan.createMessage(Translator.getLabel(lg, "command.request.2") + " *" + commandName + "* " + Translator.getLabel(lg, "command.request.4"))).subscribe();
                } else
                    BasicDiscordException.FORBIDDEN_COMMAND_NOTFOUND.throwException(message, this, lg);
            } else
                badUse.throwException(message, this, lg);
        } else if (potentialCmds.isEmpty())
            notFoundCmd.throwException(message, this, lg);
        else
            tooMuchCmds.throwException(message, this, lg);
    } else
        BasicDiscordException.NO_ENOUGH_RIGHTS.throwException(message, this, lg);
}
Also used : Language(enums.Language) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) AbstractCommand(commands.model.AbstractCommand) CommandForbidden(data.CommandForbidden) Guild(data.Guild) exceptions(exceptions) ArrayList(java.util.ArrayList) List(java.util.List) Matcher(java.util.regex.Matcher) Message(discord4j.core.object.entity.Message) CommandManager(commands.CommandManager) Command(commands.model.Command) Translator(util.Translator) CommandForbidden(data.CommandForbidden) AbstractCommand(commands.model.AbstractCommand) Command(commands.model.Command) ArrayList(java.util.ArrayList) Guild(data.Guild)

Example 12 with Message

use of discord4j.core.object.entity.Message 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 13 with Message

use of discord4j.core.object.entity.Message in project symja_android_library by axkr.

the class SymjaBot method main.

public static void main(String[] args) {
    if (args.length > 0) {
        Locale.setDefault(Locale.US);
        ParserConfig.PARSER_USE_LOWERCASE_SYMBOLS = true;
        ToggleFeature.COMPILE = false;
        Config.JAVA_UNSAFE = true;
        Config.SHORTEN_STRING_LENGTH = 512;
        Config.USE_VISJS = true;
        Config.FILESYSTEM_ENABLED = false;
        Config.FUZZY_PARSER = true;
        Config.UNPROTECT_ALLOWED = false;
        Config.USE_MANIPULATE_JS = true;
        Config.JAS_NO_THREADS = true;
        Config.MATHML_TRIG_LOWERCASE = false;
        Config.MAX_AST_SIZE = 10000;
        Config.MAX_OUTPUT_SIZE = 10000;
        Config.MAX_BIT_LENGTH = 200000;
        Config.MAX_POLYNOMIAL_DEGREE = 100;
        Config.MAX_INPUT_LEAVES = 100L;
        Config.MAX_MATRIX_DIMENSION_SIZE = 100;
        Config.PRIME_FACTORS = new BigIntegerPrimality();
        EvalEngine.get().setPackageMode(true);
        String theDiscordToken = args[0];
        GatewayDiscordClient client = DiscordClientBuilder.create(theDiscordToken).build().login().block();
        client.getEventDispatcher().on(ReadyEvent.class).subscribe(event -> {
            LocalDateTime now = LocalDateTime.now();
            final User self = event.getSelf();
            System.out.println(String.format(TIME_FORMATTER.format(now) + ": Logged in as %s#%s", self.getUsername(), self.getDiscriminator()));
        });
        client.on(MessageCreateEvent.class).subscribe(event -> {
            final Message message = event.getMessage();
            if (filterMessage(message)) {
                createMessage(message);
            }
        });
        client.onDisconnect().block();
    } else {
        System.out.println("The discord bot token has to be set as the first argument.");
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ReadyEvent(discord4j.core.event.domain.lifecycle.ReadyEvent) MessageCreateEvent(discord4j.core.event.domain.message.MessageCreateEvent) User(discord4j.core.object.entity.User) Message(discord4j.core.object.entity.Message) BigIntegerPrimality(org.matheclipse.gpl.numbertheory.BigIntegerPrimality) GatewayDiscordClient(discord4j.core.GatewayDiscordClient)

Example 14 with Message

use of discord4j.core.object.entity.Message 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 15 with Message

use of discord4j.core.object.entity.Message 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)

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