Search in sources :

Example 41 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class AudioCmdUtils method embedForQueue.

public static void embedForQueue(int page, GuildMessageReceivedEvent event, GuildMusicManager musicManager) {
    String toSend = AudioUtils.getQueueList(musicManager.getTrackScheduler().getQueue());
    Guild guild = event.getGuild();
    String nowPlaying = musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack() != null ? "**[" + musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().title + "](" + musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().uri + ")** (" + Utils.getDurationMinutes(musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().length) + ")" : "Nothing or title/duration not found";
    if (toSend.isEmpty()) {
        event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN).setDescription("Nothing here, just dust. Why don't you queue some songs?\n" + "If you think there are songs here but they don't appear, try using `~>queue 1`.\n\n" + "**If there is a song playing and you didn't add more songs, then there is actually just dust here. You can queue more songs as you desire!**").addField("Currently playing", nowPlaying, false).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").build()).queue();
        return;
    }
    String[] lines = NEWLINE_PATTERN.split(toSend);
    if (!guild.getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION)) {
        String line = null;
        StringBuilder sb = new StringBuilder();
        int total;
        {
            int t = 0;
            int c = 0;
            for (String s : lines) {
                if (s.length() + c + 1 > MessageEmbed.TEXT_MAX_LENGTH) {
                    t++;
                    c = 0;
                }
                c += s.length() + 1;
            }
            if (c > 0)
                t++;
            total = t;
        }
        int current = 0;
        for (String s : lines) {
            int l = s.length() + 1;
            if (l > MessageEmbed.TEXT_MAX_LENGTH)
                throw new IllegalArgumentException("Length for one of the pages is greater than the maximum");
            if (sb.length() + l > MessageEmbed.TEXT_MAX_LENGTH) {
                current++;
                if (current == page) {
                    line = sb.toString();
                    break;
                }
                sb = new StringBuilder();
            }
            sb.append(s).append('\n');
        }
        if (sb.length() > 0 && current + 1 == page) {
            line = sb.toString();
        }
        if (line == null || page > total) {
            event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN).setDescription("Nothing here, just dust. Why don't you go back some pages?\n" + "If you think there are songs here but they don't appear, try using `~>queue 1`.").addField("Currently playing", nowPlaying, false).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").build()).queue();
        } else {
            long length = musicManager.getTrackScheduler().getQueue().stream().mapToLong(value -> value.getInfo().length).sum();
            EmbedBuilder builder = new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN);
            VoiceChannel vch = guild.getSelfMember().getVoiceState().getChannel();
            builder.addField("Currently playing", nowPlaying, false).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").addField("Total queue time", "`" + Utils.getReadableTime(length) + "`", true).addField("Total queue size", "`" + musicManager.getTrackScheduler().getQueue().size() + " songs`", true).addField("Repeat / Pause", "`" + (musicManager.getTrackScheduler().getRepeatMode() == null ? "false" : musicManager.getTrackScheduler().getRepeatMode()) + " / " + String.valueOf(musicManager.getTrackScheduler().getAudioPlayer().isPaused()) + "`", true).addField("Playing in", vch == null ? "No channel :<" : "`" + vch.getName() + "`", true).setFooter("Total pages: " + total + (total == 1 ? "" : " -> Use ~>queue <page> to change pages") + ". Currently in page " + page, guild.getIconUrl());
            event.getChannel().sendMessage(builder.setDescription(line).build()).queue();
        }
        return;
    }
    DiscordUtils.list(event, 30, false, (p, total) -> {
        long length = musicManager.getTrackScheduler().getQueue().stream().mapToLong(value -> value.getInfo().length).sum();
        EmbedBuilder builder = new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN);
        VoiceChannel vch = guild.getSelfMember().getVoiceState().getChannel();
        builder.addField("Currently playing", nowPlaying, false).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").addField("Total queue time", "`" + Utils.getReadableTime(length) + "`", true).addField("Total queue size", "`" + musicManager.getTrackScheduler().getQueue().size() + " songs`", true).addField("Repeat / Pause", "`" + (musicManager.getTrackScheduler().getRepeatMode() == null ? "false" : musicManager.getTrackScheduler().getRepeatMode()) + " / " + String.valueOf(musicManager.getTrackScheduler().getAudioPlayer().isPaused()) + "`", true).addField("Playing in", vch == null ? "No channel :<" : "`" + vch.getName() + "`", true).setFooter("Total pages: " + total + (total == 1 ? "" : " -> React to change pages") + ". Currently in page " + p, guild.getIconUrl());
        return builder;
    }, lines);
}
Also used : VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) NEWLINE_PATTERN(net.kodehawa.mantarobot.utils.data.SimpleFileDataManager.NEWLINE_PATTERN) Utils(net.kodehawa.mantarobot.utils.Utils) AudioManager(net.dv8tion.jda.core.managers.AudioManager) GuildMusicManager(net.kodehawa.mantarobot.commands.music.GuildMusicManager) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) java.awt(java.awt) Guild(net.dv8tion.jda.core.entities.Guild) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Guild(net.dv8tion.jda.core.entities.Guild)

