Search in sources :

Example 1 with MessageChannel

use of net.dv8tion.jda.api.entities.MessageChannel 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) > MAX_SIZE_TO_SYNC)
        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.getTimeCreated();
                    OffsetDateTime b = topMsg.getTimeCreated();
                    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 : Message(net.dv8tion.jda.api.entities.Message) Document(org.bson.Document) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Projections.fields(com.mongodb.client.model.Projections.fields) Permission(net.dv8tion.jda.api.Permission) Logging(ws.nmathe.saber.utils.Logging) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Updates.set(com.mongodb.client.model.Updates.set) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Projections.include(com.mongodb.client.model.Projections.include) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) java.time(java.time) Guild(net.dv8tion.jda.api.entities.Guild) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Message(net.dv8tion.jda.api.entities.Message) JDA(net.dv8tion.jda.api.JDA) Document(org.bson.Document) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel)

Example 2 with MessageChannel

use of net.dv8tion.jda.api.entities.MessageChannel 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 3 with MessageChannel

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

the class PurgeCommand method verify.

@Override
public String verify(String prefix, String[] args, MessageReceivedEvent event) {
    String head = prefix + this.name();
    int index = 0;
    // verify current argument count
    if (args.length != 1) {
        return "This command requires a channel as an argument!";
    }
    // verify argument 1 is properly formed
    if (!args[index].matches("<#[\\d]+>")) {
        return "Your channel name, *" + args[index] + "*, looks malformed!";
    }
    // verify that argument is a proper link to a channel
    MessageChannel channel = event.getJDA().getTextChannelById(args[index].replaceAll("[^\\d]", ""));
    if (channel == null) {
        return "I could not find " + args[index] + " on your guild!";
    }
    // basic protection against misuse
    if (limiter.check(event.getGuild().getId())) {
        return "The purge command has been used on your guild recently.\n" + "Please wait at least one minute before reusing the command!";
    }
    if (processing.keySet().contains(event.getGuild().getId())) {
        return "I am still purging messages from <#" + processing.getOrDefault(event.getGuild().getId(), "0") + ">.\n" + "You may not issue another purge command until this finishes.";
    }
    return "";
}
Also used : MessageChannel(net.dv8tion.jda.api.entities.MessageChannel)

Example 4 with MessageChannel

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

the class GlobalMsgCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    String msg = "";
    for (String arg : args) {
        msg += arg + " ";
    }
    for (Guild guild : Main.getShardManager().getGuilds()) {
        String channelId = Main.getGuildSettingsManager().getGuildSettings(guild.getId()).getCommandChannelId();
        if (// look for default control channel name
        channelId == null) {
            Collection<TextChannel> chans = guild.getTextChannelsByName(Main.getBotSettingsManager().getControlChan(), true);
            for (TextChannel chan : chans) {
                MessageUtilities.sendMsg(msg, chan, null);
            }
        } else // send to configured control channel
        {
            MessageChannel chan = guild.getTextChannelById(channelId);
            if (chan != null) {
                MessageUtilities.sendMsg(msg, chan, null);
            }
        }
    }
    MessageUtilities.sendPrivateMsg("Finished sending announcements to guilds!", event.getAuthor(), null);
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) Guild(net.dv8tion.jda.api.entities.Guild)

Aggregations

MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)4 Guild (net.dv8tion.jda.api.entities.Guild)3 TextChannel (net.dv8tion.jda.api.entities.TextChannel)3 Filters.eq (com.mongodb.client.model.Filters.eq)2 Projections.fields (com.mongodb.client.model.Projections.fields)2 Projections.include (com.mongodb.client.model.Projections.include)2 Consumer (java.util.function.Consumer)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2 JDA (net.dv8tion.jda.api.JDA)2 Permission (net.dv8tion.jda.api.Permission)2 Document (org.bson.Document)2 Main (ws.nmathe.saber.Main)2 Logging (ws.nmathe.saber.utils.Logging)2 Updates.set (com.mongodb.client.model.Updates.set)1 java.time (java.time)1 ChronoUnit (java.time.temporal.ChronoUnit)1 java.util (java.util)1 Collection (java.util.Collection)1 Executors (java.util.concurrent.Executors)1