Search in sources :

Example 16 with ScheduleEntry

use of ws.nmathe.saber.core.schedule.ScheduleEntry in project Saber-Bot by notem.

the class AnnouncementsCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    int index = 0;
    // get entry object
    Integer entryId = ParsingUtilities.encodeIDToInt(args[index]);
    ScheduleEntry entry = Main.getEntryManager().getEntry(entryId);
    // verify the entry's message exists
    Message msg = entry.getMessageObject();
    if (msg == null)
        return;
    index++;
    if (args.length > 2) {
        // if additional args have been provided. . .
        switch(args[index++].toLowerCase()) {
            case "a":
            case "add":
                String target = args[index].replaceAll("[^\\d]", "");
                String time = args[index + 1];
                String message = args[index + 2];
                entry.addAnnouncementOverride(target, time, message);
                break;
            case "r":
            case "remove":
                Integer id = Integer.parseInt(args[index].replaceAll("[^\\d]", "")) - 1;
                entry.removeAnnouncementOverride(id);
                break;
            case "qs":
            case "quiet-start":
                entry.setQuietStart(!entry.isQuietStart());
                break;
            case "qe":
            case "quiet-end":
                entry.setQuietEnd(!entry.isQuietEnd());
                break;
            case "qr":
            case "quiet-remind":
                entry.setQuietRemind(!entry.isQuietRemind());
                break;
            case "qa":
            case "quiet-all":
                if (entry.isQuietRemind() && entry.isQuietEnd() && entry.isQuietStart()) {
                    entry.setQuietRemind(false).setQuietEnd(false).setQuietStart(false);
                } else {
                    entry.setQuietRemind(true).setQuietEnd(true).setQuietStart(true);
                }
                break;
        }
        Main.getEntryManager().updateEntry(entry, false);
    }
    /*
         * generate output message
         */
    String content = "```js\n// Schedule Announcements\n";
    if (!entry.isQuietStart()) {
        String format = Main.getScheduleManager().getStartAnnounceFormat(entry.getChannelId());
        if (!format.isEmpty()) {
            String target = Main.getScheduleManager().getStartAnnounceChan(entry.getChannelId());
            if (target.matches("\\d+")) {
                JDA jda = Main.getShardManager().getJDA(entry.getGuildId());
                try {
                    target = jda.getTextChannelById(target).getName();
                } catch (Exception ignored) {
                }
            }
            content += "[s] \"" + format + "\" at \"START\" on \"#" + target + "\"\n";
        }
    }
    if (!entry.isQuietEnd()) {
        String format = Main.getScheduleManager().getEndAnnounceFormat(entry.getChannelId());
        if (!format.isEmpty()) {
            String target = Main.getScheduleManager().getEndAnnounceChan(entry.getChannelId());
            if (target.matches("\\d+")) {
                JDA jda = Main.getShardManager().getJDA(entry.getGuildId());
                try {
                    target = jda.getTextChannelById(target).getName();
                } catch (Exception ignored) {
                }
            }
            content += "[e] \"" + format + "\" at \"END\" on \"#" + target + "\"\n";
        }
    }
    if (!entry.isQuietRemind()) {
        String format = Main.getScheduleManager().getReminderFormat(entry.getChannelId());
        String target = Main.getScheduleManager().getReminderChan(entry.getChannelId());
        if (target.matches("\\d+")) {
            JDA jda = Main.getShardManager().getJDA(entry.getGuildId());
            try {
                target = jda.getTextChannelById(target).getName();
            } catch (Exception ignored) {
            }
        }
        for (Integer reminder : Main.getScheduleManager().getReminders(entry.getChannelId())) {
            content += "[r] \"" + format + "\" at \"START" + (reminder > 0 ? "-" + reminder : "+" + Math.abs(reminder)) + "m\" on \"#" + target + "\"\n";
        }
        format = Main.getScheduleManager().getReminderFormat(entry.getChannelId());
        for (Integer reminder : Main.getScheduleManager().getEndReminders(entry.getChannelId())) {
            content += "[r] \"" + format + "\" at \"END" + (reminder > 0 ? "-" + reminder : "+" + Math.abs(reminder)) + "m\" on \"#" + target + "\"\n";
        }
    }
    if (!entry.getAnnouncementTimes().values().isEmpty()) {
        content += entry.announcementsToString();
    }
    content += "```";
    MessageUtilities.sendMsg(content, event.getChannel(), null);
}
Also used : ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Message(net.dv8tion.jda.core.entities.Message) JDA(net.dv8tion.jda.core.JDA)

Example 17 with ScheduleEntry