Example 42 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class CommandRegistry method process.

// BEWARE OF INSTANCEOF CALLS
// I know there are better approaches to this, THIS IS JUST A WORKAROUND, DON'T TRY TO REPLICATE THIS.
public boolean process(GuildMessageReceivedEvent event, String cmdName, String content) {
    long start = System.currentTimeMillis();
    Command command = commands.get(cmdName);
    if (command == null) {
        command = commands.get(cmdName.toLowerCase());
        if (command == null)
            return false;
    }
    // Variable used in lambda expression should be final or effectively final...
    final Command cmd = command;
    if (MantaroData.db().getMantaroData().getBlackListedUsers().contains(event.getAuthor().getId())) {
        return false;
    }
    DBGuild dbg = MantaroData.db().getGuild(event.getGuild());
    GuildData data = dbg.getData();
    if (data.getDisabledCommands().contains(cmd instanceof AliasCommand ? ((AliasCommand) cmd).getOriginalName() : cmdName)) {
        return false;
    }
    List<String> channelDisabledCommands = data.getChannelSpecificDisabledCommands().get(event.getChannel().getId());
    if (channelDisabledCommands != null && channelDisabledCommands.contains(cmd instanceof AliasCommand ? ((AliasCommand) cmd).getOriginalName() : cmdName)) {
        return false;
    }
    if (data.getDisabledUsers().contains(event.getAuthor().getId()) && !isAdmin(event.getMember())) {
        return false;
    }
    if (data.getDisabledChannels().contains(event.getChannel().getId()) && (cmd instanceof AliasCommand ? ((AliasCommand) cmd).parentCategory() != Category.MODERATION : cmd.category() != Category.MODERATION)) {
        return false;
    }
    if (conf.isPremiumBot() && (cmd instanceof AliasCommand ? ((AliasCommand) cmd).parentCategory() == Category.CURRENCY : cmd.category() == Category.CURRENCY)) {
        return false;
    }
    if (data.getDisabledCategories().contains(cmd instanceof AliasCommand ? ((AliasCommand) cmd).parentCategory() : cmd.category())) {
        return false;
    }
    if (data.getChannelSpecificDisabledCategories().computeIfAbsent(event.getChannel().getId(), c -> new ArrayList<>()).contains(cmd instanceof AliasCommand ? ((AliasCommand) cmd).parentCategory() : cmd.category())) {
        return false;
    }
    if (!data.getDisabledRoles().isEmpty() && event.getMember().getRoles().stream().anyMatch(r -> data.getDisabledRoles().contains(r.getId())) && !isAdmin(event.getMember())) {
        return false;
    }
    HashMap<String, List<String>> roleSpecificDisabledCommands = data.getRoleSpecificDisabledCommands();
    if (event.getMember().getRoles().stream().anyMatch(r -> roleSpecificDisabledCommands.computeIfAbsent(r.getId(), s -> new ArrayList<>()).contains(cmd instanceof AliasCommand ? ((AliasCommand) cmd).getOriginalName() : cmdName)) && !isAdmin(event.getMember())) {
        return false;
    }
    HashMap<String, List<Category>> roleSpecificDisabledCategories = data.getRoleSpecificDisabledCategories();
    if (event.getMember().getRoles().stream().anyMatch(r -> roleSpecificDisabledCategories.computeIfAbsent(r.getId(), s -> new ArrayList<>()).contains(cmd instanceof AliasCommand ? ((AliasCommand) cmd).parentCategory() : cmd.category())) && !isAdmin(event.getMember())) {
        return false;
    }
    // If we are in the patreon bot, deny all requests from unknown guilds.
    if (conf.isPremiumBot() && !conf.isOwner(event.getAuthor()) && !dbg.isPremium()) {
        event.getChannel().sendMessage(EmoteReference.ERROR + "Seems like you're trying to use the Patreon bot when this guild is **not** marked as premium. " + "**If you think this is an error please contact Kodehawa#3457 or poke me on #donators in the support guild**").queue();
        return false;
    }
    if (!cmd.permission().test(event.getMember())) {
        event.getChannel().sendMessage(EmoteReference.STOP + "You have no permissions to trigger this command :(").queue();
        return false;
    }
    long end = System.currentTimeMillis();
    MantaroBot.getInstance().getStatsClient().increment("commands");
    log.debug("Command invoked: {}, by {}#{} with timestamp {}", cmdName, event.getAuthor().getName(), event.getAuthor().getDiscriminator(), new Date(System.currentTimeMillis()));
    cmd.run(event, cmdName, content);
    if (cmd.category() != null && cmd.category().name() != null && !cmd.category().name().isEmpty()) {
        MantaroBot.getInstance().getStatsClient().increment("command", "name:" + cmdName);
        MantaroBot.getInstance().getStatsClient().increment("category", "name:" + cmd.category().name().toLowerCase());
        CommandStatsManager.log(cmdName);
        CategoryStatsManager.log(cmd.category().name().toLowerCase());
    }
    MantaroBot.getInstance().getStatsClient().histogram("command_process_time", (end - start));
    return true;
}
Also used : SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) java.util(java.util) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) Member(net.dv8tion.jda.core.entities.Member) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) CategoryStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CategoryStatsManager) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) MantaroBot(net.kodehawa.mantarobot.MantaroBot) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) Slf4j(lombok.extern.slf4j.Slf4j) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Preconditions(com.google.common.base.Preconditions) CommandStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CommandStatsManager) Config(net.kodehawa.mantarobot.data.Config) AliasCommand(net.kodehawa.mantarobot.core.modules.commands.AliasCommand) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) AliasCommand(net.kodehawa.mantarobot.core.modules.commands.AliasCommand) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) AliasCommand(net.kodehawa.mantarobot.core.modules.commands.AliasCommand)

