Search in sources :

Example 16 with JDA

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

the class MessageGenerator method generate.

/**
 * Primary method which generates a complete Discord message object for the event
 * @param se (ScheduleEntry) to generate a message display
 * @return the message to be used to display the event in it's associated Discord channel
 */
public static Message generate(ScheduleEntry se) {
    JDA jda = Main.getShardManager().getJDA(se.getGuildId());
    String titleUrl = (se.getTitleUrl() != null && VerifyUtilities.verifyUrl(se.getTitleUrl())) ? se.getTitleUrl() : "https://nmathe.ws/bots/saber";
    String titleImage = "https://upload.wikimedia.org/wikipedia/en/8/8d/Calendar_Icon.png";
    String footerStr = "ID: " + ParsingUtilities.intToEncodedID(se.getId());
    if (se.isQuietEnd() || se.isQuietStart() || se.isQuietRemind()) {
        footerStr += " |";
        if (se.isQuietStart())
            footerStr += " quiet-start";
        if (se.isQuietEnd())
            footerStr += " quiet-end";
        if (se.isQuietRemind())
            footerStr += " quiet-remind";
    }
    // generate reminder footer
    List<Date> reminders = new ArrayList<>();
    reminders.addAll(se.getReminders());
    reminders.addAll(se.getEndReminders());
    if (!reminders.isEmpty()) {
        footerStr += " | remind in ";
        long minutes = Instant.now().until(reminders.get(0).toInstant(), ChronoUnit.MINUTES);
        if (minutes <= 120) {
            footerStr += " " + minutes + "m";
        } else {
            footerStr += " " + (int) Math.ceil(minutes / 60) + "h";
        }
        for (int i = 1; i < reminders.size() - 1; i++) {
            minutes = Instant.now().until(reminders.get(i).toInstant(), ChronoUnit.MINUTES);
            if (minutes <= 120) {
                footerStr += ", " + minutes + "m";
            } else {
                footerStr += ", " + (int) Math.ceil(minutes / 60) + "h";
            }
        }
        if (reminders.size() > 1) {
            minutes = Instant.now().until(reminders.get(reminders.size() - 1).toInstant(), ChronoUnit.MINUTES);
            footerStr += " and ";
            if (minutes <= 120) {
                footerStr += minutes + "m";
            } else {
                footerStr += (int) Math.ceil(minutes / 60) + "h";
            }
        }
    }
    // get embed color from first hoisted bot role
    Color color = Color.DARK_GRAY;
    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);
        }
    }
    // generate the body of the embed
    String bodyContent;
    if (Main.getScheduleManager().getStyle(se.getChannelId()).toLowerCase().equals("narrow")) {
        bodyContent = generateBodyNarrow(se);
    } else {
        bodyContent = generateBodyFull(se);
    }
    // build the embed
    EmbedBuilder builder = new EmbedBuilder();
    builder.setDescription(bodyContent).setColor(color).setAuthor(se.getTitle(), titleUrl, titleImage).setFooter(footerStr, null);
    if (se.getImageUrl() != null && VerifyUtilities.verifyUrl(se.getImageUrl())) {
        builder.setImage(se.getImageUrl());
    }
    if (se.getThumbnailUrl() != null && VerifyUtilities.verifyUrl(se.getThumbnailUrl())) {
        builder.setThumbnail(se.getThumbnailUrl());
    }
    return new MessageBuilder().setEmbed(builder.build()).build();
}
Also used : Role(net.dv8tion.jda.core.entities.Role) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) JDA(net.dv8tion.jda.core.JDA)

Example 17 with JDA

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

the class EntryManager method newEntry.

/**
 * Create a new entry on a schedule
 * @param se (ScheduleEntry) the base ScheduleEntry object to use
 */
