Search in sources :

Example 11 with JDA

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

the class EntryProcessor method run.

@SuppressWarnings("unchecked")
public void run() {
    try {
        /*
             * Process events
             */
        if (type == EntryManager.type.PROCESS) {
            Logging.info(this.getClass(), "Processing entries. . .");
            Bson query;
            /*
                 * process any event-specific announcements
                 */
            query = lte("announcements", new Date());
            processEvents(ActionType.SPECIAL, query);
            /*
                 * process events to end
                 */
            query = and(eq("hasStarted", true), lte("end", new Date()));
            processEvents(ActionType.END, query);
            /*
                 * process events to start
                 */
            query = and(eq("hasStarted", false), lte("start", new Date()));
            processEvents(ActionType.START, query);
            /*
                 * process events with reminders
                 */
            query = and(and(eq("hasStarted", false), lte("reminders", new Date())), gte("start", new Date()));
            query = or(query, and(and(eq("hasStarted", true), lte("end_reminders", new Date())), gte("end", new Date())));
            processEvents(ActionType.REMIND, query);
            Logging.info(this.getClass(), "Currently processing " + processing.size() + " events.");
            // exit the bot if any event takes more than a few minutes to process
            int timeThreshold = 3;
            int countThreshold = 30;
            int count = 0;
            for (Date value : timestamps.values()) {
                boolean flagged = value.before(Date.from(Instant.now().minus(timeThreshold, ChronoUnit.MINUTES)));
                if (flagged)
                    count += 1;
            }
            if (count > countThreshold) {
                String txt = "[EXIT] There are " + count + " events that have been in processing for over " + timeThreshold + ".";
                Logging.warn(this.getClass(), txt);
                System.exit(-100);
            }
        } else /*
             * Updates the 'starts in x minutes' timer on events
             */
        {
            // dummy document query will filter all events
            // should an invalid level ever be passed in, all entries will be reloaded!
            Bson query = new Document();
            Logging.info(this.getClass(), "Processing entries: updating timers. . .");
            if (type == EntryManager.type.UPDATE1) {
                // adjust timers for entries starting/ending within the next hour
                query = or(and(eq("hasStarted", false), and(lte("start", Date.from(ZonedDateTime.now().plusHours(1).toInstant())), gte("start", Date.from(ZonedDateTime.now().plusMinutes(4).toInstant())))), and(eq("hasStarted", true), and(lte("end", Date.from(ZonedDateTime.now().plusHours(1).toInstant())), gte("end", Date.from(ZonedDateTime.now().plusMinutes(4).toInstant())))));
            }
            if (type == EntryManager.type.UPDATE2) {
                // purge expiring events
                query = lte("expire", Date.from(ZonedDateTime.now().plusDays(1).toInstant()));
                // delete message objects
                Main.getDBDriver().getEventCollection().find(query).forEach((Consumer<? super Document>) document -> {
                    MessageUtilities.deleteMsg((new ScheduleEntry(document)).getMessageObject(), null);
                });
                // bulk delete entries from the database
                Main.getDBDriver().getEventCollection().deleteMany(query);
                // adjust timers
                query = or(and(eq("hasStarted", false), and(lte("start", Date.from(ZonedDateTime.now().plusDays(1).toInstant())), gte("start", Date.from(ZonedDateTime.now().plusHours(1).toInstant())))), and(eq("hasStarted", true), and(lte("end", Date.from(ZonedDateTime.now().plusDays(1).toInstant())), gte("end", Date.from(ZonedDateTime.now().plusHours(1).toInstant())))));
            }
            if (type == EntryManager.type.UPDATE3) {
                // adjust timers for entries that aren't starting/ending within the next day
                query = or(and(eq("hasStarted", false), gte("start", Date.from(ZonedDateTime.now().plusDays(1).toInstant()))), and(eq("hasStarted", true), gte("end", Date.from(ZonedDateTime.now().plusDays(1).toInstant()))));
            }
            // reload entries based on the appropriate query
            Main.getDBDriver().getEventCollection().find(query).forEach((Consumer<? super Document>) document -> {
                String guildId = document.getString("guildId");
                JDA jda = Main.getShardManager().getJDA(guildId);
                if (jda == null)
                    return;
                if (!jda.getStatus().equals(JDA.Status.CONNECTED))
                    return;
                timerExecutor.execute(() -> {
                    try {
                        (new ScheduleEntry(document)).reloadDisplay();
                    } catch (PermissionException ignored) {
                    } catch (Exception e) {
                        Logging.warn(this.getClass(), "Error occurred while updating event timer.");
                        Logging.exception(this.getClass(), e);
                    }
                });
            });
            Logging.info(this.getClass(), "Finished updating timers. . .");
        }
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    }
}
Also used : Document(org.bson.Document) JDA(net.dv8tion.jda.api.JDA) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Date(java.util.Date) java.util.concurrent(java.util.concurrent) Logging(ws.nmathe.saber.utils.Logging) ZonedDateTime(java.time.ZonedDateTime) Set(java.util.Set) Instant(java.time.Instant) Bson(org.bson.conversions.Bson) Consumer(java.util.function.Consumer) Filters(com.mongodb.client.model.Filters) ChronoUnit(java.time.temporal.ChronoUnit) Map(java.util.Map) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Main(ws.nmathe.saber.Main) Collections(java.util.Collections) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) JDA(net.dv8tion.jda.api.JDA) Document(org.bson.Document) Date(java.util.Date) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Bson(org.bson.conversions.Bson)