Example 43 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class MantaroListener method onEvent.

@Override
public void onEvent(Event event) {
    if (event instanceof ShardMonitorEvent) {
        if (MantaroBot.getInstance().getShardedMantaro().getShards()[shardId].getEventManager().getLastJDAEventTimeDiff() > 30000)
            return;
        ((ShardMonitorEvent) event).alive(shardId, ShardMonitorEvent.MANTARO_LISTENER);
        return;
    }
    if (event instanceof GuildMessageReceivedEvent) {
        MantaroBot.getInstance().getStatsClient().increment("messages_received");
        GuildMessageReceivedEvent e = (GuildMessageReceivedEvent) event;
        onMessage(e);
        return;
    }
    if (event instanceof GuildMemberJoinEvent) {
        shard.getThreadPool().execute(() -> onUserJoin((GuildMemberJoinEvent) event));
        return;
    }
    if (event instanceof GuildMemberLeaveEvent) {
        shard.getThreadPool().execute(() -> onUserLeave((GuildMemberLeaveEvent) event));
        return;
    }
    // Doesn't run on the thread pool as there's no need for it.
    if (event instanceof GuildMemberRoleAddEvent) {
        // It only runs on the thread pool if needed.
        handleNewPatron((GuildMemberRoleAddEvent) event);
    }
    if (event instanceof GuildMessageUpdateEvent) {
        logEdit((GuildMessageUpdateEvent) event);
        return;
    }
    if (event instanceof GuildMessageDeleteEvent) {
        logDelete((GuildMessageDeleteEvent) event);
        return;
    }
    if (event instanceof GuildUnbanEvent) {
        logUnban((GuildUnbanEvent) event);
        return;
    }
    if (event instanceof GuildBanEvent) {
        logBan((GuildBanEvent) event);
        return;
    }
    // Internal events
    if (event instanceof GuildJoinEvent) {
        GuildJoinEvent e = (GuildJoinEvent) event;
        if (e.getGuild().getSelfMember().getJoinDate().isBefore(OffsetDateTime.now().minusSeconds(30)))
            return;
        onJoin(e);
        if (MantaroCore.hasLoadedCompletely()) {
            MantaroBot.getInstance().getStatsClient().gauge("guilds", MantaroBot.getInstance().getGuildCache().size());
            MantaroBot.getInstance().getStatsClient().gauge("users", MantaroBot.getInstance().getUserCache().size());
        }
        return;
    }
    if (event instanceof GuildLeaveEvent) {
        onLeave((GuildLeaveEvent) event);
        if (MantaroCore.hasLoadedCompletely()) {
            MantaroBot.getInstance().getStatsClient().gauge("guilds", MantaroBot.getInstance().getGuildCache().size());
            MantaroBot.getInstance().getStatsClient().gauge("users", MantaroBot.getInstance().getUserCache().size());
        }
        return;
    }
    // debug
    if (event instanceof StatusChangeEvent) {
        logStatusChange((StatusChangeEvent) event);
        return;
    }
    if (event instanceof DisconnectEvent) {
        onDisconnect((DisconnectEvent) event);
        return;
    }
    if (event instanceof ExceptionEvent) {
        MantaroBot.getInstance().getStatsClient().increment("exceptions");
        onException((ExceptionEvent) event);
        return;
    }
    if (event instanceof HttpRequestEvent) {
        MantaroBot.getInstance().getStatsClient().incrementCounter("http_requests");
        return;
    }
    if (event instanceof ReconnectedEvent) {
        MantaroBot.getInstance().getStatsClient().increment("shard.reconnect");
        MantaroBot.getInstance().getStatsClient().recordEvent(com.timgroup.statsd.Event.builder().withTitle("shard.reconnect").withText("Shard reconnected").withDate(new Date()).build());
        return;
    }
    if (event instanceof ResumedEvent) {
        MantaroBot.getInstance().getStatsClient().increment("shard.resume");
        MantaroBot.getInstance().getStatsClient().recordEvent(com.timgroup.statsd.Event.builder().withTitle("shard.resume").withText("Shard resumed").withDate(new Date()).build());
    }
}
Also used : GuildJoinEvent(net.dv8tion.jda.core.events.guild.GuildJoinEvent) HttpRequestEvent(net.dv8tion.jda.core.events.http.HttpRequestEvent) GuildMemberJoinEvent(net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent) GuildMemberRoleAddEvent(net.dv8tion.jda.core.events.guild.member.GuildMemberRoleAddEvent) GuildMemberLeaveEvent(net.dv8tion.jda.core.events.guild.member.GuildMemberLeaveEvent) GuildMessageUpdateEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageUpdateEvent) GuildLeaveEvent(net.dv8tion.jda.core.events.guild.GuildLeaveEvent) Date(java.util.Date) GuildBanEvent(net.dv8tion.jda.core.events.guild.GuildBanEvent) ShardMonitorEvent(net.kodehawa.mantarobot.core.listeners.events.ShardMonitorEvent) GuildMessageDeleteEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageDeleteEvent) GuildUnbanEvent(net.dv8tion.jda.core.events.guild.GuildUnbanEvent) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)