public Integer newEntry(ScheduleEntry se, boolean sort) {
    // identify which shard is responsible for the schedule
    String guildId = se.getGuildId();
    String channelId = se.getChannelId();
    JDA jda = Main.getShardManager().getJDA(guildId);
    // generate the reminders
    se.reloadReminders(Main.getScheduleManager().getReminders(se.getChannelId())).reloadEndReminders(Main.getScheduleManager().getEndReminders(se.getChannelId()));
    // process expiration date
    Date expire = null;
    if (se.getExpire() != null) {
        expire = Date.from(se.getExpire().toInstant());
    }
    // process deadline
    Date deadline = null;
    if (se.getDeadline() != null) {
        deadline = Date.from(se.getDeadline().toInstant());
    }
    // is rsvp enabled on the channel set empty rsvp lists
    if (Main.getScheduleManager().isRSVPEnabled(se.getChannelId())) {
        for (String type : Main.getScheduleManager().getRSVPOptions(se.getChannelId()).values()) {
            se.setRsvpMembers(type, new ArrayList<>());
        }
    }
    // generate event display message
    se.setId(this.newId());
    Message message = MessageGenerator.generate(se);
    // send message to schedule
    TextChannel channel = jda.getTextChannelById(channelId);
    Date finalExpire = expire;
    Date finalDeadline = deadline;
    MessageUtilities.sendMsg(message, channel, msg -> {
        try {
            // add reaction options if rsvp is enabled
            if (Main.getScheduleManager().isRSVPEnabled(channelId)) {
                Map<String, String> map = Main.getScheduleManager().getRSVPOptions(channelId);
                addRSVPReactions(map, Main.getScheduleManager().getRSVPClear(channelId), msg);
            }
            // add new document
            Document entryDocument = new Document("_id", se.getId()).append("title", se.getTitle()).append("start", Date.from(se.getStart().toInstant())).append("end", Date.from(se.getEnd().toInstant())).append("comments", se.getComments()).append("recurrence", se.getRepeat()).append("reminders", se.getReminders()).append("end_reminders", se.getEndReminders()).append("url", se.getTitleUrl()).append("hasStarted", se.hasStarted()).append("messageId", msg.getId()).append("channelId", se.getChannelId()).append("googleId", se.getGoogleId()).append("rsvp_members", se.getRsvpMembers()).append("rsvp_limits", se.getRsvpLimits()).append("image", se.getImageUrl()).append("thumbnail", se.getThumbnailUrl()).append("orig_start", Date.from(se.getRecurrence().getOriginalStart().toInstant())).append("count", se.getRecurrence().getCount()).append("start_disabled", false).append("end_disabled", false).append("reminders_disabled", false).append("expire", finalExpire).append("deadline", finalDeadline).append("guildId", se.getGuildId()).append("location", se.getLocation());
            Main.getDBDriver().getEventCollection().insertOne(entryDocument);
            // auto-sort
            autoSort(sort, channelId);
        } catch (Exception e) {
            Logging.exception(EntryManager.class, e);
        }
    });
    return se.getId();
}
Also used : TextChannel(net.dv8tion.jda.core.entities.TextChannel) Message(net.dv8tion.jda.core.entities.Message) JDA(net.dv8tion.jda.core.JDA) Document(org.bson.Document) MongoException(com.mongodb.MongoException)

Example 18 with JDA

use of net.dv8tion.jda.core.JDA 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()) {
        if (args.length > 0) {
            switch(args[0]) {
                case "restart":
                    Integer shardId = Integer.parseInt(args[1]);
                    Main.getShardManager().restartShard(shardId);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ignored) {
                    }
                    break;
            }
        }
        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.getPing() + "\"\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) CommandInfo(ws.nmathe.saber.commands.CommandInfo) ChannelType(net.dv8tion.jda.core.entities.ChannelType) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) JDA(net.dv8tion.jda.core.JDA) Main(ws.nmathe.saber.Main) JDA(net.dv8tion.jda.core.JDA)

Example 19 with JDA

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

the class ScheduleSyncer method run.

