Search in sources :

Example 1 with Cursor

use of com.rethinkdb.net.Cursor in project MantaroBot by Mantaro.

the class MoneyCmds method richest.

@Subscribe
public void richest(CommandRegistry cr) {
    final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 10);
    final String pattern = ":g$";
    ITreeCommand leaderboards = (ITreeCommand) cr.register("leaderboard", new TreeCommand(Category.CURRENCY) {

        @Override
        public Command defaultTrigger(GuildMessageReceivedEvent event, String mainCommand, String commandName) {
            return new SubCommand() {

                @Override
                protected void call(GuildMessageReceivedEvent event, String content) {
                    if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                        return;
                    OrderBy template = r.table("players").orderBy().optArg("index", r.desc("money"));
                    Cursor<Map> c1 = getGlobalRichest(template, pattern);
                    List<Map> c = c1.toList();
                    c1.close();
                    event.getChannel().sendMessage(baseEmbed(event, "Money leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("money").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - $%s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
                }
            };
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Leaderboard").setDescription("**Returns the leaderboard.**").addField("Usage", "`~>leaderboard` - **Returns the money leaderboard.**\n" + "`~>leaderboard rep` - **Returns the reputation leaderboard.**\n" + "`~>leaderboard lvl` - **Returns the level leaderboard.**\n" + "~>leaderboard streak - **Returns the daily streak leaderboard.", false).build();
        }
    });
    leaderboards.addSubCommand("lvl", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            Cursor<Map> m;
            try (Connection conn = Utils.newDbConnection()) {
                m = r.table("players").orderBy().optArg("index", r.desc("level")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", "level", r.hashMap("data", "experience"))).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
            }
            List<Map> c = m.toList();
            m.close();
            event.getChannel().sendMessage(baseEmbed(event, "Level leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("level").toString() + "\n - Experience: **" + ((Map) map.get("data")).get("experience") + "**")).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
        }
    });
    leaderboards.addSubCommand("rep", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Cursor<Map> m;
            try (Connection conn = Utils.newDbConnection()) {
                m = r.table("players").orderBy().optArg("index", r.desc("reputation")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", "reputation")).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
            }
            List<Map> c = m.toList();
            m.close();
            event.getChannel().sendMessage(baseEmbed(event, "Reputation leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("reputation").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
        }
    });
    leaderboards.addSubCommand("streak", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Cursor<Map> m;
            try (Connection conn = Utils.newDbConnection()) {
                m = r.table("players").orderBy().optArg("index", r.desc("userDailyStreak")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", r.hashMap("data", "dailyStrike"))).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
            }
            List<Map> c = m.toList();
            m.close();
            event.getChannel().sendMessage(baseEmbed(event, "Daily streak leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), ((HashMap) (map.get("data"))).get("dailyStrike").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %sx", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
        }
    });
    // TODO enable in 4.9
    /*
        leaderboards.addSubCommand("localxp", new SubCommand() {
            @Override
            protected void call(GuildMessageReceivedEvent event, String content) {
                List<Map> l;

                try(Connection conn = Utils.newDbConnection()) {
                    l = r.table("guilds")
                            .get(event.getGuild().getId())
                            .getField("data")
                            .getField("localPlayerExperience")
                            .run(conn, OptArgs.of("read_mode", "outdated"));
                }

                l.sort(Comparator.<Map>comparingLong(o -> (long) o.get("experience")).reversed());

                event.getChannel().sendMessage(
                        baseEmbed(event,
                                "Local level leaderboard", event.getJDA().getSelfUser().getEffectiveAvatarUrl()
                        ).setDescription(l.stream()
                                .map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("userId").toString()), map.get("level").toString() +
                                        "\n - Experience: **" + map.get("experience") + "**\n"))
                                .map(p -> String.format("%s**%s** - %s", EmoteReference.MARKER,
                                        p == null ? "User left guild" : p.getKey().getName() + "#" + p.getKey().getDiscriminator(), p.getValue()))
                                .collect(Collectors.joining("\n"))
                        ).build()
                ).queue();
            }
        });

        leaderboards.createSubCommandAlias("localxp", "local");
        */
    leaderboards.createSubCommandAlias("rep", "reputation");
    leaderboards.createSubCommandAlias("lvl", "level");
    leaderboards.createSubCommandAlias("streak", "daily");
    cr.registerAlias("leaderboard", "richest");
}
Also used : OrderBy(com.rethinkdb.gen.ast.OrderBy) Items(net.kodehawa.mantarobot.commands.currency.item.Items) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) Member(net.dv8tion.jda.core.entities.Member) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) NumberFormat(java.text.NumberFormat) InteractiveOperation(net.kodehawa.mantarobot.core.listeners.operations.core.InteractiveOperation) MantaroBot(net.kodehawa.mantarobot.MantaroBot) SecureRandom(java.security.SecureRandom) RethinkDB.r(com.rethinkdb.RethinkDB.r) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) Pair(org.apache.commons.lang3.tuple.Pair) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) OptArgs(com.rethinkdb.model.OptArgs) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ParseException(java.text.ParseException) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) Connection(com.rethinkdb.net.Connection) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Month(java.time.Month) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) TimeUnit(java.util.concurrent.TimeUnit) User(net.dv8tion.jda.core.entities.User) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) LocalDate(java.time.LocalDate) MantaroData(net.kodehawa.mantarobot.data.MantaroData) FinderUtil(com.jagrosh.jdautilities.utils.FinderUtil) OrderBy(com.rethinkdb.gen.ast.OrderBy) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Connection(com.rethinkdb.net.Connection) Cursor(com.rethinkdb.net.Cursor) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 2 with Cursor