Example 44 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class CurrencyCmds method inventory.

@Subscribe
public void inventory(CommandRegistry cr) {
    cr.register("inventory", new SimpleCommand(Category.CURRENCY) {

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Map<String, Optional<String>> t = StringUtils.parse(args);
            content = Utils.replaceArguments(t, content, "brief", "calculate");
            Member member = Utils.findMember(event, event.getMember(), content);
            if (member == null)
                return;
            Player player = MantaroData.db().getPlayer(member);
            if (t.containsKey("brief")) {
                event.getChannel().sendMessage(String.format("**%s's inventory:** %s", member.getEffectiveName(), ItemStack.toString(player.getInventory().asList()))).queue();
                return;
            }
            if (t.containsKey("calculate")) {
                long all = player.getInventory().asList().stream().filter(item -> item.getItem().isSellable()).mapToLong(value -> (long) (value.getItem().getValue() * value.getAmount() * 0.9d)).sum();
                event.getChannel().sendMessage(String.format("%sYou will get **%d credits** if you sell all of your items!", EmoteReference.DIAMOND, all)).queue();
                return;
            }
            EmbedBuilder builder = baseEmbed(event, member.getEffectiveName() + "'s Inventory", member.getUser().getEffectiveAvatarUrl());
            List<ItemStack> list = player.getInventory().asList();
            List<MessageEmbed.Field> fields = new LinkedList<>();
            if (list.isEmpty())
                builder.setDescription("There is only dust here.");
            else
                player.getInventory().asList().forEach(stack -> {
                    long buyValue = stack.getItem().isBuyable() ? stack.getItem().getValue() : 0;
                    long sellValue = stack.getItem().isSellable() ? (long) (stack.getItem().getValue() * 0.9) : 0;
                    fields.add(new MessageEmbed.Field(stack.getItem().getEmoji() + " " + stack.getItem().getName() + " x " + stack.getAmount(), String.format("**Price**: \uD83D\uDCE5 %d \uD83D\uDCE4 %d\n%s", buyValue, sellValue, stack.getItem().getDesc()), false));
                });
            List<List<MessageEmbed.Field>> splitFields = DiscordUtils.divideFields(18, fields);
            boolean hasReactionPerms = event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION);
            if (hasReactionPerms) {
                DiscordUtils.list(event, 45, false, builder, splitFields);
            } else {
                DiscordUtils.listText(event, 45, false, builder, splitFields);
            }
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Inventory command").setDescription("**Shows your current inventory.**\n" + "You can use `~>inventory -brief` to get a mobile friendly version.\n" + "Use `~>inventory -calculate` to see how much you'd get if you sell every sellable item on your inventory!").build();
        }
    });
    cr.registerAlias("inventory", "inv");
}
Also used : 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) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) RethinkDB.r(com.rethinkdb.RethinkDB.r) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) OptArgs(com.rethinkdb.model.OptArgs) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) Connection(com.rethinkdb.net.Connection) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Stream(java.util.stream.Stream) User(net.dv8tion.jda.core.entities.User) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Item(net.kodehawa.mantarobot.commands.currency.item.Item) Player(net.kodehawa.mantarobot.db.entities.Player) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) List(java.util.List) Member(net.dv8tion.jda.core.entities.Member) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 45 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class CurrencyCmds method market.

