Search in sources :

Example 1 with BirthdayCacher

use of net.kodehawa.mantarobot.commands.utils.birthday.BirthdayCacher in project MantaroBot by Mantaro.

the class BirthdayCmd method birthday.

@Subscribe
public void birthday(CommandRegistry registry) {
    TreeCommand birthdayCommand = registry.register("birthday", new TreeCommand(CommandCategory.UTILS) {

        @Override
        public Command defaultTrigger(Context context, String mainCommand, String commandName) {
            return new SubCommand() {

                @Override
                protected void call(Context ctx, I18nContext languageContext, String content) {
                    if (content.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_content", EmoteReference.ERROR);
                        return;
                    }
                    // Twice. Yep.
                    var parseFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");
                    var displayFormat = DateTimeFormatter.ofPattern("dd-MM");
                    MonthDay birthdayDate;
                    String date;
                    var extra = "";
                    try {
                        String birthday;
                        birthday = content.replace("/", "-");
                        var parts = new ArrayList<>(Arrays.asList(birthday.split("-")));
                        if (Integer.parseInt(parts.get(0)) > 31 || Integer.parseInt(parts.get(1)) > 12) {
                            ctx.sendLocalized("commands.birthday.error_date", EmoteReference.ERROR);
                            return;
                        }
                        if (parts.size() > 2) {
                            ctx.sendLocalized("commands.birthday.new_format", EmoteReference.ERROR);
                            return;
                        }
                        // Add a year so it parses and saves using the old format. Yes, this is also cursed.
                        parts.add("2037");
                        date = String.join("-", parts);
                        birthdayDate = MonthDay.parse(birthday, displayFormat);
                    } catch (Exception e) {
                        ctx.sendStrippedLocalized("commands.birthday.error_date", EmoteReference.ERROR);
                        return;
                    }
                    final var display = displayFormat.format(birthdayDate);
                    // This whole leap year stuff is cursed when you work with dates using raw strings tbh.
                    // Only I could come up with such an idea like this on 2016. Now I regret it with pain... peko.
                    var leap = display.equals("29-02");
                    if (leap) {
                        extra += "\n" + languageContext.get("commands.birthday.leap");
                        // Cursed workaround since 2036 is a leap.
                        date = date.replace("2037", "2036");
                    }
                    final var birthdayFormat = parseFormat.format(parseFormat.parse(date));
                    // Actually save it to the user's profile.
                    DBUser dbUser = ctx.getDBUser();
                    dbUser.getData().setBirthday(birthdayFormat);
                    dbUser.saveUpdating();
                    ctx.sendLocalized("commands.birthday.added_birthdate", EmoteReference.CORRECT, display, extra);
                }
            };
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Sets your birthday date. Only useful if the server has enabled this functionality").setUsage("`~>birthday <date>`").addParameter("date", "A date in dd-mm format (13-02 for example). Check subcommands for more options.").build();
        }
    });
    birthdayCommand.addSubCommand("allowserver", new SubCommand() {

        public String description() {
            return "Allows the server where you send this command to announce your birthday.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var dbGuild = ctx.getDBGuild();
            var guildData = dbGuild.getData();
            if (guildData.getAllowedBirthdays().contains(ctx.getAuthor().getId())) {
                ctx.sendLocalized("commands.birthday.already_allowed", EmoteReference.ERROR);
                return;
            }
            guildData.getAllowedBirthdays().add(ctx.getAuthor().getId());
            dbGuild.save();
            var cached = guildBirthdayCache.getIfPresent(ctx.getGuild().getIdLong());
            var cachedBirthday = ctx.getBot().getBirthdayCacher().getCachedBirthdays().get(ctx.getUser().getIdLong());
            if (cached != null && cachedBirthday != null) {
                cached.put(ctx.getUser().getIdLong(), cachedBirthday);
            }
            ctx.sendLocalized("commands.birthday.allowed_server", EmoteReference.CORRECT);
        }
    });
    birthdayCommand.addSubCommand("denyserver", new SubCommand() {

        public String description() {
            return "Denies the server where you send this command to announce your birthday.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var dbGuild = ctx.getDBGuild();
            var guildData = dbGuild.getData();
            if (!guildData.getAllowedBirthdays().contains(ctx.getAuthor().getId())) {
                ctx.sendLocalized("commands.birthday.already_denied", EmoteReference.CORRECT);
                return;
            }
            guildData.getAllowedBirthdays().remove(ctx.getAuthor().getId());
            dbGuild.save();
            var cached = guildBirthdayCache.getIfPresent(ctx.getGuild().getIdLong());
            if (cached != null) {
                cached.remove(ctx.getUser().getIdLong());
            }
            ctx.sendLocalized("commands.birthday.denied", EmoteReference.CORRECT);
        }
    });
    birthdayCommand.addSubCommand("remove", new SubCommand() {

        @Override
        public String description() {
            return "Removes your set birthday date.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var user = ctx.getDBUser();
            user.getData().setBirthday(null);
            user.save();
            ctx.sendLocalized("commands.birthday.reset", EmoteReference.CORRECT);
        }
    });
    birthdayCommand.addSubCommand("list", new SubCommand() {

        @Override
        public String description() {
            return "Gives all of the birthdays for this server.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            BirthdayCacher cacher = MantaroBot.getInstance().getBirthdayCacher();
            try {
                if (cacher != null) {
                    var globalBirthdays = cacher.getCachedBirthdays();
                    if (globalBirthdays.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_global_birthdays", EmoteReference.SAD);
                        return;
                    }
                    var guild = ctx.getGuild();
                    var data = ctx.getDBGuild().getData();
                    var ids = data.getAllowedBirthdays().stream().map(Long::parseUnsignedLong).collect(Collectors.toList());
                    if (ids.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_guild_birthdays", EmoteReference.ERROR);
                        return;
                    }
                    var guildCurrentBirthdays = getBirthdayMap(ctx.getGuild().getIdLong(), ids);
                    if (guildCurrentBirthdays.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_guild_birthdays", EmoteReference.ERROR);
                        return;
                    }
                    var birthdays = guildCurrentBirthdays.entrySet().stream().sorted(Comparator.comparingLong(i -> i.getValue().day)).filter(birthday -> ids.contains(birthday.getKey())).limit(100).collect(Collectors.toList());
                    var bdIds = birthdays.stream().map(Map.Entry::getKey).collect(Collectors.toList());
                    guild.retrieveMembersByIds(bdIds).onSuccess(members -> sendBirthdayList(ctx, members, guildCurrentBirthdays, null, false));
                } else {
                    ctx.sendLocalized("commands.birthday.cache_not_running", EmoteReference.SAD);
                }
            } catch (Exception e) {
                ctx.sendLocalized("commands.birthday.error", EmoteReference.SAD);
                log.error("Error on birthday list display!", e);
            }
        }
    });
    birthdayCommand.addSubCommand("month", new SubCommand() {

        @Override
        public String description() {
            return "Checks the current birthday date for the specified month. Example: `~>birthday month 1`";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var args = ctx.getArguments();
            var cacher = MantaroBot.getInstance().getBirthdayCacher();
            var calendar = Calendar.getInstance();
            var month = calendar.get(Calendar.MONTH);
            var msg = "";
            if (args.length == 1) {
                msg = args[0];
            }
            if (!msg.isEmpty()) {
                try {
                    month = Integer.parseInt(msg);
                    if (month < 1 || month > 12) {
                        ctx.sendLocalized("commands.birthday.invalid_month", EmoteReference.ERROR);
                        return;
                    }
                    // Substract here so we can do the check properly up there.
                    month = month - 1;
                } catch (NumberFormatException e) {
                    ctx.sendLocalized("commands.birthday.invalid_month", EmoteReference.ERROR);
                    return;
                }
            }
            calendar.set(calendar.get(Calendar.YEAR), month, Calendar.MONDAY);
            try {
                if (cacher != null) {
                    final var cachedBirthdays = cacher.getCachedBirthdays();
                    if (cachedBirthdays.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_global_birthdays", EmoteReference.SAD);
                        return;
                    }
                    var data = ctx.getDBGuild().getData();
                    var ids = data.getAllowedBirthdays().stream().map(Long::parseUnsignedLong).collect(Collectors.toList());
                    var guildCurrentBirthdays = getBirthdayMap(ctx.getGuild().getIdLong(), ids);
                    if (ids.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_guild_birthdays", EmoteReference.ERROR);
                        return;
                    }
                    var calendarMonth = calendar.get(Calendar.MONTH) + 1;
                    var birthdays = guildCurrentBirthdays.entrySet().stream().filter(bds -> bds.getValue().month == calendarMonth).sorted(Comparator.comparingLong(i -> i.getValue().day)).limit(100).collect(Collectors.toList());
                    if (birthdays.isEmpty()) {
                        ctx.sendLocalized("commands.birthday.no_guild_month_birthdays", EmoteReference.ERROR, month + 1, EmoteReference.BLUE_SMALL_MARKER);
                        return;
                    }
                    var bdIds = birthdays.stream().map(Map.Entry::getKey).collect(Collectors.toList());
                    ctx.getGuild().retrieveMembersByIds(bdIds).onSuccess(members -> sendBirthdayList(ctx, members, guildCurrentBirthdays, calendar, true));
                } else {
                    ctx.sendLocalized("commands.birthday.cache_not_running", EmoteReference.SAD);
                }
            } catch (Exception e) {
                ctx.sendLocalized("commands.birthday.error", EmoteReference.SAD);
                log.error("Error on birthday month display!", e);
            }
        }
    });
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) Utils(net.kodehawa.mantarobot.utils.Utils) LoggerFactory(org.slf4j.LoggerFactory) Member(net.dv8tion.jda.api.entities.Member) MantaroBot(net.kodehawa.mantarobot.MantaroBot) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Subscribe(com.google.common.eventbus.Subscribe) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) DiscordUtils(net.kodehawa.mantarobot.utils.commands.DiscordUtils) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Logger(org.slf4j.Logger) MonthDay(java.time.MonthDay) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Collectors(java.util.stream.Collectors) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) BirthdayCacher(net.kodehawa.mantarobot.commands.utils.birthday.BirthdayCacher) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) DateTimeFormatter(java.time.format.DateTimeFormatter) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) MonthDay(java.time.MonthDay) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) BirthdayCacher(net.kodehawa.mantarobot.commands.utils.birthday.BirthdayCacher) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Cache (com.google.common.cache.Cache)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 Subscribe (com.google.common.eventbus.Subscribe)1 MonthDay (java.time.MonthDay)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 java.util (java.util)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Collectors (java.util.stream.Collectors)1 Member (net.dv8tion.jda.api.entities.Member)1 MantaroBot (net.kodehawa.mantarobot.MantaroBot)1 BirthdayCacher (net.kodehawa.mantarobot.commands.utils.birthday.BirthdayCacher)1 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)1 Module (net.kodehawa.mantarobot.core.modules.Module)1 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)1 TreeCommand (net.kodehawa.mantarobot.core.modules.commands.TreeCommand)1 Command (net.kodehawa.mantarobot.core.modules.commands.base.Command)1 CommandCategory (net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory)1 Context (net.kodehawa.mantarobot.core.modules.commands.base.Context)1 HelpContent (net.kodehawa.mantarobot.core.modules.commands.help.HelpContent)1 I18nContext (net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext)1