Search in sources :

Example 26 with JDA

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

the class InstallEmotesCommand method createEmote.

// Code taken from JDA's GuildController since they have a limitation that bot accounts can't upload emotes.
private void createEmote(String iconName, CommandEvent commandEvent, Icon icon, Role... roles) {
    JSONObject body = new JSONObject();
    body.put("name", iconName);
    body.put("image", icon.getEncoding());
    if (// making sure none of the provided roles are null before mapping them to the snowflake id
    roles.length > 0) {
        body.put("roles", Stream.of(roles).filter(Objects::nonNull).map(ISnowflake::getId).collect(Collectors.toSet()));
    }
    GuildImpl guild = (GuildImpl) commandEvent.getGuild();
    JDA jda = commandEvent.getJDA();
    Route.CompiledRoute route = Route.Emotes.CREATE_EMOTE.compile(guild.getId());
    AuditableRestAction<Emote> action = new AuditableRestAction<Emote>(jda, route, body) {

        @Override
        protected void handleResponse(Response response, Request<Emote> request) {
            if (response.isOk()) {
                JSONObject obj = response.getObject();
                final long id = obj.getLong("id");
                String name = obj.getString("name");
                EmoteImpl emote = new EmoteImpl(id, guild).setName(name);
                // managed is false by default, should always be false for emotes created by client accounts.
                JSONArray rolesArr = obj.getJSONArray("roles");
                Set<Role> roleSet = emote.getRoleSet();
                for (int i = 0; i < rolesArr.length(); i++) {
                    roleSet.add(guild.getRoleById(rolesArr.getString(i)));
                }
                // put emote into cache
                guild.getEmoteMap().put(id, emote);
                request.onSuccess(emote);
            } else {
                request.onFailure(response);
                throw new RuntimeException("Couldn't install emojis. " + "Make sure that pokeraidbot has access to manage emojis.");
            }
        }
    };
    action.queue();
}
Also used : AuditableRestAction(net.dv8tion.jda.core.requests.restaction.AuditableRestAction) JDA(net.dv8tion.jda.core.JDA) Emote(net.dv8tion.jda.core.entities.Emote) Request(net.dv8tion.jda.core.requests.Request) JSONArray(org.json.JSONArray) Response(net.dv8tion.jda.core.requests.Response) Role(net.dv8tion.jda.core.entities.Role) GuildImpl(net.dv8tion.jda.core.entities.impl.GuildImpl) EmoteImpl(net.dv8tion.jda.core.entities.impl.EmoteImpl) JSONObject(org.json.JSONObject) Route(net.dv8tion.jda.core.requests.Route) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake)

Example 27 with JDA

use of net.dv8tion.jda.core.JDA in project lavaplayer by sedmelluq.

the class Main method main.

public static void main(String[] args) throws Exception {
    JDA jda = new JDABuilder(AccountType.BOT).setToken(System.getProperty("botToken")).buildBlocking();
    jda.addEventListener(new Main());
}
Also used : JDABuilder(net.dv8tion.jda.core.JDABuilder) JDA(net.dv8tion.jda.core.JDA)

Example 28 with JDA

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

the class ConfigCommand method genMsgStr.

/**
 * Generates the schedule config message to display to the user
 * type codes:  0 - full message
 *              1 - announcement settings
 *              2 - reminder settings
 *              3 - miscellaneous settings
 *              4 - sync settings
 *              5 - rsvp settings
 * @param cId (String) the ID of the schedule/channel
 * @return (String) the message to display
 */