Example 12 with JDA

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

the class EventListener method onGuildJoin.

@Override
public void onGuildJoin(GuildJoinEvent event) {
    // leave guild if guild is blacklisted
    if (Main.getBotSettingsManager().getBlackList().contains(event.getGuild().getId())) {
        event.getGuild().leave().queue();
        return;
    }
    // identify which shard is responsible for the guild
    String guildId = event.getGuild().getId();
    JDA jda = Main.getShardManager().isSharding() ? Main.getShardManager().getShard(guildId) : Main.getShardManager().getJDA();
    // send welcome message to the server owner
    String welcomeMessage = "```diff\n- Joined```\n" + "**" + jda.getSelfUser().getName() + "**, a calendar bot, has been added to the guild you own, '" + event.getGuild().getName() + "'." + "\n\n" + "If this is your first time using the bot, you will need to create a new channel in your guild named" + " **" + Main.getBotSettingsManager().getControlChan() + "** to control the bot.\n" + "The bot will not listen to commands in any other channel!" + "\n\n" + "If you have not yet reviewed the **Quickstart** guide (as seen on the bots.discord.pw listing), " + "it may be found here: https://bots.discord.pw/bots/250801603630596100";
    MessageUtilities.sendPrivateMsg(welcomeMessage, event.getGuild().getOwner().getUser(), null);
    // update web stats
    JDA.ShardInfo info = event.getJDA().getShardInfo();
    HttpUtilities.updateStats(info == null ? null : info.getShardId());
}
Also used : JDA(net.dv8tion.jda.api.JDA)

Example 13 with JDA

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

the class Pruner method run.

@Override
public void run() {
    Logging.info(this.getClass(), "Running database pruner. . .");
    // purge guild setting entries for any guild not connected to the bot
    Bson query = new Document();
    Main.getDBDriver().getGuildCollection().find(query).projection(fields(include("_id"))).forEach((Consumer<? super Document>) document -> {
        try {
            String guildId = document.getString("_id");
            JDA jda = Main.getShardManager().getShard(guildId);
            if (jda == null)
                return;
            if (JDA.Status.valueOf("CONNECTED") != jda.getStatus())
                return;
            Guild guild = jda.getGuildById(guildId);
            if (guild == null) {
                Main.getDBDriver().getGuildCollection().deleteOne(eq("_id", guildId));
                Main.getDBDriver().getEventCollection().deleteMany(eq("guildId", guildId));
                Main.getDBDriver().getScheduleCollection().deleteMany(eq("guildId", guildId));
                Logging.info(this.getClass(), "Pruned guild with ID: " + guildId);
            }
        } catch (Exception e) {
            Logging.exception(this.getClass(), e);
        }
    });
    // purge schedules that the bot cannot connect to
    query = new Document();
    Main.getDBDriver().getScheduleCollection().find(query).projection(fields(include("_id", "guildId"))).forEach((Consumer<? super Document>) document -> {
        try {
            String guildId = document.getString("guildId");
            JDA jda = Main.getShardManager().getShard(guildId);
            if (jda == null)
                return;
            if (JDA.Status.valueOf("CONNECTED") != jda.getStatus())
                return;
            String chanId = document.getString("_id");
            MessageChannel channel = jda.getTextChannelById(chanId);
            if (channel == null) {
                Main.getDBDriver().getEventCollection().deleteMany(eq("channeldId", chanId));
                Main.getDBDriver().getScheduleCollection().deleteMany(eq("_id", chanId));
                Logging.info(this.getClass(), "Pruned schedule with channel ID: " + chanId);
            }
        } catch (Exception e) {
            Logging.exception(this.getClass(), e);
        }
    });
    // purge events for which the bot cannot access the message
    query = new Document();
    Main.getDBDriver().getEventCollection().find(query).projection(fields(include("_id", "messageId", "channelId", "guildId"))).forEach((Consumer<? super Document>) document -> {
        try {
            String guildId = document.getString("guildId");
            JDA jda = Main.getShardManager().getShard(guildId);
            if (jda == null)
                return;
            if (JDA.Status.valueOf("CONNECTED") != jda.getStatus())
                return;
            Integer eventId = document.getInteger("_id");
            String messageId = document.getString("messageId");
            if (messageId == null) {
                Main.getDBDriver().getEventCollection().deleteOne(eq("_id", eventId));
                Logging.info(this.getClass(), "Pruned event with ID: " + eventId);
                return;
            }
            String channelId = document.getString("channelId");
            TextChannel channel = jda.getTextChannelById(channelId);
            if (channel == null) {
                return;
            }
            channel.retrieveMessageById(messageId).queue(message -> {
                if (message == null) {
                    Main.getDBDriver().getEventCollection().deleteOne(eq("_id", eventId));
                    Logging.info(this.getClass(), "Pruned event with ID: " + eventId + " on channel with ID: " + channelId);
                }
            }, throwable -> {
                Main.getDBDriver().getEventCollection().deleteOne(eq("_id", eventId));
                Logging.info(this.getClass(), "Pruned event with ID: " + eventId + " on channel with ID: " + channelId);
            });
        } catch (Exception e) {
            Logging.exception(this.getClass(), e);
        }
    });
}
Also used : Document(org.bson.Document) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) JDA(net.dv8tion.jda.api.JDA) Projections.fields(com.mongodb.client.model.Projections.fields) Permission(net.dv8tion.jda.api.Permission) Logging(ws.nmathe.saber.utils.Logging) Collection(java.util.Collection) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Collectors(java.util.stream.Collectors) Projections.include(com.mongodb.client.model.Projections.include) Bson(org.bson.conversions.Bson) Consumer(java.util.function.Consumer) Guild(net.dv8tion.jda.api.entities.Guild) Stream(java.util.stream.Stream) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) JDA(net.dv8tion.jda.api.JDA) Document(org.bson.Document) Guild(net.dv8tion.jda.api.entities.Guild) Bson(org.bson.conversions.Bson)