use of ws.nmathe.saber.core.schedule.ScheduleEntry in project Saber-Bot by notem.

the class EventListener method onGuildMemberLeave.

@Override
@SuppressWarnings("unchecked")
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
    String memberId = event.getMember().getUser().getId();
    // remove user from any events they have rsvp'ed to
    Collection<ScheduleEntry> entries = Main.getEntryManager().getEntriesFromGuild(event.getGuild().getId());
    for (ScheduleEntry se : entries) {
        boolean updateFlag = false;
        // check each rsvp group on the entry
        for (String key : se.getRsvpMembers().keySet()) {
            if (se.getRsvpMembersOfType(key).contains(memberId)) {
                // remove the user and flag the entry for updating
                se.getRsvpMembersOfType(key).remove(memberId);
                updateFlag = true;
            }
        }
        if (updateFlag) {
            Main.getEntryManager().updateEntry(se, false);
        }
    }
}
Also used : ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry)

Example 18 with ScheduleEntry

use of ws.nmathe.saber.core.schedule.ScheduleEntry in project Saber-Bot by notem.

the class ManageCommand 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 logging = Main.getScheduleManager().getRSVPLogging(se.getChannelId());
    String content = "", group, user;
    List<String> members;
    switch(args[index++].toLowerCase()) {
        case "a":
        case "add":
            group = args[index++];
            user = args[index].matches("<@!?\\d+>") ? args[index].replaceAll("[^\\d]", "") : args[index];
            members = se.getRsvpMembersOfType(group);
            members.add(user);
            se.setRsvpMembers(group, members);
            content = "I have added *" + args[index] + "* to *" + group + "* on event :id:" + ParsingUtilities.intToEncodedID(se.getId());
            // log the rsvp action
            if (!logging.isEmpty()) {
                String msg = "";
                if (user.matches("[\\d]+"))
                    msg += "<@" + user + ">";
                else
                    msg += user;
                msg += " has been added to the RSVP group *" + group + "* for **" + se.getTitle() + "** - :id: **" + ParsingUtilities.intToEncodedID(se.getId()) + "**";
                MessageUtilities.sendMsg(msg, event.getJDA().getTextChannelById(logging), null);
            }
            break;
        case "k":
        case "kick":
            group = args[index++];
            user = args[index].matches("<@!?\\d+>") ? args[index].replaceAll("[^\\d]", "") : args[index];
            members = se.getRsvpMembersOfType(group);
            members.remove(user);
            se.setRsvpMembers(group, members);
            content = "I have removed *" + args[index] + "* from *" + group + "* on event :id:" + ParsingUtilities.intToEncodedID(se.getId());
            // log the rsvp action
            if (!logging.isEmpty()) {
                String msg = "";
                if (user.matches("[\\d]+"))
                    msg += "<@" + user + ">";
                else
                    msg += user;
                msg += " has been kicked from the RSVP group *" + group + "* for **" + se.getTitle() + "** - :id: **" + ParsingUtilities.intToEncodedID(se.getId()) + "**";
                MessageUtilities.sendMsg(msg, event.getJDA().getTextChannelById(logging), null);
            }
            break;
    }
    Main.getEntryManager().updateEntry(se, false);
    MessageUtilities.sendMsg(content, event.getTextChannel(), null);
}
Also used : ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry)

Example 19 with ScheduleEntry

use of ws.nmathe.saber.core.schedule.ScheduleEntry in project Saber-Bot by notem.

the class SkipCommand method verify.

@Override
public String verify(String prefix, String[] args, MessageReceivedEvent event) {
    String head = prefix + this.name();
    if (args.length != 1) {
        return "Incorrect amount of arguments!" + "\nUse ``" + head + " <id>``";
    }
    ScheduleEntry entry;
    if (VerifyUtilities.verifyEntryID(args[0])) {
        Integer entryId = ParsingUtilities.encodeIDToInt(args[0]);
        entry = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());
        if (entry == null) {
            return "The requested entry does not exist!";
        }
    } else {
        return "Argument *" + args[0] + "* is not a valid entry ID!";
    }
    return "";
}
Also used : ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry)

Example 20 with ScheduleEntry

use of ws.nmathe.saber.core.schedule.ScheduleEntry in project Saber-Bot by notem.

the class ParsingUtilities method parseMessageFormat.

/**
 * @param format the base string to parse into a message
 * @param entry the entry associated with the message
 * @return a new message which has entry specific information inserted into the format string
 */
