Search in sources :

Example 6 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent in project legendarybot by greatman.

the class LegionBuildingCommand method execute.

@Override
public void execute(MessageReceivedEvent event, String[] args) {
    if (getBot().getGuildSettings(event.getGuild()).getRegionName() == null) {
        event.getChannel().sendMessage(getBot().getTranslateManager().translate(event.getGuild(), "server.region.must.be.set")).queue();
        return;
    }
    List<String> buildingStatus = new ArrayList<>();
    List<String> buildingStatusString = new ArrayList<>();
    try {
        Document document = Jsoup.connect("http://www.wowhead.com/").get();
        int skip = (!getBot().getGuildSettings(event.getGuild()).getRegionName().equalsIgnoreCase("US")) ? 3 : 0;
        document.getElementsByClass("imitation-heading heading-size-5").stream().skip(skip).forEach(element -> buildingStatusString.add(element.ownText()));
        document.getElementsByClass("tiw-bs-status-progress").stream().skip(skip).forEach(element -> element.getElementsByTag("span").forEach(value -> buildingStatus.add(value.ownText())));
        event.getChannel().sendMessage(getBot().getTranslateManager().translate(event.getGuild(), "command.legionbuilding.message", getBot().getTranslateManager().translate(event.getGuild(), buildingStatusString.get(0).replaceAll(" ", ".").toLowerCase()), buildingStatus.get(0), getBot().getTranslateManager().translate(event.getGuild(), buildingStatusString.get(1).replaceAll(" ", ".").toLowerCase()), buildingStatus.get(1), getBot().getTranslateManager().translate(event.getGuild(), buildingStatusString.get(2).replaceAll(" ", ".").toLowerCase()), buildingStatus.get(2))).queue();
    } catch (IOException e) {
        e.printStackTrace();
        getBot().getStacktraceHandler().sendStacktrace(e, "region:" + getBot().getGuildSettings(event.getGuild()).getRegionName(), "guildId:" + event.getGuild().getId());
        event.getChannel().sendMessage(getBot().getTranslateManager().translate(event.getGuild(), "error.occurred.try.again.later")).queue();
    } catch (NullPointerException e) {
        event.getChannel().sendMessage(getBot().getTranslateManager().translate(event.getGuild(), "error.occurred.try.again.later")).queue();
    }
}
Also used : Guild(net.dv8tion.jda.core.entities.Guild) ZeroArgsCommand(com.greatmancode.legendarybot.api.commands.ZeroArgsCommand) List(java.util.List) LegendaryBotPlugin(com.greatmancode.legendarybot.api.plugin.LegendaryBotPlugin) Document(org.jsoup.nodes.Document) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) PublicCommand(com.greatmancode.legendarybot.api.commands.PublicCommand) IOException(java.io.IOException) Jsoup(org.jsoup.Jsoup) PluginWrapper(org.pf4j.PluginWrapper) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.jsoup.nodes.Document)

Example 7 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent in project Ardent by adamint.

the class CommandFactory method pass.

/**
 * Handles generic message events, parses message content
 * and creates a new AsyncCommandExecutor that will execute the command
 *
 * @param event the MessageReceivedEvent to be handled
 */