private String genMsgStr(String cId, Mode mode, JDA jda) {
    ZoneId zone = Main.getScheduleManager().getTimeZone(cId);
    String content = "**Configuration for** <#" + cId + ">\n";
    switch(mode) {
        default:
        case ANN:
            String form1 = Main.getScheduleManager().getStartAnnounceFormat(cId);
            String form2 = Main.getScheduleManager().getEndAnnounceFormat(cId);
            String chanIdentifier = Main.getScheduleManager().getStartAnnounceChan(cId);
            String endChanIdentifier = Main.getScheduleManager().getEndAnnounceChan(cId);
            content += "```js\n" + "// Event Announcement Settings" + "\n[message]  " + (form1.isEmpty() ? "(off)" : "\"" + form1.replace("```", "`\uFEFF`\uFEFF`") + "\"") + "\n[channel]  " + "\"" + this.channelIdentifierToString(chanIdentifier, jda) + "\"" + "\n[end-msg]  " + (Main.getScheduleManager().isEndFormatOverridden(cId) ? (form2.isEmpty() ? "(off)" : "\"" + form2.replace("```", "`\uFEFF`\uFEFF`") + "\"") : "(using [message])") + "\n[end-chan] " + (Main.getScheduleManager().isEndChannelOverridden(cId) ? "\"" + this.channelIdentifierToString(endChanIdentifier, jda) + "\"" : "(using [channel])") + "```";
            if (mode == Mode.ANN)
                break;
        case REM:
            if (content.length() > 1900) {
                return content;
            }
            String form3 = Main.getScheduleManager().getReminderFormat(cId);
            List<Integer> reminders = Main.getScheduleManager().getReminders(cId);
            List<Integer> endReminders = Main.getScheduleManager().getEndReminders(cId);
            String remindChanIdentifier = Main.getScheduleManager().getReminderChan(cId);
            content += "```js\n" + "// Event Reminder Settings" + "\n[reminders]   " + "\"" + makeReminderString(reminders) + "\"" + "\n[end-remind]  " + "\"" + makeReminderString(endReminders) + "\"" + "\n[remind-msg]  " + (Main.getScheduleManager().isRemindFormatOverridden(cId) ? (form3.isEmpty() ? "(off)" : "\"" + form3.replace("```", "`\uFEFF`\uFEFF`") + "\"") : "(using [msg])") + "\n[remind-chan] " + (Main.getScheduleManager().isRemindChanOverridden(cId) ? "\"" + this.channelIdentifierToString(remindChanIdentifier, jda) + "\"" : "(using [chan])") + "```";
            if (mode == Mode.REM)
                break;
        case MISC:
            if (content.length() > 1900) {
                return content;
            }
            int sortType = Main.getScheduleManager().getAutoSort(cId);
            String sort = "";
            switch(sortType) {
                case 0:
                    sort = "disabled";
                    break;
                case 1:
                    sort = "ascending";
                    break;
                case 2:
                    sort = "descending";
                    break;
            }
            content += "```js\n" + "// Misc. Settings" + "\n[zone]   " + "\"" + zone + "\"" + "\n[clock]  " + "\"" + Main.getScheduleManager().getClockFormat(cId) + "\"" + "\n[style]  " + "\"" + Main.getScheduleManager().getStyle(cId).toLowerCase() + "\"" + "\n[sort]   " + "\"" + sort + "\"" + "```";
            if (mode == Mode.MISC)
                break;
        case SYNC:
            if (content.length() > 1900) {
                return content;
            }
            // get sync user object (if exists)
            User user = null;
            if (Main.getScheduleManager().getSyncUser(cId) != null)
                user = jda.getUserById(Main.getScheduleManager().getSyncUser(cId));
            content += "```js\n" + "// Schedule Sync Settings" + "\n[sync]   " + "\"" + Main.getScheduleManager().getAddress(cId) + "\"" + (user != null ? " (authorized by " + user.getName() + ")" : "");
            // display full body only if sync is on
            if (!Main.getScheduleManager().getAddress(cId).equalsIgnoreCase("off")) {
                Date syncTime = Main.getScheduleManager().getSyncTime(cId);
                OffsetTime sync_time_display = ZonedDateTime.ofInstant(syncTime.toInstant(), zone).toOffsetDateTime().toOffsetTime().truncatedTo(ChronoUnit.MINUTES);
                content += "\n[time]   " + "\"" + sync_time_display + "\"" + "\n[length] " + "\"" + Main.getScheduleManager().getSyncLength(cId) + "\"";
            }
            content += "```";
            if (mode == Mode.SYNC)
                break;
        case RSVP:
            if (content.length() > 1900) {
                return content;
            }
            String clear = Main.getScheduleManager().getRSVPClear(cId);
            content += "```js\n" + "// RSVP Settings" + "\n[rsvp]    " + "\"" + (Main.getScheduleManager().isRSVPEnabled(cId) ? "on" : "off") + "\"";
            // only display full settings message when rsvp is enabled
            if (Main.getScheduleManager().isRSVPEnabled(cId)) {
                // rsvp logging channel
                String logging = Main.getScheduleManager().getRSVPLogging(cId);
                content += "\n[clear]   " + "\"" + (clear.isEmpty() ? "off" : clear) + "\"" + "\n[confirm] " + "\"" + (Main.getScheduleManager().isRSVPConfirmationsEnabled(cId) ? "on" : "off") + "\"" + "\n[exclude] " + "\"" + (Main.getScheduleManager().isRSVPExclusive(cId) ? "on" : "off") + "\"" + "\n[logging] " + "\"" + (logging.isEmpty() ? "off" : channelIdentifierToString(logging, jda)) + "\"" + "\n<Groups>  ";
                // generate the list of rsvp groups
                Map<String, String> options = Main.getScheduleManager().getRSVPOptions(cId);
                for (String key : options.keySet()) {
                    if (EmojiManager.isEmoji(key)) {
                        content += " (" + options.get(key) + " - " + key + ")";
                    } else {
                        Emote emote = null;
                        for (JDA shard : Main.getShardManager().getShards()) {
                            emote = shard.getEmoteById(key);
                            if (emote != null)
                                break;
                        }
                        if (emote != null) {
                            String displayName = emote.getName();
                            content += " (" + options.get(key) + " - :" + displayName + ":)";
                        }
                    }
                }
            }
            content += "```";
            if (mode == Mode.RSVP)
                break;
    }
    return content;
}
Also used : JDA(net.dv8tion.jda.core.JDA)

