Search in sources :

Example 11 with GuildData

use of net.kodehawa.mantarobot.db.entities.helpers.GuildData in project MantaroBot by Mantaro.

the class I18nTest method testI18n.

@Test
public void testI18n() throws LanguageKeyNotFoundException {
    // Should default to en_US
    I18nContext context = new I18nContext(new GuildData(), null);
    Assertions.assertEquals("en_US", context.getContextLanguage());
    String localized = context.get("test.inherited");
    Assertions.assertNotNull(localized);
    Assertions.assertEquals("owo", localized);
}
Also used : GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Test(org.junit.jupiter.api.Test)

Example 12 with GuildData

use of net.kodehawa.mantarobot.db.entities.helpers.GuildData in project MantaroBot by Mantaro.

the class AudioLoader method loadSingle.

private void loadSingle(AudioTrack audioTrack, boolean silent) {
    AudioTrackInfo trackInfo = audioTrack.getInfo();
    audioTrack.setUserData(event.getAuthor().getId());
    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
    DBUser dbUser = MantaroData.db().getUser(event.getMember());
    GuildData guildData = dbGuild.getData();
    String title = trackInfo.title;
    long length = trackInfo.length;
    long queueLimit = !Optional.ofNullable(dbGuild.getData().getMusicQueueSizeLimit()).isPresent() ? MAX_QUEUE_LENGTH : dbGuild.getData().getMusicQueueSizeLimit();
    int fqSize = guildData.getMaxFairQueue();
    if (musicManager.getTrackScheduler().getQueue().size() > queueLimit && !dbUser.isPremium() && !dbGuild.isPremium()) {
        if (!silent)
            event.getChannel().sendMessage(String.format(":warning: Could not queue %s: Surpassed queue song limit!", title)).queue(message -> message.delete().queueAfter(30, TimeUnit.SECONDS));
        return;
    }
    if (audioTrack.getInfo().length > MAX_SONG_LENGTH && !dbUser.isPremium() && !dbGuild.isPremium()) {
        event.getChannel().sendMessage(String.format(":warning: Could not queue %s: Track is longer than 32 minutes! (%s)", title, AudioUtils.getLength(length))).queue();
        return;
    }
    // Comparing if the URLs are the same to be 100% sure they're just not spamming the same url over and over again.
    if (musicManager.getTrackScheduler().getQueue().stream().filter(track -> track.getInfo().uri.equals(audioTrack.getInfo().uri)).count() > fqSize && !silent) {
        event.getChannel().sendMessage(EmoteReference.ERROR + String.format("**Surpassed fair queue level of %d (Too many songs which are exactly equal)**", fqSize + 1)).queue();
        return;
    }
    musicManager.getTrackScheduler().queue(audioTrack, insertFirst);
    musicManager.getTrackScheduler().setRequestedChannel(event.getChannel().getIdLong());
    if (!silent) {
        event.getChannel().sendMessage(new MessageBuilder().append(String.format("\uD83D\uDCE3 Added to queue -> **%s** **(%s)**", title, AudioUtils.getLength(length))).stripMentions(event.getGuild(), Message.MentionType.EVERYONE, Message.MentionType.HERE).build()).queue();
    }
    MantaroBot.getInstance().getStatsClient().increment("tracks_loaded");
}
Also used : Utils(net.kodehawa.mantarobot.utils.Utils) GuildMusicManager(net.kodehawa.mantarobot.commands.music.GuildMusicManager) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) Message(net.dv8tion.jda.core.entities.Message) MantaroBot(net.kodehawa.mantarobot.MantaroBot) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) AudioTrackInfo(com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) SentryHelper(net.kodehawa.mantarobot.utils.SentryHelper) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AudioUtils(net.kodehawa.mantarobot.commands.music.utils.AudioUtils) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) AudioTrackInfo(com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo) DBUser(net.kodehawa.mantarobot.db.entities.DBUser)

Example 13 with GuildData

use of net.kodehawa.mantarobot.db.entities.helpers.GuildData 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 14 with GuildData

use of net.kodehawa.mantarobot.db.entities.helpers.GuildData in project MantaroBot by Mantaro.

