Search in sources :

Example 1 with MessageReceivedEvent

use of net.dv8tion.jda.api.events.message.MessageReceivedEvent in project Saber-Bot by notem.

the class ShardsCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    Consumer<String> sendMsg = (msg) -> {
        if (event.isFromType(ChannelType.PRIVATE)) {
            MessageUtilities.sendPrivateMsg(msg, event.getAuthor(), null);
        } else {
            MessageUtilities.sendMsg(msg, event.getTextChannel(), null);
        }
    };
    String msg = "I am not sharded!";
    if (Main.getShardManager().isSharding()) {
        msg = "```javascript\n" + "\"Total Shards\" (" + Main.getBotSettingsManager().getShardTotal() + ")\n";
        for (JDA shard : Main.getShardManager().getShards()) {
            JDA.ShardInfo info = shard.getShardInfo();
            msg += "\n[Shard-" + info.getShardId() + "]\n" + "       Status: \"" + shard.getStatus().toString() + "\"\n" + "         Ping: \"" + shard.getGatewayPing() + "\"\n" + "       Guilds: \"" + shard.getGuilds().size() + "\"\n" + "        Users: \"" + shard.getUsers().size() + "\"\n" + "ResponseTotal: \"" + shard.getResponseTotal() + "\"\n";
            if (msg.length() > 1900) {
                msg += "```";
                sendMsg.accept(msg);
                msg = "```javascript\n";
            }
        }
        msg += "```";
    }
    sendMsg.accept(msg);
}
Also used : Consumer(java.util.function.Consumer) Command(ws.nmathe.saber.commands.Command) JDA(net.dv8tion.jda.api.JDA) CommandInfo(ws.nmathe.saber.commands.CommandInfo) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Main(ws.nmathe.saber.Main) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) ChannelType(net.dv8tion.jda.api.entities.ChannelType) JDA(net.dv8tion.jda.api.JDA)

Example 2 with MessageReceivedEvent

use of net.dv8tion.jda.api.events.message.MessageReceivedEvent in project Saber-Bot by notem.

the class InitCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    String body;
    if (args.length > 0) {
        boolean isAChannel = false;
        TextChannel chan = null;
        String chanId = null;
        try {
            chanId = args[0].replaceAll("[^\\d]", "");
            chan = event.getGuild().getTextChannelById(chanId);
            if (chan != null)
                isAChannel = true;
        } catch (Exception ignored) {
        }
        if (// use the argument as the new channel's name
        !isAChannel) {
            String chanTitle = args[0].replaceAll("[^A-Za-z0-9_ \\-]", "").replaceAll("[ ]", "_");
            Main.getScheduleManager().createSchedule(event.getGuild().getId(), chanTitle);
            body = "A new schedule channel named **" + chanTitle.toLowerCase() + "** has been created!\n" + "You can now use the create command to create events on that schedule, or the sync command to sync " + "that schedule to a Google Calendar.";
        } else // convert the channel to a schedule
        {
            if (Main.getScheduleManager().isSchedule(chan.getId())) {
                // clear the channel of events
                TextChannel finalChan = chan;
                Main.getDBDriver().getEventCollection().find(eq("channelId", chan.getId())).forEach((Consumer<? super Document>) document -> {
                    String msgId = document.getString("messageId");
                    finalChan.deleteMessageById(msgId).complete();
                    Main.getEntryManager().removeEntry(document.getInteger("_id"));
                });
                body = "The schedule <#" + chanId + "> has been cleared!";
            } else {
                // create a new schedule
                Main.getScheduleManager().createSchedule(chan);
                body = "The channel <#" + chanId + "> has been converted to a schedule channel!\n" + "You can now use the create command to create events on that schedule, or the sync " + "command to sync that schedule to a Google Calendar.";
            }
        }
    } else // create a new schedule using the default name
    {
        Main.getScheduleManager().createSchedule(event.getGuild().getId(), null);
        body = "A new schedule channel named **new_schedule** has been created!\n" + "You can now use the create command to create events on that schedule, or the sync command" + " to sync that schedule to a Google Calendar.";
    }
    MessageUtilities.sendMsg(body, event.getChannel(), null);
}
Also used : Document(org.bson.Document) Consumer(java.util.function.Consumer) Command(ws.nmathe.saber.commands.Command) CommandInfo(ws.nmathe.saber.commands.CommandInfo) Permission(net.dv8tion.jda.api.Permission) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) TextChannel(net.dv8tion.jda.api.entities.TextChannel)