public static String parseMessageFormat(String format, ScheduleEntry entry, boolean displayComments) {
    // determine time formatter from schedule settings
    String clock = Main.getScheduleManager().getClockFormat(entry.getChannelId());
    DateTimeFormatter timeFormatter;
    if (clock.equalsIgnoreCase("12"))
        timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
    else
        timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
    // advanced parsing
    /*
         * parses the format string using regex grouping
         * allows for an 'if element exists, print string + element + string' type of insertion
         */
    Matcher matcher = Pattern.compile("%\\{(.*?)}").matcher(format);
    while (matcher.find()) {
        String group = matcher.group();
        String trimmed = group.substring(2, group.length() - 1);
        StringBuilder sub = new StringBuilder();
        if (!trimmed.isEmpty()) {
            Matcher matcher2 = Pattern.compile("\\[.*?]").matcher(trimmed);
            if (// advanced comment
            trimmed.matches("(\\[.*?])?c\\d+(\\[.*?])?") && displayComments) {
                int i = Integer.parseInt(trimmed.replaceAll("(\\[.*?])?c|\\[.*?]", ""));
                if (entry.getComments().size() >= i && i > 0) {
                    sub.append(messageFormatHelper(entry.getComments().get(i - 1), matcher2));
                }
            } else if (// advanced start
            trimmed.matches("(\\[.*?])?s(\\[.*?])?")) {
                if (!entry.hasStarted()) {
                    while (matcher2.find()) {
                        sub.append(matcher2.group().replaceAll("[\\[\\]]", ""));
                    }
                }
            } else if (// advanced end
            trimmed.matches("(\\[.*?])?e(\\[.*?])?")) {
                if (entry.hasStarted()) {
                    while (matcher2.find()) {
                        sub.append(matcher2.group().replaceAll("[\\[\\]]", ""));
                    }
                }
            } else if (// advanced end
            trimmed.matches("(\\[.*?])?start .+(\\[.*?])?")) {
                String formatter = trimmed.replaceAll("start ", "").replaceAll("^[GuyDMLdQqYwWEeCFahkKHmsSAnNVzOXxZp'\\[\\]#{}.,\\- ]", " ").replaceAll("\\[.*?]", "");
                String startString = "";
                try {
                    startString = entry.getStart().format(DateTimeFormatter.ofPattern(formatter));
                } catch (Exception ignored) {
                }
                sub.append(startString);
            } else if (// advanced end
            trimmed.matches("(\\[.*?])?end .+(\\[.*?])?")) {
                String formatter = trimmed.replaceAll("end ", "").replaceAll("^[GuyDMLdQqYwWEeCFahkKHmsSAnNVzOXxZp'\\[\\]#{}.,\\- ]", " ").replaceAll("\\[.*?]", "");
                String endString = "";
                try {
                    endString = entry.getEnd().format(DateTimeFormatter.ofPattern(formatter));
                } catch (Exception ignored) {
                }
                sub.append(endString);
            } else if (// advanced remind in minutes
            trimmed.matches("(\\[.*?])?m(\\[.*?])?")) {
                if (!entry.hasStarted()) {
                    long minutes = ZonedDateTime.now().until(entry.getStart(), ChronoUnit.MINUTES);
                    if (minutes > 0) {
                        sub.append(messageFormatHelper("" + (minutes + 1), matcher2));
                    }
                } else {
                    long minutes = ZonedDateTime.now().until(entry.getEnd(), ChronoUnit.MINUTES);
                    if (minutes > 0) {
                        sub.append(messageFormatHelper("" + (minutes + 1), matcher2));
                    }
                }
            } else if (// advanced remind in hours
            trimmed.matches("(\\[.*?])?h(\\[.*?])?")) {
                if (!entry.hasStarted()) {
                    long minutes = ZonedDateTime.now().until(entry.getStart(), ChronoUnit.MINUTES);
                    if (minutes > 0) {
                        sub.append(messageFormatHelper("" + (minutes + 1) / 60, matcher2));
                    }
                } else {
                    long minutes = ZonedDateTime.now().until(entry.getEnd(), ChronoUnit.MINUTES);
                    if (minutes > 0) {
                        sub.append(messageFormatHelper("" + (minutes + 1) / 60, matcher2));
                    }
                }
            } else if (// rsvp count
            trimmed.matches("(\\[.*?])?rsvp .+(\\[.*?])?")) {
                String name = trimmed.replaceAll("rsvp ", "").replaceAll("\\[.*?]", "");
                List<String> members = entry.getRsvpMembers().get(name);
                if (members != null) {
                    sub.append(messageFormatHelper("" + members.size(), matcher2));
                }
            } else if (// rsvp mentions
            trimmed.matches("(\\[.*?])?mention .+(\\[.*?])?")) {
                String name = trimmed.replaceAll("mention ", "").replaceAll("\\[.*?]", "");
                List<String> users = compileUserList(entry, name);
                if (// a valid mention option was used
                users != null) {
                    StringBuilder userMentions = new StringBuilder();
                    for (int i = 0; i < users.size(); i++) {
                        if (users.get(i).matches("\\d+"))
                            userMentions.append("<@").append(users.get(i)).append(">");
                        if (i + 1 < users.size())
                            userMentions.append(", ");
                    }
                    sub.append(messageFormatHelper(userMentions.toString(), matcher2));
                }
            } else if (trimmed.matches("(\\[.*?])?mentionm .+(\\[.*?])?") || // rsvp mentions
            trimmed.matches("(\\[.*?])?list .+(\\[.*?])?")) {
                String name = trimmed.replace("mentionm ", "").replace("list", "").replaceAll("\\[.*?]", "");
                List<String> users = compileUserList(entry, name);
                if (users != null) {
                    StringBuilder userMentions = new StringBuilder();
                    for (int i = 0; i < users.size(); i++) {
                        if (users.get(i).matches("\\d+")) {
                            Member member = Main.getShardManager().getJDA(entry.getGuildId()).getGuildById(entry.getGuildId()).getMemberById(users.get(i));
                            userMentions.append(member.getEffectiveName());
                        }
                        if (i + 1 < users.size())
                            userMentions.append(", ");
                    }
                    sub.append(messageFormatHelper(userMentions.toString(), matcher2));
                }
            } else if (// advanced title url
            trimmed.matches("(\\[.*?])?u(\\[.*?])?")) {
                if (entry.getTitleUrl() != null) {
                    sub.append(messageFormatHelper(entry.getTitleUrl(), matcher2));
                }
            } else if (// advanced image url
            trimmed.matches("(\\[.*?])?v(\\[.*?])?")) {
                if (entry.getImageUrl() != null) {
                    sub.append(messageFormatHelper(entry.getImageUrl(), matcher2));
                }
            } else if (// advanced thumbnail url
            trimmed.matches("(\\[.*?])?w(\\[.*?])?")) {
                if (entry.getThumbnailUrl() != null) {
                    sub.append(messageFormatHelper(entry.getThumbnailUrl(), matcher2));
                }
            }
        }
        format = format.replace(group, sub.toString());
    }
    // legacy parsing
    /*
         * parses the format string character by character looking for % characters
         * a token is one % character followed by a key character
         */
    StringBuilder announceMsg = new StringBuilder();
    for (int i = 0; i < format.length(); i++) {
        char ch = format.charAt(i);
        if (ch == '%' && i + 1 < format.length()) {
            i++;
            ch = format.charAt(i);
            switch(ch) {
                case 'c':
                    if (i + 1 < format.length() && displayComments) {
                        ch = format.charAt(i + 1);
                        if (Character.isDigit(ch)) {
                            i++;
                            int x = Integer.parseInt("" + ch);
                            if (entry.getComments().size() >= x && x != 0) {
                                String parsedComment = ParsingUtilities.parseMessageFormat(entry.getComments().get(x - 1), entry, false);
                                announceMsg.append(parsedComment);
                            }
                        }
                    }
                    break;
                case 'f':
                    if (displayComments) {
                        // if this call of the parser is nested, don't insert comments
                        announceMsg.append(String.join("\n", entry.getComments().stream().map(comment -> ParsingUtilities.parseMessageFormat(comment, entry, false)).collect(Collectors.toList())));
                    }
                    break;
                case 'a':
                    if (!entry.hasStarted()) {
                        announceMsg.append("begins");
                        long minutes = ZonedDateTime.now().until(entry.getStart(), ChronoUnit.MINUTES);
                        if (minutes > 0) {
                            if (minutes > 120)
                                announceMsg.append(" in ").append((minutes + 1) / 60).append(" hours");
                            else
                                announceMsg.append(" in ").append(minutes + 1).append(" minutes");
                        }
                    } else {
                        announceMsg.append("ends");
                        long minutes = ZonedDateTime.now().until(entry.getEnd(), ChronoUnit.MINUTES);
                        if (minutes > 0) {
                            if (minutes > 120)
                                announceMsg.append(" in ").append((minutes + 1) / 60).append(" hours");
                            else
                                announceMsg.append(" in ").append(minutes + 1).append(" minutes");
                        }
                    }
                    break;
                case 'b':
                    if (!entry.hasStarted())
                        announceMsg.append("begins");
                    else
                        announceMsg.append("ends");
                    break;
                case 'x':
                    if (!entry.hasStarted()) {
                        long minutes = ZonedDateTime.now().until(entry.getStart(), ChronoUnit.MINUTES);
                        if (minutes > 0) {
                            if (minutes > 120)
                                announceMsg.append(" in ").append((minutes + 1) / 60).append(" hours");
                            else
                                announceMsg.append(" in ").append(minutes + 1).append(" minutes");
                        }
                    } else {
                        long minutes = ZonedDateTime.now().until(entry.getEnd(), ChronoUnit.MINUTES);
                        if (minutes > 0) {
                            if (minutes > 120)
                                announceMsg.append(" in ").append((minutes + 1) / 60).append(" hours");
                            else
                                announceMsg.append(" in ").append(minutes + 1).append(" minutes");
                        }
                    }
                    break;
                case 's':
                    announceMsg.append(entry.getStart().format(timeFormatter));
                    break;
                case 'e':
                    announceMsg.append(entry.getEnd().format(timeFormatter));
                    break;
                case 't':
                    announceMsg.append(entry.getTitle());
                    break;
                case 'd':
                    announceMsg.append(String.format("%02d", entry.getStart().getDayOfMonth()));
                    break;
                case 'D':
                    announceMsg.append(StringUtils.capitalize(entry.getStart().getDayOfWeek().toString()));
                    break;
                case 'm':
                    announceMsg.append(String.format("%02d", entry.getStart().getMonthValue()));
                    break;
                case 'M':
                    announceMsg.append(StringUtils.capitalize(entry.getStart().getMonth().toString()));
                    break;
                case 'y':
                    announceMsg.append(entry.getStart().getYear());
                    break;
                case 'i':
                    announceMsg.append(ParsingUtilities.intToEncodedID(entry.getId()));
                    break;
                case '%':
                    announceMsg.append('%');
                    break;
                case 'u':
                    announceMsg.append(entry.getTitleUrl() == null ? "" : entry.getTitleUrl());
                    break;
                case 'v':
                    announceMsg.append(entry.getImageUrl() == null ? "" : entry.getImageUrl());
                    break;
                case 'w':
                    announceMsg.append(entry.getThumbnailUrl() == null ? "" : entry.getThumbnailUrl());
                    break;
                case 'n':
                    announceMsg.append("\n");
                    break;
                case 'h':
                    announceMsg.append(String.format("%02d", entry.getStart().getHour()));
                    break;
                case 'k':
                    announceMsg.append(String.format("%02d", entry.getStart().getMinute()));
                    break;
                case 'l':
                    announceMsg.append(entry.getLocation());
                    break;
            }
        } else {
            announceMsg.append(ch);
        }
    }
    return announceMsg.toString();
}
Also used : java.util(java.util) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) ZonedDateTime(java.time.ZonedDateTime) StringUtils(org.apache.commons.lang3.StringUtils) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Collectors(java.util.stream.Collectors) ByteBuffer(java.nio.ByteBuffer) ZoneId(java.time.ZoneId) ChronoUnit(java.time.temporal.ChronoUnit) Matcher(java.util.regex.Matcher) Permission(net.dv8tion.jda.core.Permission) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) LocalTime(java.time.LocalTime) JDA(net.dv8tion.jda.core.JDA) Main(ws.nmathe.saber.Main) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) DateTimeFormatter(java.time.format.DateTimeFormatter)

Aggregations

ScheduleEntry (ws.nmathe.saber.core.schedule.ScheduleEntry)21 JDA (net.dv8tion.jda.core.JDA)6 Main (ws.nmathe.saber.Main)6 ZonedDateTime (java.time.ZonedDateTime)5 java.util (java.util)5 Message (net.dv8tion.jda.core.entities.Message)5 ZoneId (java.time.ZoneId)4 Matcher (java.util.regex.Matcher)4 Pattern (java.util.regex.Pattern)4 Permission (net.dv8tion.jda.core.Permission)4 net.dv8tion.jda.core.entities (net.dv8tion.jda.core.entities)4 StringUtils (org.apache.commons.lang3.StringUtils)4 DateTimeFormatter (java.time.format.DateTimeFormatter)3 ChronoUnit (java.time.temporal.ChronoUnit)3 Consumer (java.util.function.Consumer)3 Collectors (java.util.stream.Collectors)3 MessageReceivedEvent (net.dv8tion.jda.core.events.message.MessageReceivedEvent)3 Document (org.bson.Document)3 MessageUtilities (ws.nmathe.saber.utils.MessageUtilities)3 ParsingUtilities (ws.nmathe.saber.utils.ParsingUtilities)3