the class MantaroListener method onUserJoin.

private void onUserJoin(GuildMemberJoinEvent event) {
    DBGuild dbg = MantaroData.db().getGuild(event.getGuild());
    GuildData data = dbg.getData();
    try {
        String role = MantaroData.db().getGuild(event.getGuild()).getData().getGuildAutoRole();
        String hour = df.format(new Date(System.currentTimeMillis()));
        if (role != null) {
            try {
                if (!(event.getMember().getUser().isBot() && data.isIgnoreBotsAutoRole())) {
                    Role toAssign = event.getGuild().getRoleById(role);
                    if (toAssign != null) {
                        if (!event.getGuild().getSelfMember().canInteract(toAssign))
                            return;
                        event.getGuild().getController().addSingleRoleToMember(event.getMember(), toAssign).reason("Autorole assigner.").queue(s -> log.debug("Successfully added a new role to " + event.getMember()));
                        MantaroBot.getInstance().getStatsClient().increment("join_autorole");
                    }
                }
            } catch (Exception ignored) {
            }
        }
        String logChannel = MantaroData.db().getGuild(event.getGuild()).getData().getGuildLogChannel();
        if (logChannel != null) {
            TextChannel tc = event.getGuild().getTextChannelById(logChannel);
            if (tc != null && tc.canTalk()) {
                tc.sendMessage(String.format("`[%s]` \uD83D\uDCE3 `%s#%s` just joined `%s` `(User #%d | ID: %s)`", hour, event.getMember().getEffectiveName(), event.getMember().getUser().getDiscriminator(), event.getGuild().getName(), event.getGuild().getMembers().size(), event.getUser().getId())).queue();
            }
            logTotal++;
        }
    } catch (Exception e) {
        SentryHelper.captureExceptionContext("Failed to process join message!", e, MantaroListener.class, "Join Handler");
    }
    try {
        String joinChannel = data.getLogJoinLeaveChannel() == null ? data.getLogJoinChannel() : data.getLogJoinLeaveChannel();
        String joinMessage = data.getJoinMessage();
        sendJoinLeaveMessage(event, joinMessage, joinChannel);
        MantaroBot.getInstance().getStatsClient().increment("join_messages");
    } catch (Exception e) {
        SentryHelper.captureExceptionContext("Failed to send join message!", e, MantaroListener.class, "Join Handler");
    }
}
Also used : GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Date(java.util.Date) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 15 with GuildData

use of net.kodehawa.mantarobot.db.entities.helpers.GuildData in project MantaroBot by Mantaro.

the class CommandListener method onCommand.