public void pass(MessageReceivedEvent event, String prefix) {
    try {
        Guild guild = event.getGuild();
        User ardent = guild.getSelfMember().getUser();
        User user = event.getAuthor();
        if (user.isBot())
            return;
        Message message = event.getMessage();
        MessageChannel channel = event.getChannel();
        String[] args = message.getContent().split(" ");
        String rawContent = message.getRawContent();
        if (rawContent.startsWith(guild.getSelfMember().getUser().getAsMention())) {
            rawContent = rawContent.replaceFirst(ardent.getAsMention(), "");
            if (rawContent.length() == 0)
                channel.sendMessage("Type @Ardent [msg] to talk to me or /help to see a list of commands").queue();
            else {
                if (!Ardent.disabledCommands.contains("cleverbot")) {
                    channel.sendMessage(Unirest.post("https://cleverbot.io/1.0/ask").field("user", Ardent.cleverbotUser).field("key", Ardent.cleverbotKey).field("nick", "ardent").field("text", rawContent).asJson().getBody().getObject().getString("response")).queue();
                } else
                    channel.sendMessage("Cleverbot is currently disabled, sorry.").queue();
            }
            return;
        }
        if (!args[0].startsWith(prefix))
            return;
        String cmd = args[0].replaceFirst(prefix, "");
        final boolean[] ranCommand = { false };
        String pre = StringEscapeUtils.escapeJava(prefix);
        if (args[0].startsWith(pre)) {
            args[0] = args[0].replaceFirst(pre, "");
            baseCommands.forEach(command -> {
                if (command.getBotCommand().containsAlias(args[0])) {
                    command.botCommand.usages++;
                    if (!Ardent.disabledCommands.contains(command.getName())) {
                        EntityGuild entityGuild = EntityGuild.get(guild);
                        for (RestrictedUser u : entityGuild.getRestrictedUsers()) {
                            if (u.getUserId().equalsIgnoreCase(user.getId())) {
                                command.sendRestricted(user);
                                return;
                            }
                        }
                        GuildModel guildModel = BaseCommand.asPojo(r.table("guilds").get(guild.getId()).run(connection), GuildModel.class);
                        if (guildModel == null) {
                            guildModel = new GuildModel(guild.getId(), "english", "/");
                            r.table("guilds").insert(r.json(shard.gson.toJson(guildModel))).runNoReply(connection);
                        }
                        if (guildModel.role_permissions != null) {
                            for (RolePermission rolePermission : guildModel.role_permissions) {
                                Member member = guild.getMember(user);
                                Role r = guild.getRoleById(rolePermission.getId());
                                if (r != null && member.getRoles().contains(r) && !member.hasPermission(Permission.MANAGE_SERVER)) {
                                    if (!rolePermission.getCanUseArdentCommands()) {
                                        user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Ardent commands!").queue());
                                        return;
                                    }
                                    if (!message.getRawContent().toLowerCase().contains("discord.gg") && !rolePermission.getCanSendDiscordInvites()) {
                                        message.delete().queue();
                                        user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of " + "your roles, **" + r.getName() + "**, cannot send Discord server invite " + "links!").queue());
                                        return;
                                    }
                                    if (!rolePermission.getCanSendLinks()) {
                                        if (message.getContent().toLowerCase().contains("http://") || message.getContent().toLowerCase().contains("https://")) {
                                            message.delete().queue();
                                            user.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One" + " of " + "your roles, **" + r.getName() + "**, cannot send websiet links!").queue());
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                        new AsyncCommandExecutor(command.botCommand, guild, channel, event.getAuthor(), message, args, user).run();
                        commandsReceived++;
                        ranCommand[0] = true;
                        UserUtils.addMoney(user, 1);
                    } else {
                        command.sendTranslatedMessage("Sorry, this command is currently disabled and will be re-enabled soon.", channel, user);
                        ranCommand[0] = true;
                    }
                }
            });
        }
        if (!ranCommand[0]) {
            if (!prefix.equalsIgnoreCase("/")) {
                pass(event, "/");
            }
        }
    } catch (Throwable ex) {
        if (ex instanceof PermissionException) {
            event.getAuthor().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("I don't have permission to " + "send a message in this channel, please tell a server administrator").queue());
        } else {
            new BotException(ex);
        }
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) GuildModel(tk.ardentbot.rethink.models.GuildModel) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) UserUtils(tk.ardentbot.utils.discord.UserUtils) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser) Database.r(tk.ardentbot.rethink.Database.r) HashMap(java.util.HashMap) ChatterBotSession(com.google.code.chatterbotapi.ChatterBotSession) BotException(tk.ardentbot.core.misc.logging.BotException) Shard(tk.ardentbot.main.Shard) RolePermission(tk.ardentbot.rethink.models.RolePermission) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Unirest(com.mashape.unirest.http.Unirest) Permission(net.dv8tion.jda.core.Permission) Database.connection(tk.ardentbot.rethink.Database.connection) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) StringEscapeUtils(org.apache.commons.lang3.StringEscapeUtils) Ardent(tk.ardentbot.main.Ardent) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) GuildModel(tk.ardentbot.rethink.models.GuildModel) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) EntityGuild(tk.ardentbot.utils.rpg.EntityGuild) BotException(tk.ardentbot.core.misc.logging.BotException) RolePermission(tk.ardentbot.rethink.models.RolePermission) RestrictedUser(tk.ardentbot.utils.models.RestrictedUser)