@Subscribe
public void market(CommandRegistry cr) {
    final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 8);
    TreeCommand marketCommand = (TreeCommand) cr.register("market", 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) {
                    EmbedBuilder embed = baseEmbed(event, "Mantaro's Market").setThumbnail("https://png.icons8.com/metro/540/shopping-cart.png");
                    List<MessageEmbed.Field> fields = new LinkedList<>();
                    Stream.of(Items.ALL).forEach(item -> {
                        if (!item.isHidden()) {
                            String buyValue = item.isBuyable() ? String.format("$%d", item.getValue()) : "N/A";
                            String sellValue = item.isSellable() ? String.format("$%d", (int) Math.floor(item.getValue() * 0.9)) : "N/A";
                            fields.add(new MessageEmbed.Field(String.format("%s %s", item.getEmoji(), item.getName()), EmoteReference.BUY + buyValue + " " + EmoteReference.SELL + sellValue, true));
                        }
                    });
                    List<List<MessageEmbed.Field>> splitFields = DiscordUtils.divideFields(8, fields);
                    boolean hasReactionPerms = event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION);
                    if (hasReactionPerms) {
                        DiscordUtils.list(event, 120, false, embed, splitFields);
                    } else {
                        DiscordUtils.listText(event, 120, false, embed, splitFields);
                    }
                }
            };
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Mantaro's market").setDescription("**List current items for buying and selling.**").addField("Buying and selling", "To buy do ~>market buy <item emoji>. It will subtract the value from your money" + " and give you the item.\n" + "To sell do `~>market sell all` to sell all your items or `~>market sell <item emoji>` to sell the specified item. " + "**You'll get the sell value of the item on coins to spend.**\n" + "You can check the value of a single item using `~>market price <item emoji>`\n" + "You can send an item to the trash using `~>market dump <amount> <item emoji>`\n" + "Use `~>inventory -calculate` to check how much is your inventory worth.", false).addField("To know", "If you don't have enough money you cannot buy the items.\n" + "Note: Don't use the item id, it's just for aesthetic reasons, the internal IDs are different than the ones shown here!", false).addField("Information", "To buy and sell multiple items you need to do `~>market <buy/sell> <amount> <item>`", false).build();
        }
    });
    marketCommand.setPredicate((event) -> {
        if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
            return false;
        Player player = MantaroData.db().getPlayer(event.getMember());
        if (player.isLocked()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot access the market now.").queue();
            return false;
        }
        return true;
    });
    marketCommand.addSubCommand("dump", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            String itemName = content;
            int itemNumber = 1;
            boolean isMassive = !itemName.isEmpty() && itemName.split(" ")[0].matches("^[0-9]*$");
            if (isMassive) {
                try {
                    itemNumber = Math.abs(Integer.valueOf(itemName.split(" ")[0]));
                    itemName = itemName.replace(args[0], "").trim();
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid number of items to dump.").queue();
                    return;
                } catch (Exception e) {
                    onHelp(event);
                    return;
                }
            }
            Item item = Items.fromAny(itemName).orElse(null);
            if (item == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot check the dump a non-existent item!").queue();
                return;
            }
            Player player = MantaroData.db().getPlayer(event.getAuthor());
            if (!player.getInventory().containsItem(item)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot dump an item you don't have!").queue();
                return;
            }
            if (player.getInventory().getAmount(item) < itemNumber) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot dump more items than what you have.").queue();
                return;
            }
            player.getInventory().process(new ItemStack(item, -itemNumber));
            player.saveAsync();
            event.getChannel().sendMessage(String.format("%sSent %dx **%s %s** to the trash!", EmoteReference.CORRECT, itemNumber, item.getEmoji(), item.getName())).queue();
        }
    }).createSubCommandAlias("dump", "trash");
    marketCommand.addSubCommand("price", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            String itemName = content.replace(args[0] + " ", "");
            Item item = Items.fromAny(itemName).orElse(null);
            if (item == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot check the price of a non-existent item!").queue();
                return;
            }
            if (!item.isBuyable() && !item.isSellable()) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This item is not available neither for sell or buy (could be an exclusive collectible)").queue();
                return;
            }
            if (!item.isBuyable()) {
                event.getChannel().sendMessage(EmoteReference.EYES + "This is a collectible item. (Sell value: " + ((int) (item.getValue() * 0.9)) + " credits)").queue();
                return;
            }
            event.getChannel().sendMessage(String.format("%sThe market value of %s**%s** is %s credits to buy it and you can get %s credits if you sell it.", EmoteReference.MARKET, item.getEmoji(), item.getName(), item.getValue(), (int) (item.getValue() * 0.9))).queue();
        }
    });
    marketCommand.addSubCommand("sell", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Player player = MantaroData.db().getPlayer(event.getMember());
            String[] args = content.split(" ");
            String itemName = content;
            int itemNumber = 1;
            boolean isMassive = !itemName.isEmpty() && itemName.split(" ")[0].matches("^[0-9]*$");
            if (isMassive) {
                try {
                    itemNumber = Math.abs(Integer.valueOf(itemName.split(" ")[0]));
                    itemName = itemName.replace(args[0], "").trim();
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid number of items to buy.").queue();
                    return;
                } catch (Exception e) {
                    onHelp(event);
                    return;
                }
            }
            try {
                if (args[0].equals("all")) {
                    long all = player.getInventory().asList().stream().filter(item -> item.getItem().isSellable()).mapToLong(value -> (long) (value.getItem().getValue() * value.getAmount() * 0.9d)).sum();
                    player.getInventory().clearOnlySellables();
                    player.addMoney(all);
                    event.getChannel().sendMessage(String.format("%sYou sold all your inventory items and gained %d credits!", EmoteReference.MONEY, all)).queue();
                    player.saveAsync();
                    return;
                }
                Item toSell = Items.fromAny(itemName).orElse(null);
                if (toSell == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell a non-existant item.").queue();
                    return;
                }
                if (!toSell.isSellable()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell an item that cannot be sold.").queue();
                    return;
                }
                if (player.getInventory().getAmount(toSell) < 1) {
                    event.getChannel().sendMessage(EmoteReference.STOP + "You cannot sell an item you don't have.").queue();
                    return;
                }
                if (player.getInventory().getAmount(toSell) < itemNumber) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell more items than what you have.").queue();
                    return;
                }
                int many = itemNumber * -1;
                long amount = Math.round((toSell.getValue() * 0.9)) * Math.abs(many);
                player.getInventory().process(new ItemStack(toSell, many));
                player.addMoney(amount);
                player.getData().setMarketUsed(player.getData().getMarketUsed() + 1);
                event.getChannel().sendMessage(String.format("%sYou sold %d **%s** and gained %d credits!", EmoteReference.CORRECT, Math.abs(many), toSell.getName(), amount)).queue();
                player.saveAsync();
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid syntax.").queue();
            }
        }
    });
    marketCommand.addSubCommand("buy", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Player player = MantaroData.db().getPlayer(event.getMember());
            String[] args = content.split(" ");
            String itemName = content;
            int itemNumber = 1;
            boolean isMassive = !itemName.isEmpty() && itemName.split(" ")[0].matches("^[0-9]*$");
            if (isMassive) {
                try {
                    itemNumber = Math.abs(Integer.valueOf(itemName.split(" ")[0]));
                    itemName = itemName.replace(args[0], "").trim();
                } catch (Exception e) {
                    if (e instanceof NumberFormatException) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid number of items to buy.").queue();
                    } else {
                        onHelp(event);
                        return;
                    }
                }
            }
            Item itemToBuy = Items.fromAnyNoId(itemName).orElse(null);
            if (itemToBuy == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot buy an unexistant item.").queue();
                return;
            }
            try {
                if (!itemToBuy.isBuyable()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot buy an item that cannot be bought.").queue();
                    return;
                }
                ItemStack stack = player.getInventory().getStackOf(itemToBuy);
                if (stack != null && !stack.canJoin(new ItemStack(itemToBuy, itemNumber))) {
                    // assume overflow
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot buy more of that object!").queue();
                    return;
                }
                if (player.removeMoney(itemToBuy.getValue() * itemNumber)) {
                    player.getInventory().process(new ItemStack(itemToBuy, itemNumber));
                    player.getData().addBadgeIfAbsent(Badge.BUYER);
                    player.getData().setMarketUsed(player.getData().getMarketUsed() + 1);
                    player.saveAsync();
                    event.getChannel().sendMessage(String.format("%sBought %d %s for %d credits successfully. You now have %d credits.", EmoteReference.OK, itemNumber, itemToBuy.getEmoji(), itemToBuy.getValue() * itemNumber, player.getMoney())).queue();
                } else {
                    event.getChannel().sendMessage(EmoteReference.STOP + "You don't have enough money to buy this item.").queue();
                }
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid syntax.").queue();
            }
        }
    });
}
Also used : 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) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) RethinkDB.r(com.rethinkdb.RethinkDB.r) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) OptArgs(com.rethinkdb.model.OptArgs) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) Connection(com.rethinkdb.net.Connection) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Stream(java.util.stream.Stream) User(net.dv8tion.jda.core.entities.User) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Item(net.kodehawa.mantarobot.commands.currency.item.Item) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) Item(net.kodehawa.mantarobot.commands.currency.item.Item) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) List(java.util.List) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)67 Subscribe (com.google.common.eventbus.Subscribe)50 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)48 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)42 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)36 MantaroData (net.kodehawa.mantarobot.data.MantaroData)34 List (java.util.List)28 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)27 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)26 Utils (net.kodehawa.mantarobot.utils.Utils)26 TimeUnit (java.util.concurrent.TimeUnit)25 Collectors (java.util.stream.Collectors)25 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)25 Module (net.kodehawa.mantarobot.core.modules.Module)25 MantaroBot (net.kodehawa.mantarobot.MantaroBot)19 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)18 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)18 RateLimiter (net.kodehawa.mantarobot.utils.commands.RateLimiter)18 Slf4j (lombok.extern.slf4j.Slf4j)17 Player (net.kodehawa.mantarobot.db.entities.Player)17