Search in sources :

Example 11 with JDA

use of net.dv8tion.jda.core.JDA in project FredBoat by Frederikam.

the class EvalCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    final long started = System.currentTimeMillis();
    String source = context.rawArgs;
    if (context.hasArguments() && (context.args[0].equals("-k") || context.args[0].equals("kill"))) {
        if (this.lastTask != null) {
            if (this.lastTask.isDone() || this.lastTask.isCancelled()) {
                context.reply("Task isn't running.");
            } else {
                this.lastTask.cancel(true);
                context.reply("Task killed.");
            }
        } else {
            context.reply("No task found to kill.");
        }
        return;
    }
    context.sendTyping();
    final int timeOut;
    if (context.args.length > 1 && (context.args[0].equals("-t") || context.args[0].equals("timeout"))) {
        timeOut = Integer.parseInt(context.args[1]);
        source = source.replaceFirst(context.args[0], "");
        source = source.replaceFirst(context.args[1], "");
    } else
        timeOut = -1;
    final String finalSource = source.trim();
    Guild guild = context.guild;
    JDA jda = guild.getJDA();
    engine.put("jda", jda);
    engine.put("api", jda);
    engine.put("channel", context.channel);
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(guild);
    engine.put("vc", player != null ? player.getCurrentVoiceChannel() : null);
    engine.put("author", context.msg.getAuthor());
    engine.put("invoker", context.invoker);
    engine.put("bot", jda.getSelfUser());
    engine.put("member", guild.getSelfMember());
    engine.put("message", context.msg);
    engine.put("guild", guild);
    engine.put("player", player);
    engine.put("pm", Launcher.getBotController().getAudioPlayerManager());
    engine.put("context", context);
    ScheduledExecutorService service = Executors.newScheduledThreadPool(1, r -> new Thread(r, "Eval comm execution"));
    Future<?> future = service.submit(() -> {
        Object out;
        try {
            out = engine.eval("(function() {" + "with (imports) {\n" + finalSource + "\n}" + "})();");
        } catch (Exception ex) {
            context.reply(String.format("`%s`\n\n`%sms`", ex.getMessage(), System.currentTimeMillis() - started));
            log.info("Error occurred in eval", ex);
            return;
        }
        String outputS;
        if (out == null) {
            outputS = ":ok_hand::skin-tone-3:";
        } else if (out.toString().contains("\n")) {
            outputS = "\nEval: " + TextUtils.asCodeBlock(out.toString());
        } else {
            outputS = "\nEval: `" + out.toString() + "`";
        }
        context.reply(String.format("```java\n%s```\n%s\n`%sms`", finalSource, outputS, System.currentTimeMillis() - started));
    });
    this.lastTask = future;
    Thread script = new Thread("Eval comm waiter") {

        @Override
        public void run() {
            try {
                if (timeOut > -1) {
                    future.get(timeOut, TimeUnit.SECONDS);
                }
            } catch (final TimeoutException ex) {
                future.cancel(true);
                context.reply("Task exceeded time limit of " + timeOut + " seconds.");
            } catch (final Exception ex) {
                context.reply(String.format("`%s`\n\n`%sms`", ex.getMessage(), System.currentTimeMillis() - started));
            }
        }
    };
    script.start();
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) JDA(net.dv8tion.jda.core.JDA) Guild(net.dv8tion.jda.core.entities.Guild) ScriptException(javax.script.ScriptException)

Example 12 with JDA

use of net.dv8tion.jda.core.JDA in project FredBoat by Frederikam.

the class EventLogger method sendGuildStats.

private void sendGuildStats() {
    if (guildStatsWebhook == null) {
        return;
    }
    EmbedBuilder eb = CentralMessaging.getColoredEmbedBuilder().setTimestamp(OffsetDateTime.now()).setTitle("Joins and Leaves since the last update").addField("Guilds joined", Integer.toString(guildsJoinedEvents.getAndSet(0)), true).addField("Guilds left", Integer.toString(guildsLeftEvents.getAndSet(0)), true);
    Optional<JDA> shards = shardProvider.streamShards().findAny();
    if (shards.isPresent()) {
        JDA anyShard = shards.get();
        User self = anyShard.getSelfUser();
        eb.setFooter(self.getName(), self.getEffectiveAvatarUrl());
    }
    toBeSentGuildStats.add(CentralMessaging.from(eb.build()));
    drainMessageQueue(toBeSentGuildStats, guildStatsWebhook);
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) User(net.dv8tion.jda.core.entities.User) JDA(net.dv8tion.jda.core.JDA)