Example 29 with JDA

use of net.dv8tion.jda.core.JDA 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 30 with JDA

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

the class EntryProcessor method run.

@SuppressWarnings("unchecked")
public void run() {
    try {
        /* Fills the sets which events which have announcements that should be processed */
        if (type == EntryManager.type.FILL) {
            Logging.info(this.getClass(), "Processing entries: Filling queues. . .");
            // process entries which are ending
            Bson query = and(eq("hasStarted", true), lte("end", new Date()));
            processAndQueueEvents(SetType.END_SET, query);
            // process entries which are starting
            query = and(eq("hasStarted", false), lte("start", new Date()));
            processAndQueueEvents(SetType.START_SET, query);
            // process entries with reminders
            query = and(and(eq("hasStarted", false), lte("reminders", new Date())), gte("start", new Date()));
            processAndQueueEvents(SetType.REMIND_SET, query);
            // process entries with end reminders
            query = and(and(eq("hasStarted", true), lte("end_reminders", new Date())), gte("end", new Date()));
            processAndQueueEvents(SetType.REMIND_SET, query);
            // process entries with announcement overrides
            query = lte("announcements", new Date());
            processAndQueueEvents(SetType.SPECIAL_SET, query);
            Logging.info(this.getClass(), "Finished filling queues.");
        } else /* Processes the events in each set */
        if (type == EntryManager.type.EMPTY) {
            Logging.info(this.getClass(), "Processing entries: Emptying queues. . .");
            endSet.forEach(entryId -> {
                if (!processing.contains(entryId)) {
                    setExecutor.submit(() -> {
                        try {
                            processing.add(entryId);
                            Main.getEntryManager().getEntry(entryId).end();
                            endSet.remove(entryId);
                            processing.remove(entryId);
                        } catch (Exception e) {
                            Logging.exception(this.getClass(), e);
                        }
                    });
                }
            });
            startSet.forEach(entryId -> {
                if (!processing.contains(entryId)) {
                    setExecutor.submit(() -> {
                        try {
                            processing.add(entryId);
                            Main.getEntryManager().getEntry(entryId).start();
                            startSet.remove(entryId);
                            processing.remove(entryId);
                        } catch (Exception e) {
                            Logging.exception(this.getClass(), e);
                        }
                    });
                }
            });
            remindSet.forEach(entryId -> {
                if (!processing.contains(entryId)) {
                    setExecutor.submit(() -> {
                        try {
                            processing.add(entryId);
                            Main.getEntryManager().getEntry(entryId).remind();
                            remindSet.remove(entryId);
                            processing.remove(entryId);
                        } catch (Exception e) {
                            Logging.exception(this.getClass(), e);
                        }
                    });
                }
            });
            specialSet.forEach(entryId -> {
                if (!processing.contains(entryId)) {
                    setExecutor.submit(() -> {
                        try {
                            processing.add(entryId);
                            Main.getEntryManager().getEntry(entryId).announce();
                            specialSet.remove(entryId);
                            processing.remove(entryId);
                        } catch (Exception e) {
                            Logging.exception(this.getClass(), e);
                        }
                    });
                }
            });
        // Logging.info(this.getClass(), "Finished emptying queues.");
        } 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.Status.valueOf("CONNECTED") != jda.getStatus())
                    return;
                timerExecutor.execute(() -> {
                    try {
                        (new ScheduleEntry(document)).reloadDisplay();
                    } catch (Exception e) {
                        Logging.exception(this.getClass(), e);
                    }
                });
            });
            Logging.info(this.getClass(), "Finished processing entries. . .");
        }
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    }
}
Also used : Document(org.bson.Document) Date(java.util.Date) java.util.concurrent(java.util.concurrent) Logging(ws.nmathe.saber.utils.Logging) ZonedDateTime(java.time.ZonedDateTime) Set(java.util.Set) Bson(org.bson.conversions.Bson) Consumer(java.util.function.Consumer) Filters(com.mongodb.client.model.Filters) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) JDA(net.dv8tion.jda.core.JDA) Main(ws.nmathe.saber.Main) Collections(java.util.Collections) Consumer(java.util.function.Consumer) JDA(net.dv8tion.jda.core.JDA) Document(org.bson.Document) Date(java.util.Date) Bson(org.bson.conversions.Bson)

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