Example 8 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent in project RoleBotPlus by LeshDev.

the class VerifyEvent method onMessageReceived.

public void onMessageReceived(MessageReceivedEvent e) {
    vRole = e.getJDA().getRoleById(401772846050967572L);
    EmbedBuilder eB = new EmbedBuilder();
    Message msg = e.getMessage();
    if (msg.getContentRaw().startsWith(lib.prefix + "VerifyEvent") && !msg.getMember().getRoles().contains(vRole)) {
        e.getGuild().getController().addSingleRoleToMember(msg.getMember(), vRole).queue();
        eB.addField("Vielen Dank fürs verifizieren", msg.getMember().getEffectiveName() + " hat sich für mehr Commands verifiziert", true);
        eB.setColor(Green.g500);
        eB.setFooter("RoleBot+ / More infos: !help / Made by Lesh", null);
        Main.jLog.info("Added VERIFIED Role to " + e.getMember().getEffectiveName());
        e.getMessage().delete().queueAfter(1, TimeUnit.MILLISECONDS);
        e.getChannel().sendMessage(eB.build()).queue(msge -> msge.delete().queueAfter(20, TimeUnit.SECONDS));
    } else if (msg.getContentRaw().startsWith(lib.prefix + "VerifyEvent") && msg.getMember().getRoles().contains(vRole)) {
        eB.addField("Du bist schon verifiziert", "Es ist dir leider nicht möglich deine Verifizierung aufzuheben. Frage einen Mod/Admin für mehr Infos", true);
        eB.setColor(Red.r500);
        eB.setFooter("RoleBot+ - More infos: !help - Made by Lesh", null);
        Main.jLog.info("Blocked VERIFIED Role to " + e.getMember().getEffectiveName());
        e.getMessage().delete().queueAfter(1, TimeUnit.MILLISECONDS);
        e.getChannel().sendMessage(eB.build()).queue(msge -> msge.delete().queueAfter(20, TimeUnit.SECONDS));
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) TimeUnit(java.util.concurrent.TimeUnit) Main(de.lesh.rolebotplus.Main) Green(me.lesh.material.Green) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) de.lesh.rolebotplus.utils.lib(de.lesh.rolebotplus.utils.lib) ListenerAdapter(net.dv8tion.jda.core.hooks.ListenerAdapter) Red(me.lesh.material.Red) Message(net.dv8tion.jda.core.entities.Message) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Message(net.dv8tion.jda.core.entities.Message)

Example 9 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent in project Saber-Bot by notem.

the class ConfigCommand method action.