use of com.rethinkdb.net.Cursor in project Ardent by adamint.

the class DefaultRole method getDefaultRole.

public static Role getDefaultRole(Guild guild) {
    Role returned = null;
    List<HashMap> defaultRoleModels = ((Cursor<HashMap>) r.db("data").table("defaultroles").filter(row -> row.g("guild_id").eq(guild.getId())).run(connection)).toList();
    if (defaultRoleModels.size() > 0) {
        DefaultRoleModel defaultRoleModel = asPojo(defaultRoleModels.get(0), DefaultRoleModel.class);
        String roleID = defaultRoleModel.getRole_id();
        if (!roleID.equalsIgnoreCase("none")) {
            returned = guild.getRoleById(roleID);
        }
    }
    return returned;
}
Also used : DefaultRoleModel(tk.ardentbot.rethink.models.DefaultRoleModel) HashMap(java.util.HashMap) Cursor(com.rethinkdb.net.Cursor)

Example 3 with Cursor

use of com.rethinkdb.net.Cursor in project Ardent by adamint.

the class RPGMoney method setupSubcommands.

@Override
public void setupSubcommands() throws Exception {
    subcommands.add(new Subcommand("See who has the most money - globally!", "top", "top") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (args.length == 2) {
                HashMap<User, Double> moneyAmounts = new HashMap<>();
                Cursor<HashMap> top = r.db("data").table("profiles").orderBy().optArg("index", r.desc("money")).limit(20).run(connection);
                top.forEach(hashMap -> {
                    Profile profile = asPojo(hashMap, Profile.class);
                    assert profile.getUser() != null;
                    moneyAmounts.put(profile.getUser(), profile.getMoney());
                });
                Map<User, Double> sortedAmounts = MapUtils.sortByValue(moneyAmounts);
                String topMoney = "Global Richest Users";
                EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
                builder.setAuthor(topMoney, getShard().url, guild.getIconUrl());
                StringBuilder description = new StringBuilder();
                final int[] current = { 0 };
                sortedAmounts.forEach((u, money) -> {
                    if (u != null) {
                        description.append("\n#" + (current[0] + 1) + ": **" + u.getName() + "** " + RPGUtils.formatMoney(money));
                        current[0]++;
                    }
                });
                description.append("\n\nGet money by sending commands or asking questions on our support server ( https://ardentbot" + ".tk/guild )\n\nSee people's money by doing /money @User or see yours by just using /money");
                sendEmbed(builder.setDescription(description.toString()), channel, user);
                return;
            }
            try {
                int page = Integer.parseInt(args[2]) - 1;
                HashMap<User, Double> moneyAmounts = new HashMap<>();
                Cursor<HashMap> top = r.db("data").table("profiles").orderBy().optArg("index", r.desc("money")).slice((page * 20), (page * 20) + 11).limit(25).run(connection);
                top.forEach(hashMap -> {
                    Profile profile = asPojo(hashMap, Profile.class);
                    assert profile.getUser() != null;
                    moneyAmounts.put(profile.getUser(), profile.getMoney());
                });
                Map<User, Double> sortedAmounts = MapUtils.sortByValue(moneyAmounts);
                String topMoney = "Global Richest Users | Page " + page;
                EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
                builder.setAuthor(topMoney, getShard().url, guild.getIconUrl());
                StringBuilder description = new StringBuilder();
                final int[] current = { 0 };
                sortedAmounts.forEach((u, money) -> {
                    if (u != null) {
                        description.append("\n#" + ((page * 20) + current[0] + 1) + ": **" + u.getName() + "** " + RPGUtils.formatMoney(money));
                        current[0]++;
                    }
                });
                description.append("\n\nGet money by sending commands or asking questions on our support server ( https://ardentbot" + ".tk/guild )\n\nSee people's money by doing /money @User or see yours by just using /money");
                sendEmbed(builder.setDescription(description.toString()), channel, user);
            } catch (NumberFormatException e) {
                sendTranslatedMessage("You need to specify a valid page number!", channel, user);
            }
        }
    });
    subcommands.add(new Subcommand("See who has the most money in your server", "server", "server", "guild", "topguild") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (!generatedFirstTimeFor.contains(guild.getId())) {
                sendTranslatedMessage("Please wait a second, generating and caching your server's statistics", channel, user);
                generatedFirstTimeFor.add(guild.getId());
            }
            HashMap<User, Double> moneyAmounts = new HashMap<>();
            guild.getMembers().forEach(member -> {
                User u = member.getUser();
                moneyAmounts.put(u, Profile.get(u).getMoney());
            });
            Map<User, Double> sortedAmounts = MapUtils.sortByValue(moneyAmounts);
            EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
            builder.setAuthor("Richest Users | This Server", getShard().url, guild.getIconUrl());
            StringBuilder description = new StringBuilder();
            description.append("**Richest Users in this Server**");
            final int[] current = { 0 };
            sortedAmounts.forEach((u, money) -> {
                if (current[0] < 10) {
                    description.append("\n#" + (current[0] + 1) + ": **" + u.getName() + "** " + RPGUtils.formatMoney(money));
                    current[0]++;
                }
            });
            description.append("\n\nGet money by sending commands or asking questions on our support server ( https://ardentbot" + ".tk/guild )\n\nSee people's money by doing /money @User or see yours by just using /money");
            sendEmbed(builder.setDescription(description.toString()), channel, user);
        }
    });
}
Also used : MessageUtils(tk.ardentbot.utils.discord.MessageUtils) Ratelimitable(tk.ardentbot.core.executor.Ratelimitable) Subcommand(tk.ardentbot.core.executor.Subcommand) Database.r(tk.ardentbot.rethink.Database.r) HashMap(java.util.HashMap) Profile(tk.ardentbot.utils.rpg.profiles.Profile) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) Message(net.dv8tion.jda.core.entities.Message) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ArrayList(java.util.ArrayList) Guild(net.dv8tion.jda.core.entities.Guild) List(java.util.List) Cursor(com.rethinkdb.net.Cursor) User(net.dv8tion.jda.core.entities.User) RPGUtils(tk.ardentbot.utils.rpg.RPGUtils) MapUtils(tk.ardentbot.utils.MapUtils) Database.connection(tk.ardentbot.rethink.Database.connection) Map(java.util.Map) User(net.dv8tion.jda.core.entities.User) Subcommand(tk.ardentbot.core.executor.Subcommand) Message(net.dv8tion.jda.core.entities.Message) HashMap(java.util.HashMap) Guild(net.dv8tion.jda.core.entities.Guild) Cursor(com.rethinkdb.net.Cursor) Profile(tk.ardentbot.utils.rpg.profiles.Profile) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with Cursor

