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);
}
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");
}
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;
}
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");
}
}
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);
}
}
Aggregations