@Override
public void action(String head, String[] args, MessageReceivedEvent event) {
    int index = 0;
    String cId = args[index].replaceAll("[^\\d]", "");
    TextChannel scheduleChan = event.getGuild().getTextChannelById(cId);
    index++;
    if (args.length > 1) {
        switch(args[index++].toLowerCase()) {
            case "m":
            case "msg":
            case "message":
                String msgFormat = formatHelper(args[index]);
                Main.getScheduleManager().setAnnounceFormat(scheduleChan.getId(), msgFormat);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "ch":
            case "chan":
            case "channel":
                String chanIdentifier = chanHelper(args[index], event);
                Main.getScheduleManager().setAnnounceChan(scheduleChan.getId(), chanIdentifier);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "em":
            case "end-msg":
            case "end-message":
                String endFormat;
                endFormat = formatHelper(args[index]);
                Main.getScheduleManager().setEndAnnounceFormat(scheduleChan.getId(), endFormat);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "ech":
            case "end-chan":
            case "end-channel":
                String endChanIdentifier;
                switch(args[index].toLowerCase()) {
                    case "reset":
                    case "default":
                    case "null":
                        endChanIdentifier = null;
                        break;
                    default:
                        endChanIdentifier = chanHelper(args[index], event);
                }
                Main.getScheduleManager().setEndAnnounceChan(scheduleChan.getId(), endChanIdentifier);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.ANN, event.getJDA()), event.getChannel(), null);
                break;
            case "z":
            case "zone":
                ZoneId zone = ParsingUtilities.parseZone(args[index]);
                Main.getScheduleManager().setTimeZone(scheduleChan.getId(), zone);
                // correct/reload the event displays
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                    Integer id = document.getInteger("_id");
                    ScheduleEntry se = Main.getEntryManager().getEntry(id);
                    if (se.getStart().isAfter(se.getEnd())) {
                        Main.getDBDriver().getEventCollection().updateOne(eq("_id", id), set("end", Date.from(se.getEnd().plusDays(1).toInstant())));
                    }
                    Main.getEntryManager().reloadEntry(id);
                });
                // disable auto-sync'ing timezone
                Main.getDBDriver().getScheduleCollection().updateOne(eq("_id", scheduleChan.getId()), set("timezone_sync", false));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                break;
            case "cl":
            case "clock":
                Main.getScheduleManager().setClockFormat(scheduleChan.getId(), args[index]);
                // reload the schedule display
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> Main.getEntryManager().reloadEntry((Integer) document.get("_id")));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                break;
            case "s":
            case "sync":
                Credential credential = GoogleAuth.getCredential(event.getAuthor().getId());
                if (credential == null)
                    break;
                Calendar service = GoogleAuth.getCalendarService(credential);
                if (Main.getCalendarConverter().checkValidAddress(args[index], service))
                    Main.getScheduleManager().setAddress(scheduleChan.getId(), args[index]);
                else
                    Main.getScheduleManager().setAddress(scheduleChan.getId(), "off");
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.SYNC, event.getJDA()), event.getChannel(), null);
                break;
            case "t":
            case "time":
                ZonedDateTime syncTime = ZonedDateTime.of(LocalDate.now(), ParsingUtilities.parseTime(args[index]), Main.getScheduleManager().getTimeZone(cId));
                // don't allow times set in the past
                if (syncTime.isBefore(ZonedDateTime.now()))
                    syncTime.plusDays(1);
                Main.getScheduleManager().setSyncTime(cId, Date.from(syncTime.toInstant()));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.SYNC, event.getJDA()), event.getChannel(), null);
                break;
            case "r":
            case "remind":
            case "reminder":
            case "reminders":
                Set<Integer> list = this.reminderHelper(args, index, cId);
                // convert set to a list
                List<Integer> rem = new ArrayList<>(list);
                Main.getScheduleManager().setReminders(cId, rem);
                // for every entry on channel, update
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                    ScheduleEntry se = new ScheduleEntry(document).reloadReminders(Main.getScheduleManager().getReminders(scheduleChan.getId()));
                    Main.getEntryManager().updateEntry(se, false);
                });
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "er":
            case "end-remind":
            case "end-reminder":
            case "end-reminders":
                Set<Integer> list2 = this.reminderHelper(args, index, cId);
                // convert set to a list
                List<Integer> rem2 = new ArrayList<>(list2);
                Main.getScheduleManager().setEndReminders(cId, rem2);
                // for every entry on channel, update
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                    ScheduleEntry se = new ScheduleEntry(document).reloadEndReminders(Main.getScheduleManager().getEndReminders(scheduleChan.getId()));
                    Main.getEntryManager().updateEntry(se, false);
                });
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "rm":
            case "rem-msg":
            case "remind-msg":
            case "remind-message":
                String remindFormat;
                remindFormat = formatHelper(args[index]);
                Main.getScheduleManager().setReminderFormat(scheduleChan.getId(), remindFormat);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "rc":
            case "rem-chan":
            case "remind-chan":
            case "remind-channel":
                String remindChanIdentifier;
                switch(args[index].toLowerCase()) {
                    case "reset":
                    case "default":
                    case "null":
                        remindChanIdentifier = null;
                        break;
                    default:
                        remindChanIdentifier = chanHelper(args[index], event);
                        break;
                }
                Main.getScheduleManager().setReminderChan(scheduleChan.getId(), remindChanIdentifier);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.REM, event.getJDA()), event.getChannel(), null);
                break;
            case "rsvp":
                boolean enabled = Main.getScheduleManager().isRSVPEnabled(cId);
                Map<String, String> options = Main.getScheduleManager().getRSVPOptions(cId);
                Boolean new_enabled = null;
                switch(args[index++].toLowerCase()) {
                    case "add":
                    case "a":
                        String emoji = args[index + 1].trim();
                        if (!EmojiManager.isEmoji(emoji)) {
                            emoji = emoji.replaceAll("[^\\d]", "");
                        }
                        options.put(emoji, args[index].trim());
                        Main.getScheduleManager().setRSVPOptions(cId, options);
                        break;
                    case "remove":
                    case "r":
                        if (options.containsKey(args[index])) {
                            options.remove(args[index]);
                        } else if (options.containsValue(args[index])) {
                            options.values().remove(args[index]);
                        }
                        Main.getScheduleManager().setRSVPOptions(cId, options);
                        break;
                    case "on":
                    case "true":
                        new_enabled = true;
                        break;
                    case "off":
                    case "false":
                        new_enabled = false;
                        break;
                }
                String clearEmoji = Main.getScheduleManager().getRSVPClear(cId);
                // if add or remove option was used, clear the reactions and re-add the new reactions
                if (new_enabled == null) {
                    // for each entry on the schedule
                    Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                        event.getGuild().getTextChannelById(document.getString("channelId")).getMessageById(document.getString("messageId")).complete().clearReactions().queue((message) -> {
                            Map<String, String> map = Main.getScheduleManager().getRSVPOptions(document.getString("channelId"));
                            event.getGuild().getTextChannelById(document.getString("channelId")).getMessageById(document.getString("messageId")).queue(msg -> EntryManager.addRSVPReactions(map, clearEmoji, msg));
                        });
                        Main.getEntryManager().reloadEntry(document.getInteger("_id"));
                    });
                } else // otherwise, if the rsvp setting was changes
                if (enabled != new_enabled) {
                    // set schedule settings
                    Main.getScheduleManager().setRSVPEnable(cId, new_enabled);
                    if (new_enabled) {
                        // for each entry on the schedule
                        Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                            Map<String, String> map = Main.getScheduleManager().getRSVPOptions(document.getString("channelId"));
                            event.getGuild().getTextChannelById(document.getString("channelId")).getMessageById(document.getString("messageId")).queue(msg -> EntryManager.addRSVPReactions(map, clearEmoji, msg));
                            Main.getEntryManager().reloadEntry(document.getInteger("_id"));
                        });
                    } else {
                        // for each entry on the schedule
                        Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> {
                            event.getGuild().getTextChannelById(document.getString("channelId")).getMessageById(document.getString("messageId")).complete().clearReactions().queue();
                            Main.getEntryManager().reloadEntry(document.getInteger("_id"));
                        });
                    }
                }
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "c":
            case "clear":
                String emoji = args[index].trim();
                if (emoji.equalsIgnoreCase("off")) {
                    emoji = "";
                } else if (!EmojiManager.isEmoji(emoji)) {
                    emoji = emoji.replaceAll("[^\\d]", "");
                }
                Main.getScheduleManager().setRSVPClear(cId, emoji);
                String finalEmoji = emoji;
                Map<String, String> rsvpOptions = Main.getScheduleManager().getRSVPOptions(cId);
                Main.getEntryManager().getEntriesFromChannel(cId).forEach(se -> {
                    Message message = se.getMessageObject();
                    message.clearReactions().queue(ignored -> EntryManager.addRSVPReactions(rsvpOptions, finalEmoji, message));
                });
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "co":
            case "confirm":
            case "confirmation":
            case "confirmations":
                boolean confirmation = true;
                switch(args[index].toLowerCase()) {
                    case "no":
                    case "false":
                    case "off":
                        confirmation = false;
                        break;
                }
                Main.getScheduleManager().setRSVPConfirmations(cId, confirmation);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "ex":
            case "exclude":
            case "exclusivity":
                boolean exclusive = true;
                switch(args[index].toLowerCase()) {
                    case "no":
                    case "off":
                    case "false":
                        exclusive = false;
                        break;
                }
                Main.getScheduleManager().setRSVPExclusivity(cId, exclusive);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "log":
            case "logging":
                String loggingChannel = null;
                switch(args[index].toLowerCase()) {
                    case "no":
                    case "off":
                    case "false":
                        break;
                    default:
                        loggingChannel = args[index].replaceAll("[^\\d]", "");
                        break;
                }
                Main.getScheduleManager().setRSVPLoggingChannel(cId, loggingChannel);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.RSVP, event.getJDA()), event.getChannel(), null);
                break;
            case "st":
            case "style":
                String style = args[index].toLowerCase();
                if (style.equals("full"))
                    Main.getScheduleManager().setStyle(cId, style);
                else if (style.equals("narrow"))
                    Main.getScheduleManager().setStyle(cId, style);
                // for each entry on the schedule
                Main.getDBDriver().getEventCollection().find(eq("channelId", scheduleChan.getId())).forEach((Consumer<? super Document>) document -> Main.getEntryManager().reloadEntry(document.getInteger("_id")));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                break;
            case "l":
            case "len":
            case "length":
                Main.getScheduleManager().setSyncLength(cId, Integer.parseInt(args[index]));
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.SYNC, event.getJDA()), event.getChannel(), null);
                break;
            case "so":
            case "sort":
                int sortType;
                switch(args[index]) {
                    case "on":
                    case "asc":
                    case "ascending":
                        sortType = 1;
                        break;
                    case "desc":
                    case "descending":
                        sortType = 2;
                        break;
                    default:
                        sortType = 0;
                        break;
                }
                Main.getScheduleManager().setAutoSort(cId, sortType);
                MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.MISC, event.getJDA()), event.getChannel(), null);
                // now sort the schedule
                if (sortType == 1)
                    Main.getScheduleManager().sortSchedule(cId, false);
                if (sortType == 2)
                    Main.getScheduleManager().sortSchedule(cId, true);
                break;
        }
    } else // print out all settings
    {
        MessageUtilities.sendMsg(this.genMsgStr(cId, Mode.FULL, event.getJDA()), event.getChannel(), null);
    }
}
Also used : Document(org.bson.Document) Command(ws.nmathe.saber.commands.Command) java.util(java.util) CommandInfo(ws.nmathe.saber.commands.CommandInfo) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Updates.set(com.mongodb.client.model.Updates.set) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) GoogleAuth(ws.nmathe.saber.core.google.GoogleAuth) Consumer(java.util.function.Consumer) EmojiManager(com.vdurmont.emoji.EmojiManager) java.time(java.time) ChronoUnit(java.time.temporal.ChronoUnit) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) EntryManager(ws.nmathe.saber.core.schedule.EntryManager) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) JDA(net.dv8tion.jda.core.JDA) Filters.eq(com.mongodb.client.model.Filters.eq) Credential(com.google.api.client.auth.oauth2.Credential) Calendar(com.google.api.services.calendar.Calendar) Main(ws.nmathe.saber.Main) VerifyUtilities(ws.nmathe.saber.utils.VerifyUtilities) ParsingUtilities(ws.nmathe.saber.utils.ParsingUtilities) Credential(com.google.api.client.auth.oauth2.Credential) Calendar(com.google.api.services.calendar.Calendar) Document(org.bson.Document) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Consumer(java.util.function.Consumer)