use of com.rethinkdb.net.Cursor in project Ardent by adamint.

the class MusicConfig method noArgs.

@Override
public void noArgs(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
    Cursor<HashMap> settings = r.db("data").table("music_settings").filter(row -> row.g("guild_id").eq(guild.getId())).run(connection);
    if (settings.hasNext()) {
        MusicSettingsModel musicSettingsModel = asPojo(settings.next(), MusicSettingsModel.class);
        sendTranslatedMessage("**music Settings**\n" + "Delete music play messages: " + musicSettingsModel.isRemove_addition_messages(), channel, user);
    } else
        sendTranslatedMessage("Your guild has no set music settings! Type **/manage** to find your portal" + " link", channel, user);
}
Also used : Guild(net.dv8tion.jda.core.entities.Guild) Cursor(com.rethinkdb.net.Cursor) User(net.dv8tion.jda.core.entities.User) Command(tk.ardentbot.core.executor.Command) MusicSettingsModel(tk.ardentbot.rethink.models.MusicSettingsModel) Database.connection(tk.ardentbot.rethink.Database.connection) Database.r(tk.ardentbot.rethink.Database.r) HashMap(java.util.HashMap) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) Message(net.dv8tion.jda.core.entities.Message) HashMap(java.util.HashMap) MusicSettingsModel(tk.ardentbot.rethink.models.MusicSettingsModel)