Example 3 with MessageReceivedEvent

use of net.dv8tion.jda.api.events.message.MessageReceivedEvent in project Saber-Bot by notem.

the class PurgeCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    TextChannel channel = event.getGuild().getJDA().getTextChannelById(args[0].replaceAll("[^\\d]", ""));
    // number of messages to remove
    Integer[] count = { 100 };
    // ID of bot to check messages against
    String botId = event.getJDA().getSelfUser().getId();
    processing.put(event.getGuild().getId(), channel.getId());
    channel.getIterableHistory().stream().filter(message -> message.getAuthor().getId().equals(botId) && (count[0]-- > 0)).forEach((message -> {
        message.getChannel().sendTyping().queue();
        // sleep for half a second before continuing
        try {
            Thread.sleep(500);
        } catch (InterruptedException ignored) {
        }
        Bson query = eq("messageId", message.getId());
        if (Main.getDBDriver().getEventCollection().count(query) == 0) {
            MessageUtilities.deleteMsg(message);
        }
    }));
    processing.remove(event.getGuild().getId(), channel.getId());
    // send success message
    String content = "Finished purging old message.";
    MessageUtilities.sendMsg(content, event.getTextChannel(), null);
}
Also used : Bson(org.bson.conversions.Bson) Command(ws.nmathe.saber.commands.Command) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) CommandInfo(ws.nmathe.saber.commands.CommandInfo) RateLimiter(ws.nmathe.saber.core.RateLimiter) Map(java.util.Map) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Bson(org.bson.conversions.Bson)

Example 4 with MessageReceivedEvent

use of net.dv8tion.jda.api.events.message.MessageReceivedEvent in project Saber-Bot by notem.

the class ListCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    int index = 0;
    Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
    ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());
    String titleUrl = se.getTitleUrl() == null ? "https://nnmathe.ws/saber" : se.getTitleUrl();
    String title = se.getTitle() + " [" + ParsingUtilities.intToEncodedID(entryId) + "]";
    String content = "";
    List<String> userFilters = new ArrayList<>();
    List<String> roleFilters = new ArrayList<>();
    boolean filterByType = false;
    Set<String> typeFilters = new HashSet<>();
    boolean mobileFlag = false;
    boolean IdFlag = false;
    for (; index < args.length; index++) {
        if (args[index].equalsIgnoreCase("mobile") || args[index].equalsIgnoreCase("m")) {
            mobileFlag = true;
            continue;
        }
        if (args[index].equalsIgnoreCase("id") || args[index].equalsIgnoreCase("i")) {
            IdFlag = true;
            continue;
        }
        String filterType = args[index].split(":")[0].toLowerCase().trim();
        String filterValue = args[index].split(":")[1].trim();
        switch(filterType.toLowerCase()) {
            case "r":
            case "role":
                roleFilters.add(filterValue.replace("<@&", "").replace(">", ""));
                break;
            case "u":
            case "user":
                userFilters.add(filterValue.replace("<@", "").replace(">", ""));
                break;
            case "t":
            case "type":
                filterByType = true;
                typeFilters.add(filterValue);
                break;
        }
    }
    // maximum number of characters before creating a new message
    int lengthCap = 1900;
    // maximum number of lines until new message, in mobile mode
    int mobileLineCap = 25;
    Set<String> uniqueMembers = new HashSet<>();
    Map<String, String> options = Main.getScheduleManager().getRSVPOptions(se.getChannelId());
    for (String type : options.values()) {
        if (!filterByType || typeFilters.contains(type)) {
            content += "**\"" + type + "\"\n======================**\n";
            Set<String> members = se.getRsvpMembersOfType(type);
            for (String id : members) {
                // if the message is nearing maximum length, or if in mobile mode and the max lines have been reached
                if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
                    // build and send the embedded message object
                    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
                    MessageUtilities.sendMsg(message, event.getChannel(), null);
                    // clear the content sting
                    content = "*continued. . .* \n";
                }
                if (id.matches("\\d+")) {
                    // cases in which the id is most likely a valid discord user's ID
                    Member member = event.getGuild().getMemberById(id);
                    if (checkMember(member, userFilters, roleFilters)) {
                        // if the user is still a member of the guild, add to the list
                        uniqueMembers.add(member.getUser().getId());
                        content += this.getNameDisplay(mobileFlag, IdFlag, member);
                    } else // otherwise, remove the member from the event and update
                    {
                        Set<String> tmp = se.getRsvpMembersOfType(type);
                        tmp.remove(id);
                        se.getRsvpMembersOfType(type).remove(id);
                        Main.getEntryManager().updateEntry(se, false);
                    }
                } else {
                    // handles cases in which a non-discord user was added by an admin
                    uniqueMembers.add(id);
                    content += "*" + id + "*\n";
                }
            }
        }
        content += "\n";
    }
    if (!filterByType || typeFilters.contains("no-input")) {
        // generate a list of all members of the guild who pass the filter and map to their ID
        List<String> noInput = event.getGuild().getMembers().stream().filter(member -> checkMember(member, userFilters, roleFilters)).map(member -> member.getUser().getId()).collect(Collectors.toList());
        for (String type : options.values()) {
            noInput.removeAll(se.getRsvpMembersOfType(type));
        }
        content += "**No input\n======================\n**";
        if (!filterByType & noInput.size() > 10) {
            content += " Too many users to show: " + noInput.size() + " users with no rsvp\n";
        } else
            for (String id : noInput) {
                if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
                    // build and send the embedded message object
                    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
                    MessageUtilities.sendMsg(message, event.getChannel(), null);
                    // clear the content sting
                    content = "*continued. . .* \n";
                }
                Member member = event.getGuild().getMemberById(id);
                content += this.getNameDisplay(mobileFlag, IdFlag, member);
            }
    }
    String footer = uniqueMembers.size() + " unique member(s) appear in this search";
    // build and send the embedded message object
    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).setFooter(footer, null).build()).build();
    MessageUtilities.sendMsg(message, event.getChannel(), null);
}
Also used : Message(net.dv8tion.jda.api.entities.Message) Command(ws.nmathe.saber.commands.Command) java.util(java.util) CommandInfo(ws.nmathe.saber.commands.CommandInfo) ISnowflake(net.dv8tion.jda.api.entities.ISnowflake) Logging(ws.nmathe.saber.utils.Logging) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) StringUtils(org.apache.commons.lang3.StringUtils) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Collectors(java.util.stream.Collectors) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Role(net.dv8tion.jda.api.entities.Role) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Main(ws.nmathe.saber.Main) VerifyUtilities(ws.nmathe.saber.utils.VerifyUtilities) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) ParsingUtilities(ws.nmathe.saber.utils.ParsingUtilities) Message(net.dv8tion.jda.api.entities.Message) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Member(net.dv8tion.jda.api.entities.Member)