Example 10 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent in project Rubicon by Rubicon-Bot.

the class MusicManager method handleTrackChoose.

public static void handleTrackChoose(MessageReceivedEvent event) {
    List<MusicSearchResult> storage = musicChoose.stream().filter(musicSearchResult -> musicSearchResult.getUser() == event.getAuthor()).collect(Collectors.toList());
    if (storage.size() == 0) {
        return;
    }
    String response = event.getMessage().getContentDisplay();
    if (!StringUtil.isNumeric(response)) {
        return;
    }
    int ans = Integer.parseInt(response);
    if (ans < 1 || ans > 5) {
        return;
    }
    ans--;
    AudioTrack track = storage.get(0).getTrack(ans);
    storage.get(0).getMusicManager().getScheduler().queue(track);
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.setAuthor("Added a new song to queue", track.getInfo().uri, null);
    embedBuilder.addField("Title", track.getInfo().title, true);
    embedBuilder.addField("Author", track.getInfo().author, true);
    embedBuilder.addField("Duration", (track.getInfo().isStream) ? "Stream" : getTimestamp(track.getDuration()), false);
    embedBuilder.setColor(Colors.COLOR_PRIMARY);
    event.getTextChannel().sendMessage(embedBuilder.build()).queue();
    storage.get(0).getMessage().delete().queue();
    musicChoose.remove(storage.get(0));
    event.getMessage().delete().queue();
}
Also used : AudioPlayer(com.sedmelluq.discord.lavaplayer.player.AudioPlayer) EmbedUtil(fun.rubicon.util.EmbedUtil) java.util(java.util) CommandManager(fun.rubicon.command.CommandManager) Lyrics(org.jmusixmatch.entity.lyrics.Lyrics) GuildMusicSQL(fun.rubicon.sql.GuildMusicSQL) AudioPlaylist(com.sedmelluq.discord.lavaplayer.track.AudioPlaylist) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) Permission(net.dv8tion.jda.core.Permission) HttpAudioSourceManager(com.sedmelluq.discord.lavaplayer.source.http.HttpAudioSourceManager) YoutubeAudioSourceManager(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager) AudioTrackInfo(com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo) FriendlyException(com.sedmelluq.discord.lavaplayer.tools.FriendlyException) MusixMatch(org.jmusixmatch.MusixMatch) RubiconBot(fun.rubicon.RubiconBot) DefaultAudioPlayerManager(com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager) MusixMatchException(org.jmusixmatch.MusixMatchException) Track(org.jmusixmatch.entity.track.Track) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) fun.rubicon.util(fun.rubicon.util) Collectors(java.util.stream.Collectors) AudioLoadResultHandler(com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) AudioPlayerManager(com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager) UserMusicSQL(fun.rubicon.sql.UserMusicSQL) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Aggregations

MessageReceivedEvent (net.dv8tion.jda.core.events.message.MessageReceivedEvent)14 ArrayList (java.util.ArrayList)4 Consumer (java.util.function.Consumer)4 Message (net.dv8tion.jda.core.entities.Message)4 Main (ws.nmathe.saber.Main)4 Command (ws.nmathe.saber.commands.Command)4 CommandInfo (ws.nmathe.saber.commands.CommandInfo)4 MessageUtilities (ws.nmathe.saber.utils.MessageUtilities)4 Filters.eq (com.mongodb.client.model.Filters.eq)3 java.util (java.util)3 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)3 net.dv8tion.jda.core.entities (net.dv8tion.jda.core.entities)3 MessageChannel (net.dv8tion.jda.core.entities.MessageChannel)3 PublicCommand (com.greatmancode.legendarybot.api.commands.PublicCommand)2 ZeroArgsCommand (com.greatmancode.legendarybot.api.commands.ZeroArgsCommand)2 LegendaryBotPlugin (com.greatmancode.legendarybot.api.plugin.LegendaryBotPlugin)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 Permission (net.dv8tion.jda.core.Permission)2 Channel (net.dv8tion.jda.core.entities.Channel)2