Example 13 with JDA

use of net.dv8tion.jda.core.JDA in project pokeraidbot by magnusmickelsson.

the class AdminCommands method execute.

@Override
protected void execute(CommandEvent event) {
    final User user = event.getAuthor();
    if (user == null || user.getId() == null || (!user.getId().equals(BotServerMain.BOT_CREATOR_USERID))) {
        event.replyInDM("This command is reserved only for bot creator. Hands off! ;p Your user ID was: " + String.valueOf(user.getId()));
        return;
    } else {
        final String eventArgs = event.getArgs();
        if (eventArgs.startsWith("userconfig")) {
            String userId = eventArgs.replaceAll("userconfig\\s{1,3}", "");
            final UserConfig userConfig = userConfigRepository.findOne(userId);
            if (userConfig == null) {
                event.replyInDM("No user with ID " + userId);
                return;
            } else {
                userConfigRepository.delete(userConfig);
                event.replyInDM("Removed user configuration for user with ID " + userId);
                return;
            }
        } else if (eventArgs.startsWith("permissions")) {
            final JDA bot = botService.getBot();
            final List<Guild> guilds = bot.getGuilds();
            StringBuilder sb = new StringBuilder();
            sb.append("**Permissions for bot across servers:**\n\n");
            for (Guild guild : guilds) {
                final Member member = guild.getMember(bot.getSelfUser());
                if (member == null) {
                    event.replyInDM("Could not get bot as servermember!");
                    return;
                }
                sb.append("*").append(guild.getName()).append("*\n");
                for (Permission p : member.getPermissions()) {
                    sb.append(p.getName()).append("(Guild: ").append(p.isGuild()).append(" Channel: ").append(p.isChannel()).append(")\n");
                }
                sb.append("\n\n");
            }
            event.replyInDM(sb.toString());
            return;
        } else if (eventArgs.startsWith("clear tracking")) {
            trackingCommandListener.clearCache();
            event.replyInDM("Cleared tracking cache.");
            return;
        } else if (eventArgs.startsWith("announce")) {
            final JDA bot = botService.getBot();
            final List<Guild> guilds = bot.getGuilds();
            StringBuilder sb = new StringBuilder();
            for (Guild guild : guilds) {
                try {
                    guild.getDefaultChannel().sendMessage(eventArgs.replaceAll("announce\\s{1,3}", "")).queue();
                    sb.append("Sent message for guild ").append(guild.getName()).append("\n");
                } catch (Throwable t) {
                    sb.append("Failed to send message for guild ").append(guild.getName()).append(": ").append(t.getMessage()).append("\n");
                }
            }
            event.replyInDM(sb.toString());
            return;
        } else if (eventArgs.startsWith("ismember")) {
            String userIdAndGuildName = eventArgs.replaceAll("ismember\\s{1,3}", "");
            String[] args = userIdAndGuildName.split(" ");
            if (args.length < 2) {
                event.reply("Bad syntax, should be something like: !raid admin ismember {userid} {guildname}");
                return;
            } else {
                final JDA bot = botService.getBot();
                Guild guild = null;
                final List<Guild> guilds = bot.getGuilds();
                String guildName = StringUtils.join(ArrayUtils.remove(args, 0), " ");
                for (Guild guildToCheck : guilds) {
                    if (guildToCheck.getName().equalsIgnoreCase(guildName)) {
                        guild = guildToCheck;
                    }
                }
                if (guild != null) {
                    final Member memberById = guild.getMemberById(args[0]);
                    if (memberById != null) {
                        event.reply("User is a member of server " + guild.getName());
                    } else {
                        event.reply("User is not a member of server " + guild.getName());
                    }
                } else {
                    event.reply("There was no server the user is a member of.");
                }
                return;
            }
        } else if (eventArgs.startsWith("member")) {
            String userIdAndGuildName = eventArgs.replaceAll("member\\s{1,3}", "");
            String[] args = userIdAndGuildName.split(" ");
            if (args.length < 1 || args.length > 2) {
                event.reply("Bad syntax, should be something like: !raid admin member {userid}");
                return;
            } else {
                StringBuilder sb = new StringBuilder();
                final JDA bot = botService.getBot();
                final List<Guild> guilds = bot.getGuilds();
                sb.append("User with ID ").append(args[0]).append(" is a member of the following servers:\n\n");
                if (guilds.size() == 0) {
                    sb.append("-");
                }
                for (Guild guild : guilds) {
                    final Member memberById = guild.getMemberById(args[0]);
                    if (memberById != null) {
                        sb.append(guild.getName()).append(" (Username ").append(memberById.getUser().getName()).append(")\n");
                    }
                }
                event.reply(sb.toString());
                return;
            }
        } else if (eventArgs.startsWith("guilds")) {
            final JDA bot = botService.getBot();
            final List<Guild> guilds = bot.getGuilds();
            StringBuilder sb = new StringBuilder();
            for (Guild guildToCheck : guilds) {
                sb.append(guildToCheck.getName().toLowerCase()).append("\n");
            }
            event.reply(sb.toString());
            return;
        } else if (eventArgs.startsWith("test")) {
            final Config configForServer = serverConfigRepository.getConfigForServer(event.getGuild().getName().toLowerCase());
            String[] args = eventArgs.replaceAll("test\\s{1,3}", "").trim().split(" ");
            String pokemon = args[0];
            LocalDateTime startsAt = LocalDateTime.of(LocalDate.now(), Utils.parseTime(user, args[1], localeService));
            String gymName = StringUtils.join(ArrayUtils.removeElements(args, 0, 1), " ").trim();
            final String region = configForServer.getRegion();
            Raid raid = new Raid(pokemonRepository.search(pokemon, user), startsAt.plusMinutes(Utils.RAID_DURATION_IN_MINUTES), gymRepository.search(user, gymName, region), localeService, region);
            final Raid createdRaid = raidRepository.newRaid(botService.getBot().getSelfUser(), raid, event.getGuild(), configForServer, event.getMessage().getRawContent());
            event.reply("Bot created your test raid: " + createdRaid);
            return;
        } else if (eventArgs.startsWith("tier5")) {
            String[] bosses = eventArgs.replaceAll("tier5\\s{1,3}", "").trim().split(";");
            if (bosses == null || bosses.length < 1) {
                event.reply("Bad syntax, should be: !raid admin tier5 Boss1;Boss2;Boss3");
                return;
            } else {
                final CopyOnWriteArrayList<String> currentTier5Bosses = new CopyOnWriteArrayList<>();
                currentTier5Bosses.addAll(Arrays.asList(bosses));
                BotService.currentTier5Bosses = currentTier5Bosses;
                event.reply("Set current tier5 boss list: " + StringUtils.join(bosses, ", "));
                return;
            }
        }
    }
    event.reply("No such command. Existing ones are:\n- userconfig {userid}\n- permissions\n" + "- clear tracking\n- announce {message}\n- ismember {userid} {guild name}\n- guilds\n" + " - member {userid}\n - test {pokemon} {start time} {gym}\n- tier5 {list of bosses ;-separated}");
}
Also used : LocalDateTime(java.time.LocalDateTime) User(net.dv8tion.jda.core.entities.User) JDA(net.dv8tion.jda.core.JDA) UserConfig(pokeraidbot.infrastructure.jpa.config.UserConfig) Config(pokeraidbot.infrastructure.jpa.config.Config) UserConfig(pokeraidbot.infrastructure.jpa.config.UserConfig) Guild(net.dv8tion.jda.core.entities.Guild) Raid(pokeraidbot.domain.raid.Raid) Permission(net.dv8tion.jda.core.Permission) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Member(net.dv8tion.jda.core.entities.Member) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 14 with JDA