Example 5 with Cursor

use of com.rethinkdb.net.Cursor in project Ardent by adamint.

the class Automessage method getMessagesAndChannel.

public static Triplet<String, String, String> getMessagesAndChannel(Guild guild) {
    Triplet<String, String, String> triplet;
    check(guild);
    List<HashMap> getAutomessages = ((Cursor<HashMap>) r.db("data").table("automessages").filter(row -> row.g("guild_id").eq(guild.getId())).run(connection)).toList();
    if (getAutomessages.size() > 0) {
        AutomessageModel automessageModel = asPojo(getAutomessages.get(0), AutomessageModel.class);
        String channel;
        String welcome;
        String goodbye;
        if (automessageModel.getChannel_id().equalsIgnoreCase("000"))
            channel = null;
        else
            channel = automessageModel.getChannel_id();
        if (automessageModel.getWelcome().equalsIgnoreCase("000"))
            welcome = null;
        else
            welcome = automessageModel.getWelcome();
        if (automessageModel.getGoodbye().equalsIgnoreCase("000"))
            goodbye = null;
        else
            goodbye = automessageModel.getGoodbye();
        triplet = new Triplet<>(channel, welcome, goodbye);
    } else {
        triplet = new Triplet<>(null, null, null);
    }
    return triplet;
}
Also used : HashMap(java.util.HashMap) AutomessageModel(tk.ardentbot.rethink.models.AutomessageModel) Cursor(com.rethinkdb.net.Cursor)

Aggregations

Cursor (com.rethinkdb.net.Cursor)5 HashMap (java.util.HashMap)4 User (net.dv8tion.jda.core.entities.User)3 Guild (net.dv8tion.jda.core.entities.Guild)2 Message (net.dv8tion.jda.core.entities.Message)2 MessageChannel (net.dv8tion.jda.core.entities.MessageChannel)2 Database.connection (tk.ardentbot.rethink.Database.connection)2 Database.r (tk.ardentbot.rethink.Database.r)2 StringUtils (br.com.brjdevs.java.utils.texts.StringUtils)1 Subscribe (com.google.common.eventbus.Subscribe)1 FinderUtil (com.jagrosh.jdautilities.utils.FinderUtil)1 RethinkDB.r (com.rethinkdb.RethinkDB.r)1 OrderBy (com.rethinkdb.gen.ast.OrderBy)1 OptArgs (com.rethinkdb.model.OptArgs)1 Connection (com.rethinkdb.net.Connection)1 SecureRandom (java.security.SecureRandom)1 NumberFormat (java.text.NumberFormat)1 ParseException (java.text.ParseException)1 LocalDate (java.time.LocalDate)1 Month (java.time.Month)1