Example 14 with JDA

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

the class MessageGenerator method generateColor.

/**
 * creates the color object to be used with the embed
 * @param se ScheduleEntry object
 * @return color
 */
private static Color generateColor(ScheduleEntry se) {
    // attempt to use the ScheduleEntry's color attribute
    Color color = null;
    if (se.getColor() != null) {
        color = Color.getColor(se.getColor());
        if (color == null) {
            try {
                color = Color.decode(se.getColor());
            } catch (NumberFormatException ignored) {
                color = null;
            }
        }
    }
    // if color not yet defined, use color from bot hoisted role
    if (color == null) {
        // set default
        color = Color.DARK_GRAY;
        // find JDA shard instance for guild
        JDA jda = Main.getShardManager().getJDA(se.getGuildId());
        // get embed color from first hoisted bot role
        List<Role> roles = new ArrayList<>(jda.getGuildById(se.getGuildId()).getMember(jda.getSelfUser()).getRoles());
        while (!roles.isEmpty()) {
            if (roles.get(0).isHoisted()) {
                color = roles.get(0).getColor();
                break;
            } else {
                roles.remove(0);
            }
        }
    }
    // return the color (default DARK_GRAY)
    return color;
}
Also used : Role(net.dv8tion.jda.api.entities.Role) JDA(net.dv8tion.jda.api.JDA)

Example 15 with JDA

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

the class ScheduleManager method deleteSchedule.

/**
 * Removes a schedule and attempts to delete the schedule's channel
 * @param cId (String) ID of channel / schedule (synonymous)
 */
public void deleteSchedule(String cId) {
    // 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"));
    try {
        jda.getTextChannelById(cId).delete().complete();
    } catch (PermissionException e) {
        String m = e.getMessage() + ": " + e.getPermission();
        Logging.warn(this.getClass(), m);
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    }
    Main.getDBDriver().getEventCollection().deleteMany(eq("channelId", cId));
    Main.getDBDriver().getScheduleCollection().deleteOne(eq("_id", cId));
}
Also used : PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) JDA(net.dv8tion.jda.api.JDA) Document(org.bson.Document) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException)

Aggregations

JDA (net.dv8tion.jda.api.JDA)24 Document (org.bson.Document)7 Main (ws.nmathe.saber.Main)7 Consumer (java.util.function.Consumer)6 Permission (net.dv8tion.jda.api.Permission)6 PermissionException (net.dv8tion.jda.api.exceptions.PermissionException)6 Logging (ws.nmathe.saber.utils.Logging)5 TextChannel (net.dv8tion.jda.api.entities.TextChannel)4 Bson (org.bson.conversions.Bson)4 Filters (com.mongodb.client.model.Filters)3 Projections.fields (com.mongodb.client.model.Projections.fields)3 Projections.include (com.mongodb.client.model.Projections.include)3 ZonedDateTime (java.time.ZonedDateTime)3 ChronoUnit (java.time.temporal.ChronoUnit)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 Guild (net.dv8tion.jda.api.entities.Guild)3 Message (net.dv8tion.jda.api.entities.Message)3 MessageUtilities (ws.nmathe.saber.utils.MessageUtilities)3 Calendar (com.google.api.services.calendar.Calendar)2