use of net.dv8tion.jda.core.JDA in project Saber-Bot by notem.

the class CalendarConverter method importCalendar.

/**
 * Purges a schedule from entries and adds events (after conversion)
 * from the next 7 day span of a Google Calendar
 * @param address (String) valid address of calendar
 * @param channel (MessageChannel) channel to sync with
 * @param service connected calendar service with user credentials
 */
public void importCalendar(String address, TextChannel channel, Calendar service) {
    // sanity checks
    if (channel == null || address == null)
        return;
    if (!Main.getScheduleManager().isASchedule(channel.getId()))
        return;
    // query the google calendar address for the list of events
    Events events;
    try {
        ZonedDateTime min = ZonedDateTime.now();
        ZonedDateTime max = min.plusDays(Main.getScheduleManager().getSyncLength(channel.getId()));
        events = service.events().list(address).setTimeMin(new DateTime(min.format(EventRecurrence.RFC3339_FORMATTER))).setTimeMax(new DateTime(max.format(EventRecurrence.RFC3339_FORMATTER))).setOrderBy("startTime").setSingleEvents(true).setMaxResults(Main.getBotSettingsManager().getMaxEntries()).execute();
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
        return;
    }
    try // convert the list of Google Events into discord event entries
    {
        // send 'is typing' while the sync is in progress
        channel.sendTyping().queue();
        /* lock the schedule for syncing; schedule is unlocked in finally block */
        Main.getScheduleManager().lock(channel.getId());
        // change the zone to match the calendar
        // only if the zone has not been manually set for that schedule
        ZoneId zone = ZoneId.of(events.getTimeZone());
        Boolean syncZone = Main.getDBDriver().getScheduleCollection().find(eq("_id", channel.getId())).first().getBoolean("timezone_sync", false);
        if (syncZone) {
            Main.getScheduleManager().setTimeZone(channel.getId(), zone);
        }
        // a set of all unique (not child of a recurring event) events
        HashSet<String> uniqueEvents = new HashSet<>();
        // process events
        for (Event event : events.getItems()) {
            // continue to send 'is typing'
            channel.sendTyping().queue();
            // if the unique google event ID does not appear in the already processed events
            // convert the event and add it to the schedule
            String recurrenceId = event.getRecurringEventId();
            String googleId = recurrenceId == null ? event.getId() : recurrenceId;
            if (!uniqueEvents.contains(googleId)) {
                // declare and initialize event parameters
                ZonedDateTime start, end;
                String title;
                ArrayList<String> comments = new ArrayList<>();
                int repeat = 0;
                ZonedDateTime expire = null;
                String imageUrl = null;
                String thumbnailUrl = null;
                ZonedDateTime rsvpDeadline = null;
                String titleUrl = null;
                Map<String, Integer> rsvpLimits = new HashMap<>();
                if (event.getStart().getDateTime() == null) {
                    /* parse start and end dates for all day events */
                    start = ZonedDateTime.of(LocalDate.parse(event.getStart().getDate().toStringRfc3339()), LocalTime.MIN, zone);
                    end = ZonedDateTime.of(LocalDate.parse(event.getEnd().getDate().toStringRfc3339()), LocalTime.MIN, zone);
                } else {
                    /* parse start and end times for normal events */
                    start = ZonedDateTime.parse(event.getStart().getDateTime().toStringRfc3339(), EventRecurrence.RFC3339_FORMATTER).withZoneSameInstant(zone);
                    end = ZonedDateTime.parse(event.getEnd().getDateTime().toStringRfc3339(), EventRecurrence.RFC3339_FORMATTER).withZoneSameInstant(zone);
                }
                // get event title
                if (event.getSummary() == null)
                    title = "(No title)";
                else
                    title = event.getSummary();
                // process event description into event comments or other settings
                if (event.getDescription() != null) {
                    // process the description line by line
                    String description = HTMLStripper.cleanDescription(event.getDescription().replace("\n", "<br>"));
                    for (String comment : description.split("\n")) {
                        comment = comment.trim();
                        String lowerCase = comment.toLowerCase();
                        // image
                        if (lowerCase.startsWith("image:")) {
                            // split to limit:
                            String[] tmp = comment.split(":", 2);
                            if (tmp.length > 1) {
                                imageUrl = tmp[1].trim().replaceAll(" ", "");
                                if (!VerifyUtilities.verifyUrl(imageUrl))
                                    imageUrl = null;
                            }
                        } else // thumbnail
                        if (lowerCase.startsWith("thumbnail:")) {
                            String[] tmp = comment.split(":", 2);
                            if (tmp.length > 1) {
                                thumbnailUrl = tmp[1].trim().trim().replaceAll(" ", "");
                                if (!VerifyUtilities.verifyUrl(thumbnailUrl))
                                    thumbnailUrl = null;
                            }
                        } else // limit
                        if (lowerCase.startsWith("limit:")) {
                            // split to limit:
                            String[] tmp = comment.split(":", 2);
                            if (tmp.length > 1) {
                                // split into white space separated segments
                                String[] str = tmp[1].trim().split("[^\\S\n\r]+");
                                if (str.length >= 2) {
                                    // rebuild the rsvp group name
                                    StringBuilder name = new StringBuilder();
                                    for (int i = 0; i < str.length - 1; i++) {
                                        name.append(str[i]);
                                        if (i != str.length - 2)
                                            name.append(" ");
                                    }
                                    // parse the limit
                                    Integer limit = -1;
                                    if (VerifyUtilities.verifyInteger(str[str.length - 1]))
                                        limit = Integer.parseInt(str[str.length - 1]);
                                    rsvpLimits.put(name.toString(), limit);
                                }
                            }
                        } else // title url
                        if (lowerCase.startsWith("url:")) {
                            String[] tmp = comment.split(":", 2);
                            if (tmp.length > 1 && VerifyUtilities.verifyUrl(tmp[1].trim().replaceAll(" ", "")))
                                titleUrl = tmp[1].trim().replaceAll(" ", "");
                        } else // deadline
                        if (lowerCase.startsWith("deadline:")) {
                            String tmp = lowerCase.replace("deadline:", "").trim().replaceAll(" ", "");
                            if (VerifyUtilities.verifyDate(tmp))
                                rsvpDeadline = ParsingUtilities.parseDate(tmp, zone);
                        } else // plaintext comment
                        if (!comment.trim().isEmpty()) {
                            comments.add(comment);
                        }
                    }
                }
                // get the event recurrence information
                List<String> recurrence = event.getRecurrence();
                if (recurrenceId != null)
                    recurrence = service.events().get(address, recurrenceId).execute().getRecurrence();
                // parse the event recurrence information
                if (recurrence != null) {
                    // determine the start date
                    ZonedDateTime dtStart = // if orig is null, use start
                    event.getOriginalStartTime() == null ? // if orig is null, use start
                    start : (event.getOriginalStartTime().getDateTime() == null ? start : ZonedDateTime.parse(event.getOriginalStartTime().getDateTime().toStringRfc3339(), EventRecurrence.RFC3339_FORMATTER).withZoneSameInstant(zone));
                    EventRecurrence eventRecurrence = new EventRecurrence(recurrence, dtStart);
                    expire = eventRecurrence.getExpire();
                    repeat = eventRecurrence.getRepeat();
                }
                // if the google event already exists as a saber event on the schedule, update it
                // otherwise add as a new saber event
                Document doc = Main.getDBDriver().getEventCollection().find(and(eq("channelId", channel.getId()), eq("googleId", googleId))).first();
                // should the event be flagged as already started?
                boolean hasStarted = start.isBefore(ZonedDateTime.now());
                if (doc != null && (new ScheduleEntry(doc)).getMessageObject() != null) {
                    /* update an existing event */
                    ScheduleEntry se = (new ScheduleEntry(doc)).setTitle(title).setStart(start).setEnd(end).setRepeat(repeat).setGoogleId(googleId).setExpire(expire).setStarted(hasStarted).setComments(comments).setLocation(event.getLocation());
                    // set special attributes if not null
                    if (titleUrl != null)
                        se.setTitleUrl(titleUrl);
                    if (imageUrl != null)
                        se.setImageUrl(imageUrl);
                    if (thumbnailUrl != null)
                        se.setThumbnailUrl(thumbnailUrl);
                    if (rsvpDeadline != null)
                        se.setRsvpDeadline(rsvpDeadline);
                    if (rsvpLimits.keySet().size() > 0)
                        se.setRsvpLimits(rsvpLimits);
                    // update event reminders using schedule default settings
                    se.reloadReminders(Main.getScheduleManager().getReminders(se.getChannelId())).reloadEndReminders(Main.getScheduleManager().getEndReminders(se.getChannelId())).regenerateAnnouncementOverrides();
                    Main.getEntryManager().updateEntry(se, false);
                } else {
                    /* create a new event */
                    ScheduleEntry se = (new ScheduleEntry(channel, title, start, end)).setTitleUrl(titleUrl != null ? titleUrl : event.getHtmlLink()).setRepeat(repeat).setGoogleId(googleId).setExpire(expire).setStarted(hasStarted).setComments(comments).setLocation(event.getLocation());
                    // set special attributes if not null
                    if (imageUrl != null)
                        se.setImageUrl(imageUrl);
                    if (thumbnailUrl != null)
                        se.setThumbnailUrl(thumbnailUrl);
                    if (rsvpDeadline != null)
                        se.setRsvpDeadline(rsvpDeadline);
                    if (rsvpLimits.keySet().size() > 0)
                        se.setRsvpLimits(rsvpLimits);
                    Main.getEntryManager().newEntry(se, false);
                }
                // add to google ID to unique event mapping
                uniqueEvents.add(recurrenceId == null ? event.getId() : recurrenceId);
            }
        }
        // purge channel of all entries on schedule that aren't in uniqueEvents
        Bson query = and(eq("channelId", channel.getId()), nin("googleId", uniqueEvents));
        Main.getDBDriver().getEventCollection().find(query).forEach((Consumer<? super Document>) document -> {
            ScheduleEntry entry = Main.getEntryManager().getEntry((Integer) document.get("_id"));
            Message msg = entry.getMessageObject();
            if (msg == null)
                return;
            Main.getEntryManager().removeEntry((Integer) document.get("_id"));
            MessageUtilities.deleteMsg(msg, null);
        });
        // set channel topic
        JDA jda = Main.getShardManager().getJDA(channel.getGuild().getId());
        String calLink = "https://calendar.google.com/calendar/embed?src=" + address;
        boolean hasPerms = channel.getGuild().getMember(jda.getSelfUser()).hasPermission(channel, Permission.MANAGE_CHANNEL);
        if (hasPerms)
            channel.getManagerUpdatable().getTopicField().setValue(calLink).update().queue();
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    } finally {
        // syncing done, unlock the channel
        Main.getScheduleManager().unlock(channel.getId());
    }
    // auto-sort
    EntryManager.autoSort(true, channel.getId());
}
Also used : Document(org.bson.Document) java.util(java.util) TextChannel(net.dv8tion.jda.core.entities.TextChannel) EventRecurrence(ws.nmathe.saber.core.schedule.EventRecurrence) Message(net.dv8tion.jda.core.entities.Message) Bson(org.bson.conversions.Bson) Filters(com.mongodb.client.model.Filters) DateTime(com.google.api.client.util.DateTime) java.time(java.time) Matcher(java.util.regex.Matcher) Permission(net.dv8tion.jda.core.Permission) JDA(net.dv8tion.jda.core.JDA) Calendar(com.google.api.services.calendar.Calendar) VerifyUtilities(ws.nmathe.saber.utils.VerifyUtilities) Logging(ws.nmathe.saber.utils.Logging) IOException(java.io.IOException) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Consumer(java.util.function.Consumer) com.google.api.services.calendar.model(com.google.api.services.calendar.model) DateTimeFormatter(java.time.format.DateTimeFormatter) EntryManager(ws.nmathe.saber.core.schedule.EntryManager) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Main(ws.nmathe.saber.Main) Pattern(java.util.regex.Pattern) ParsingUtilities(ws.nmathe.saber.utils.ParsingUtilities) Message(net.dv8tion.jda.core.entities.Message) JDA(net.dv8tion.jda.core.JDA) Document(org.bson.Document) DateTime(com.google.api.client.util.DateTime) Bson(org.bson.conversions.Bson) EventRecurrence(ws.nmathe.saber.core.schedule.EventRecurrence) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) IOException(java.io.IOException)