private void onCommand(GuildMessageReceivedEvent event) {
    try {
        Member self = event.getGuild().getSelfMember();
        if (!self.getPermissions(event.getChannel()).contains(Permission.MESSAGE_WRITE) && !self.hasPermission(Permission.ADMINISTRATOR))
            return;
        if (commandProcessor.run(event)) {
            commandTotal++;
        } else {
            // Only run experience if no command has been executed, avoids weird race conditions when saving player status.
            try {
                // Only run experience if the user is not rate limited (clears every 30 seconds)
                if (random.nextInt(15) > 7 && !event.getAuthor().isBot() && experienceRatelimiter.process(event.getAuthor())) {
                    if (event.getMember() == null)
                        return;
                    // some nasty race conditions involving player save.
                    if (InteractiveOperations.get(event.getChannel()) != null)
                        return;
                    Player player = MantaroData.db().getPlayer(event.getAuthor());
                    PlayerData data = player.getData();
                    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
                    GuildData guildData = dbGuild.getData();
                    if (player.isLocked())
                        return;
                    // Set level to 1 if level is zero.
                    if (player.getLevel() == 0)
                        player.setLevel(1);
                    // Set player experience to a random number between 1 and 5.
                    data.setExperience(data.getExperience() + Math.round(random.nextInt(5)));
                    // Apply some black magic.
                    if (data.getExperience() > (player.getLevel() * Math.log10(player.getLevel()) * 1000) + (50 * player.getLevel() / 2)) {
                        player.setLevel(player.getLevel() + 1);
                        // Check if the member is not null, just to be sure it happened in-between.
                        if (player.getLevel() > 1 && event.getGuild().getMemberById(player.getUserId()) != null) {
                            if (guildData.isEnabledLevelUpMessages()) {
                                String levelUpChannel = guildData.getLevelUpChannel();
                                String levelUpMessage = guildData.getLevelUpMessage();
                                // Player has leveled up!
                                if (levelUpMessage != null && levelUpChannel != null) {
                                    processMessage(String.valueOf(player.getLevel()), levelUpMessage, levelUpChannel, event);
                                }
                            }
                        }
                    }
                    // This time, actually remember to save the player so you don't have to restart 102 shards to fix it.
                    player.saveAsync();
                }
            } catch (Exception ignored) {
            }
        }
    } catch (IndexOutOfBoundsException e) {
        event.getChannel().sendMessage(EmoteReference.ERROR + "Your query returned no results or you used the incorrect arguments, seemingly. Just in case, check command help!").queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            event.getChannel().sendMessage(String.format("%sI don't have permission to do this :<, I need the permission: **%s**%s", EmoteReference.ERROR, e.getPermission().getName(), e.getMessage() != null ? String.format(" | Message: %s", e.getMessage()) : "")).queue();
        } else {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot perform this action due to the lack of permission! Is the role I might be trying to assign" + " higher than my role? Do I have the correct permissions/hierarchy to perform this action?").queue();
        }
    } catch (IllegalArgumentException e) {
        // NumberFormatException == IllegalArgumentException
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        event.getChannel().sendMessage(String.format("%sI think you forgot something on the floor. (Maybe we threw it there? [Error ID: %s]... I hope we didn't)\n" + "- Incorrect type arguments or the message I'm trying to send exceeds 2048 characters, Just in case, check command help!", EmoteReference.ERROR, id)).queue();
        log.warn("Exception caught and alternate message sent. We should look into this, anyway (ID: {})", id, e);
    } catch (ReqlError e) {
        // So much just went wrong...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Database");
    } catch (RedisException e) {
        // So much just went wrong but on another side of the db...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Redis Database");
    } catch (Exception e) {
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        Player player = MantaroData.db().getPlayer(event.getAuthor());
        event.getChannel().sendMessage(String.format("%s%s\n(Error ID: `%s`)\n" + "If you want, join our **support guild** (Link on `~>about`), or check out our GitHub page (/Mantaro/MantaroBot). " + "Please tell them to quit exploding me and please don't forget the Error ID when reporting!", EmoteReference.ERROR, boomQuotes[rand.nextInt(boomQuotes.length)], id)).queue();
        if (player.getData().addBadgeIfAbsent(Badge.FIRE))
            player.saveAsync();
        SentryHelper.captureException(String.format("Unexpected Exception on Command: %s | (Error ID: ``%s``)", event.getMessage().getContentRaw(), id), e, this.getClass());
        log.error("Error happened with id: {} (Error ID: {})", event.getMessage().getContentRaw(), id, e);
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Player(net.kodehawa.mantarobot.db.entities.Player) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) ReqlError(com.rethinkdb.gen.exc.ReqlError) RedisException(org.redisson.client.RedisException) Member(net.dv8tion.jda.core.entities.Member) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) RedisException(org.redisson.client.RedisException) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException)

Aggregations

GuildData (net.kodehawa.mantarobot.db.entities.helpers.GuildData)17 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)16 MantaroData (net.kodehawa.mantarobot.data.MantaroData)11 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)11 Utils (net.kodehawa.mantarobot.utils.Utils)10 List (java.util.List)8 Subscribe (com.google.common.eventbus.Subscribe)7 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)6 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)6 TimeUnit (java.util.concurrent.TimeUnit)5 Consumer (java.util.function.Consumer)5 Collectors (java.util.stream.Collectors)5 Slf4j (lombok.extern.slf4j.Slf4j)5 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)5 MantaroBot (net.kodehawa.mantarobot.MantaroBot)5 java.awt (java.awt)4 TextChannel (net.dv8tion.jda.core.entities.TextChannel)4 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)4 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)4 CommandPermission (net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission)4