public void run() {
    Logging.info(this.getClass(), "Running schedule syncer. . .");
    Bson query = and(ne("sync_address", "off"), lte("sync_time", new Date()));
    Main.getDBDriver().getScheduleCollection().find(query).projection(fields(include("_id", "sync_time", "sync_address", "sync_user", "guildId"))).forEach((Consumer<? super Document>) document -> {
        executor.execute(() -> {
            try {
                String guildId = document.getString("guildId");
                JDA jda = Main.getShardManager().getJDA(guildId);
                if (jda == null)
                    return;
                if (JDA.Status.valueOf("CONNECTED") != jda.getStatus())
                    return;
                String scheduleId = document.getString("_id");
                Date syncTime = Date.from(ZonedDateTime.ofInstant(document.getDate("sync_time").toInstant(), Main.getScheduleManager().getTimeZone(scheduleId)).plusDays(1).toInstant());
                Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", scheduleId), set("sync_time", syncTime));
                String address = document.getString("sync_address");
                Credential credential = document.get("sync_user") == null ? GoogleAuth.authorize() : GoogleAuth.getCredential(document.getString("sync_user"));
                Calendar service = GoogleAuth.getCalendarService(credential);
                TextChannel channel = jda.getTextChannelById(document.getString("_id"));
                if (channel == null)
                    return;
                if (Main.getCalendarConverter().checkValidAddress(address, service)) {
                    Main.getCalendarConverter().importCalendar(address, channel, service);
                    Logging.info(this.getClass(), "Synchronized schedule #" + channel.getName() + " [" + document.getString("_id") + "] on '" + channel.getGuild().getName() + "' [" + channel.getGuild().getId() + "]");
                } else {
                    GuildSettingsManager.GuildSettings gs = Main.getGuildSettingsManager().getGuildSettings(guildId);
                    TextChannel control = Main.getShardManager().getJDA(guildId).getTextChannelById(gs.getCommandChannelId());
                    String content = "**Warning:** I failed to auto-sync <#" + scheduleId + "> to *" + address + "*!\n" + "Please make sure that the calendar address is still correct and that the calendar privacy settings have not changed!";
                    MessageUtilities.sendMsg(content, control, null);
                    Logging.warn(this.getClass(), "Failed to synchronize schedule #" + channel.getName() + " [" + document.getString("_id") + "] on '" + channel.getGuild().getName() + "' [" + channel.getGuild().getId() + "]");
                }
            } catch (Exception e) {
                Logging.exception(this.getClass(), e);
            }
        });
    });
}
Also used : Document(org.bson.Document) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Date(java.util.Date) Projections.fields(com.mongodb.client.model.Projections.fields) Logging(ws.nmathe.saber.utils.Logging) ZonedDateTime(java.time.ZonedDateTime) Updates.set(com.mongodb.client.model.Updates.set) GoogleAuth(ws.nmathe.saber.core.google.GoogleAuth) Executors(java.util.concurrent.Executors) Projections.include(com.mongodb.client.model.Projections.include) Bson(org.bson.conversions.Bson) Consumer(java.util.function.Consumer) Filters(com.mongodb.client.model.Filters) GuildSettingsManager(ws.nmathe.saber.core.settings.GuildSettingsManager) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) JDA(net.dv8tion.jda.core.JDA) Credential(com.google.api.client.auth.oauth2.Credential) Calendar(com.google.api.services.calendar.Calendar) Main(ws.nmathe.saber.Main) Main.getGuildSettingsManager(ws.nmathe.saber.Main.getGuildSettingsManager) ExecutorService(java.util.concurrent.ExecutorService) Credential(com.google.api.client.auth.oauth2.Credential) TextChannel(net.dv8tion.jda.core.entities.TextChannel) JDA(net.dv8tion.jda.core.JDA) Calendar(com.google.api.services.calendar.Calendar) Date(java.util.Date) Bson(org.bson.conversions.Bson)

Example 20 with JDA

use of net.dv8tion.jda.core.JDA in project legendarybot by greatman.

the class BotGeneralPlugin method start.

@Override
public void start() {
    getBot().getCommandHandler().addCommand("invite", new InviteCommand(getBot()), "General Commands");
    log.info("Command !invite loaded!");
    getBot().getCommandHandler().addCommand("help", new HelpCommand(getBot()), "General Commands");
    log.info("Command !help loaded!");
    getBot().getCommandHandler().addCommand("info", new InfoCommand(getBot()), "General Commands");
    // We find our main guild
    Guild guild = null;
    for (JDA jda : getBot().getJDA()) {
        Guild guildEntry = jda.getGuildById("330748360673722381");
        if (guildEntry != null) {
            guild = guildEntry;
        }
    }
    listener = new MessageListener(guild);
    getBot().getJDA().forEach(jda -> jda.addEventListener(listener));
}
Also used : InviteCommand(com.greatmancode.legendarybot.plugin.botgeneral.commands.InviteCommand) HelpCommand(com.greatmancode.legendarybot.plugin.botgeneral.commands.HelpCommand) JDA(net.dv8tion.jda.core.JDA) InfoCommand(com.greatmancode.legendarybot.plugin.botgeneral.commands.InfoCommand) Guild(net.dv8tion.jda.core.entities.Guild)

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