Example 5 with MessageReceivedEvent

use of net.dv8tion.jda.api.events.message.MessageReceivedEvent in project Saber-Bot by notem.

the class ConfigCommand method action.

@Override
public void action(String head, String[] args, MessageReceivedEvent event) {
    int index = 0;
    String cId = args[index].replaceAll("[^\\d]", "");
    TextChannel scheduleChan = event.getGuild().getTextChannelById(cId);
    index++;
    if (args.length > 1) {
        switch(args[index++].toLowerCase()) {
            case "m":
            case "msg":
            case "message":
                String msgFormat = formatHelper(args[index]);
                Main.getScheduleManager().setAnnounceFormat(scheduleChan.getId(), msgFormat);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "ch":
            case "chan":
            case "channel":
                String chanIdentifier = args[index].matches("<#[\\d]+>") ? args[index].replaceAll("[^\\d]", "") : args[index];
                Main.getScheduleManager().setAnnounceChan(scheduleChan.getId(), chanIdentifier);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "em":
            case "end-msg":
            case "end-message":
                String endFormat;
                endFormat = formatHelper(args[index]);
                Main.getScheduleManager().setEndAnnounceFormat(scheduleChan.getId(), endFormat);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "ech":
            case "end-chan":
            case "end-channel":
                String endChanIdentifier;
                switch(args[index].toLowerCase()) {
                    case "reset":
                    case "default":
                    case "null":
                        endChanIdentifier = null;
                        break;
                    default:
                        endChanIdentifier = args[index].matches("<#[\\d]+>") ? args[index].replaceAll("[^\\d]", "") : args[index];
                }
                Main.getScheduleManager().setEndAnnounceChan(scheduleChan.getId(), endChanIdentifier);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "z":
            case "zone":
            case "zones":
                HashSet<ZoneId> altZones = new HashSet<>();
                altZones.addAll(Main.getScheduleManager().getAltZones(scheduleChan.getId()));
                ZoneId primaryZone = Main.getScheduleManager().getTimeZone(scheduleChan.getId());
                ZoneId zone;
                switch(args[index].toLowerCase()) {
                    case "a":
                    case "add":
                        index++;
                        zone = ParsingUtilities.parseZone(args[index]);
                        // Note: different zones can have the same timezone offset (eg. same zones, different names)
                        if (!primaryZone.equals(zone)) {
                            altZones.add(zone);
                        }
                        break;
                    case "r":
                    case "remove":
                        index++;
                        zone = ParsingUtilities.parseZone(args[index]);
                        // remove the zone from the alt zones list
                        altZones.remove(zone);
                        // if so, replace the primary zone with the next alt zone (only if available)
                        if (primaryZone.equals(zone) && altZones.size() > 0) {
                            primaryZone = altZones.iterator().next();
                            // disable auto-sync'ing timezone
                            Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", scheduleChan.getId()), set("timezone_sync", false));
                        }
                        break;
                    default:
                        primaryZone = ParsingUtilities.parseZone(args[index]);
                        altZones.remove(primaryZone);
                        // disable auto-sync'ing timezone
                        Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", scheduleChan.getId()), set("timezone_sync", false));
                        break;
                }
                // set the primary and alt zones
                Main.getScheduleManager().setTimeZone(scheduleChan.getId(), primaryZone);
                Main.getScheduleManager().setAltZones(scheduleChan.getId(), new ArrayList<>(altZones));
                // reload each entry on the schedule
                Main.getEntryManager().getEntriesFromChannel(scheduleChan.getId()).forEach(se -> Main.getEntryManager().reloadEntry(se.getId()));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                break;
            case "cl":
            case "clock":
                Main.getScheduleManager().setClockFormat(scheduleChan.getId(), args[index]);
                // reload the schedule display
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> Main.getEntryManager().reloadEntry((Integer) document.get("_id")));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                break;
            case "s":
            case "sync":
                Credential credential = GoogleAuth.getCredential(event.getAuthor().getId());
                if (credential == null)
                    break;
                Calendar service = GoogleAuth.getCalendarService(credential);
                if (Main.getCalendarConverter().checkValidAddress(args[index], service))
                    Main.getScheduleManager().setAddress(scheduleChan.getId(), args[index]);
                else
                    Main.getScheduleManager().setAddress(scheduleChan.getId(), "off");
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.SYNC, event.getJDA()), event.getChannel(), null);
                break;
            case "t":
            case "time":
                ZonedDateTime syncTime = ZonedDateTime.of(LocalDate.now(), ParsingUtilities.parseTime(args[index], null), Main.getScheduleManager().getTimeZone(cId));
                // don't allow times set in the past
                if (syncTime.isBefore(ZonedDateTime.now()))
                    syncTime.plusDays(1);
                Main.getScheduleManager().setSyncTime(cId, Date.from(syncTime.toInstant()));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.SYNC, event.getJDA()), event.getChannel(), null);
                break;
            case "r":
            case "remind":
            case "reminder":
            case "reminders":
                Set<Integer> list = this.reminderHelper(args, index, cId);
                // convert set to a list
                List<Integer> rem = new ArrayList<>(list);
                Main.getScheduleManager().setReminders(cId, rem);
                // for every entry on channel, update
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                    ScheduleEntry se = new ScheduleEntry(document).reloadReminders(Main.getScheduleManager().getReminders(scheduleChan.getId()));
                    Main.getEntryManager().updateEntry(se, false);
                });
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "er":
            case "end-remind":
            case "end-reminder":
            case "end-reminders":
                Set<Integer> list2 = this.reminderHelper(args, index, cId);
                // convert set to a list
                List<Integer> rem2 = new ArrayList<>(list2);
                Main.getScheduleManager().setEndReminders(cId, rem2);
                // for every entry on channel, update
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                    ScheduleEntry se = new ScheduleEntry(document).reloadEndReminders(Main.getScheduleManager().getEndReminders(scheduleChan.getId()));
                    Main.getEntryManager().updateEntry(se, false);
                });
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "rm":
            case "rem-msg":
            case "remind-msg":
            case "remind-message":
                String remindFormat;
                remindFormat = formatHelper(args[index]);
                Main.getScheduleManager().setReminderFormat(scheduleChan.getId(), remindFormat);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "rc":
            case "rem-chan":
            case "remind-chan":
            case "remind-channel":
                String remindChanIdentifier;
                switch(args[index].toLowerCase()) {
                    case "reset":
                    case "default":
                    case "null":
                        remindChanIdentifier = null;
                        break;
                    default:
                        remindChanIdentifier = args[index].matches("<#[\\d]+>") ? args[index].replaceAll("[^\\d]", "") : args[index];
                        break;
                }
                Main.getScheduleManager().setReminderChan(scheduleChan.getId(), remindChanIdentifier);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "rsvp":
                boolean enabled = Main.getScheduleManager().isRSVPEnabled(cId);
                Map<String, String> options = Main.getScheduleManager().getRSVPOptions(cId);
                Boolean new_enabled = null;
                switch(args[index++].toLowerCase()) {
                    case "add":
                    case "a":
                        String emoji = args[index + 1].trim();
                        if (!EmojiManager.isEmoji(emoji)) {
                            // split on colons to isolate the reaction name from it's ID
                            String[] split = emoji.split(":");
                            // trim to include only the ID
                            emoji = split[split.length - 1].replaceAll("[^\\d]", "");
                        }
                        options.put(emoji, args[index].trim());
                        Main.getScheduleManager().setRSVPOptions(cId, options);
                        break;
                    case "remove":
                    case "r":
                        if (options.containsKey(args[index])) {
                            options.remove(args[index]);
                        } else if (options.containsValue(args[index])) {
                            options.values().remove(args[index]);
                        }
                        Main.getScheduleManager().setRSVPOptions(cId, options);
                        break;
                    case "on":
                    case "true":
                        new_enabled = true;
                        break;
                    case "off":
                    case "false":
                        new_enabled = false;
                        break;
                }
                String clearEmoji = Main.getScheduleManager().getRSVPClear(cId);
                // if add or remove option was used, clear the reactions and re-add the new reactions
                if (new_enabled == null) {
                    // for each entry on the schedule
                    Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                        event.getGuild().getTextChannelById(document.getString("channelId")).retrieveMessageById(document.getString("messageId")).complete().clearReactions().queue((message) -> {
                            Map<String, String> map = Main.getScheduleManager().getRSVPOptions(document.getString("channelId"));
                            ScheduleEntry se = new ScheduleEntry(document);
                            event.getGuild().getTextChannelById(document.getString("channelId")).retrieveMessageById(document.getString("messageId")).queue(msg -> EntryManager.addRSVPReactions(map, clearEmoji, msg, se));
                        });
                        Main.getEntryManager().reloadEntry(document.getInteger("_id"));
                    });
                } else // otherwise, if the rsvp setting was changes
                if (enabled != new_enabled) {
                    // set schedule settings
                    Main.getScheduleManager().setRSVPEnable(cId, new_enabled);
                    if (new_enabled) {
                        // for each entry on the schedule
                        Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                            Map<String, String> map = Main.getScheduleManager().getRSVPOptions(document.getString("channelId"));
                            ScheduleEntry se = new ScheduleEntry(document);
                            event.getGuild().getTextChannelById(document.getString("channelId")).retrieveMessageById(document.getString("messageId")).queue(msg -> EntryManager.addRSVPReactions(map, clearEmoji, msg, se));
                            Main.getEntryManager().reloadEntry(document.getInteger("_id"));
                        });
                    } else {
                        // for each entry on the schedule
                        Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                            event.getGuild().getTextChannelById(document.getString("channelId")).retrieveMessageById(document.getString("messageId")).complete().clearReactions().queue();
                            Main.getEntryManager().reloadEntry(document.getInteger("_id"));
                        });
                    }
                }
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "c":
            case "clear":
                String emoji = args[index].trim();
                if (emoji.equalsIgnoreCase("off")) {
                    emoji = "";
                } else if (!EmojiManager.isEmoji(emoji)) {
                    emoji = emoji.replaceAll("[^\\d]", "");
                }
                Main.getScheduleManager().setRSVPClear(cId, emoji);
                // update reactions on all event messages in channel
                String finalEmoji = emoji;
                Map<String, String> rsvpOptions = Main.getScheduleManager().getRSVPOptions(cId);
                Main.getEntryManager().getEntriesFromChannel(cId).forEach(se -> {
                    Message message = se.getMessageObject();
                    message.clearReactions().complete();
                    EntryManager.addRSVPReactions(rsvpOptions, finalEmoji, message, se);
                });
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "co":
            case "confirm":
            case "confirmation":
            case "confirmations":
                boolean confirmation = true;
                switch(args[index].toLowerCase()) {
                    case "no":
                    case "false":
                    case "off":
                        confirmation = false;
                        break;
                }
                Main.getScheduleManager().setRSVPConfirmations(cId, confirmation);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "ex":
            case "exclude":
            case "exclusivity":
                boolean exclusive = true;
                switch(args[index].toLowerCase()) {
                    case "no":
                    case "off":
                    case "false":
                        exclusive = false;
                        break;
                }
                Main.getScheduleManager().setRSVPExclusivity(cId, exclusive);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "log":
            case "logging":
                String loggingChannel = null;
                switch(args[index].toLowerCase()) {
                    case "no":
                    case "off":
                    case "false":
                        break;
                    default:
                        loggingChannel = args[index].matches("<#[\\d]+>") ? args[index].replaceAll("[^\\d]", "") : null;
                        break;
                }
                Main.getScheduleManager().setRSVPLoggingChannel(cId, loggingChannel);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "st":
            case "style":
                String style = args[index].toLowerCase();
                if (style.equals("full"))
                    Main.getScheduleManager().setStyle(cId, style);
                else if (style.equals("narrow"))
                    Main.getScheduleManager().setStyle(cId, style);
                // for each entry on the schedule
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> Main.getEntryManager().reloadEntry(document.getInteger("_id")));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                break;
            case "l":
            case "len":
            case "length":
                Main.getScheduleManager().setSyncLength(cId, Integer.parseInt(args[index]));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.SYNC, event.getJDA()), event.getChannel(), null);
                break;
            case "so":
            case "sort":
                int sortType;
                switch(args[index]) {
                    case "on":
                    case "asc":
                    case "ascending":
                        sortType = 1;
                        break;
                    case "desc":
                    case "descending":
                        sortType = 2;
                        break;
                    default:
                        sortType = 0;
                        break;
                }
                Main.getScheduleManager().setAutoSort(cId, sortType);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                // now sort the schedule
                if (sortType == 1)
                    Main.getScheduleManager().sortSchedule(cId, false);
                if (sortType == 2)
                    Main.getScheduleManager().sortSchedule(cId, true);
                break;
        }
    } else // print out all settings
    {
        MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.FULL, event.getJDA()), event.getChannel(), null);
    }
}
Also used : Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) Command(ws.nmathe.saber.commands.Command) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) CommandInfo(ws.nmathe.saber.commands.CommandInfo) Updates.set(com.mongodb.client.model.Updates.set) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Collectors(java.util.stream.Collectors) GoogleAuth(ws.nmathe.saber.core.google.GoogleAuth) Consumer(java.util.function.Consumer) EmojiManager(com.vdurmont.emoji.EmojiManager) java.time(java.time) ChronoUnit(java.time.temporal.ChronoUnit) EntryManager(ws.nmathe.saber.core.schedule.EntryManager) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Filters.eq(com.mongodb.client.model.Filters.eq) Credential(com.google.api.client.auth.oauth2.Credential) Calendar(com.google.api.services.calendar.Calendar) Main(ws.nmathe.saber.Main) VerifyUtilities(ws.nmathe.saber.utils.VerifyUtilities) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) ParsingUtilities(ws.nmathe.saber.utils.ParsingUtilities) Credential(com.google.api.client.auth.oauth2.Credential) Calendar(com.google.api.services.calendar.Calendar) Document(org.bson.Document) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Consumer(java.util.function.Consumer)

Aggregations

MessageReceivedEvent (net.dv8tion.jda.api.events.message.MessageReceivedEvent)5 Main (ws.nmathe.saber.Main)5 Command (ws.nmathe.saber.commands.Command)5 CommandInfo (ws.nmathe.saber.commands.CommandInfo)5 MessageUtilities (ws.nmathe.saber.utils.MessageUtilities)5 Filters.eq (com.mongodb.client.model.Filters.eq)3 Consumer (java.util.function.Consumer)3 java.util (java.util)2 Collectors (java.util.stream.Collectors)2 JDA (net.dv8tion.jda.api.JDA)2 TextChannel (net.dv8tion.jda.api.entities.TextChannel)2 Document (org.bson.Document)2 ScheduleEntry (ws.nmathe.saber.core.schedule.ScheduleEntry)2 ParsingUtilities (ws.nmathe.saber.utils.ParsingUtilities)2 VerifyUtilities (ws.nmathe.saber.utils.VerifyUtilities)2 Credential (com.google.api.client.auth.oauth2.Credential)1 Calendar (com.google.api.services.calendar.Calendar)1 Updates.set (com.mongodb.client.model.Updates.set)1 EmojiManager (com.vdurmont.emoji.EmojiManager)1 java.time (java.time)1