Example 15 with JDA

use of net.dv8tion.jda.core.JDA in project Saber-Bot by notem.

the class ScheduleManager method sortSchedule.

/**
 * Reorders the schedule so that entries are displayed by start datetime ascending order in
 * the discord schedule channel
 * @param cId schedule ID
 * @param reverseOrder (boolean) whether or not to reverse the sort order
 */
public void sortSchedule(String cId, boolean reverseOrder) {
    if (this.getScheduleSize(cId) > 15)
        return;
    if (this.isLocked(cId))
        return;
    // lock the channel
    this.lock(cId);
    // always unlock the schedule at finish regardless of success or failure
    try {
        // identify which shard is responsible for the schedule
        Document doc = Main.getDBDriver().getScheduleCollection().find(eq("_id", cId)).projection(fields(include("guildId"))).first();
        JDA jda = Main.getShardManager().getJDA(doc.getString("guildId"));
        // find the message channel and send the 'is typing' while processing
        MessageChannel chan = jda.getTextChannelById(cId);
        chan.sendTyping().queue();
        int sortOrder = 1;
        if (reverseOrder)
            sortOrder = -1;
        LinkedList<ScheduleEntry> unsortedEntries = new LinkedList<>();
        Main.getDBDriver().getEventCollection().find(eq("channelId", cId)).sort(new Document("start", sortOrder)).forEach((Consumer<? super Document>) document -> unsortedEntries.add(new ScheduleEntry(document)));
        // selection sort the entries by timestamp
        while (!unsortedEntries.isEmpty()) {
            // continue to send 'is typing'
            chan.sendTyping().queue();
            ScheduleEntry top = unsortedEntries.pop();
            ScheduleEntry min = top;
            for (ScheduleEntry cur : unsortedEntries) {
                Message minMsg = min.getMessageObject();
                Message topMsg = cur.getMessageObject();
                if (minMsg != null && topMsg != null) {
                    OffsetDateTime a = minMsg.getCreationTime();
                    OffsetDateTime b = topMsg.getCreationTime();
                    if (a.isAfter(b)) {
                        min = cur;
                    }
                }
            }
            // swap messages and update db
            if (!(min == top)) {
                Message tmp = top.getMessageObject();
                top.setMessageObject(min.getMessageObject());
                Main.getDBDriver().getEventCollection().updateOne(eq("_id", top.getId()), new Document("$set", new Document("messageId", min.getMessageObject().getId())));
                min.setMessageObject(tmp);
                Main.getDBDriver().getEventCollection().updateOne(eq("_id", min.getId()), new Document("$set", new Document("messageId", tmp.getId())));
            }
            // reload display
            top.reloadDisplay();
        }
    } catch (PermissionException e) {
        String m = e.getMessage() + ": Channel ID " + cId;
        Logging.warn(this.getClass(), m);
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    } finally {
        // always unlock
        this.unlock(cId);
    }
}
Also used : Document(org.bson.Document) java.util(java.util) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Projections.fields(com.mongodb.client.model.Projections.fields) Logging(ws.nmathe.saber.utils.Logging) Updates.set(com.mongodb.client.model.Updates.set) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) Collectors(java.util.stream.Collectors) Message(net.dv8tion.jda.core.entities.Message) Executors(java.util.concurrent.Executors) Projections.include(com.mongodb.client.model.Projections.include) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Guild(net.dv8tion.jda.core.entities.Guild) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) java.time(java.time) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) Permission(net.dv8tion.jda.core.Permission) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) JDA(net.dv8tion.jda.core.JDA) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Message(net.dv8tion.jda.core.entities.Message) JDA(net.dv8tion.jda.core.JDA) Document(org.bson.Document) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel)

Aggregations

JDA (net.dv8tion.jda.core.JDA)42 Guild (net.dv8tion.jda.core.entities.Guild)10 TextChannel (net.dv8tion.jda.core.entities.TextChannel)9 Document (org.bson.Document)9 Permission (net.dv8tion.jda.core.Permission)7 Main (ws.nmathe.saber.Main)7 Consumer (java.util.function.Consumer)6 Message (net.dv8tion.jda.core.entities.Message)6 JSONObject (org.json.JSONObject)5 Logging (ws.nmathe.saber.utils.Logging)5 ArrayList (java.util.ArrayList)4 Collections (java.util.Collections)4 Date (java.util.Date)4 List (java.util.List)4 Collectors (java.util.stream.Collectors)4 Member (net.dv8tion.jda.core.entities.Member)4 Bson (org.bson.conversions.Bson)4 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)3 User (net.dv8tion.jda.core.entities.User)3 PermissionException (net.dv8tion.jda.core.exceptions.PermissionException)3