Search in sources :

Example 1 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent 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 2 with MessageReceivedEvent

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

the class ListCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    int index = 0;
    Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
    ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());
    String titleUrl = se.getTitleUrl() == null ? "https://nnmathe.ws/saber" : se.getTitleUrl();
    String title = se.getTitle() + " [" + ParsingUtilities.intToEncodedID(entryId) + "]";
    String content = "";
    List<String> userFilters = new ArrayList<>();
    List<String> roleFilters = new ArrayList<>();
    boolean filterByType = false;
    Set<String> typeFilters = new HashSet<>();
    boolean mobileFlag = false;
    boolean IdFlag = false;
    for (; index < args.length; index++) {
        if (args[index].equalsIgnoreCase("mobile") || args[index].equalsIgnoreCase("m")) {
            mobileFlag = true;
            continue;
        }
        if (args[index].equalsIgnoreCase("id") || args[index].equalsIgnoreCase("i")) {
            IdFlag = true;
            continue;
        }
        String filterType = args[index].split(":")[0].toLowerCase().trim();
        String filterValue = args[index].split(":")[1].trim();
        switch(filterType.toLowerCase()) {
            case "r":
            case "role":
                roleFilters.add(filterValue.replace("<@&", "").replace(">", ""));
                break;
            case "u":
            case "user":
                userFilters.add(filterValue.replace("<@", "").replace(">", ""));
                break;
            case "t":
            case "type":
                filterByType = true;
                typeFilters.add(filterValue);
                break;
        }
    }
    // maximum number of characters before creating a new message
    int lengthCap = 1900;
    // maximum number of lines until new message, in mobile mode
    int mobileLineCap = 25;
    Set<String> uniqueMembers = new HashSet<>();
    Map<String, String> options = Main.getScheduleManager().getRSVPOptions(se.getChannelId());
    for (String type : options.values()) {
        if (!filterByType || typeFilters.contains(type)) {
            content += "**\"" + type + "\"\n======================**\n";
            List<String> members = se.getRsvpMembersOfType(type);
            for (String id : members) {
                // if the message is nearing maximum length, or if in mobile mode and the max lines have been reached
                if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
                    // build and send the embedded message object
                    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
                    MessageUtilities.sendMsg(message, event.getChannel(), null);
                    // clear the content sting
                    content = "*continued. . .* \n";
                }
                if (id.matches("\\d+")) {
                    // cases in which the id is most likely a valid discord user's ID
                    Member member = event.getGuild().getMemberById(id);
                    if (// if the user is still a member of the guild, add to the list
                    member != null) {
                        uniqueMembers.add(member.getUser().getId());
                        content += this.getNameDisplay(mobileFlag, IdFlag, member);
                    } else // otherwise, remove the member from the event and update
                    {
                        se.getRsvpMembersOfType(type).remove(id);
                        Main.getEntryManager().updateEntry(se, false);
                    }
                } else {
                    // handles cases in which a non-discord user was added by an admin
                    uniqueMembers.add(id);
                    content += "*" + id + "*\n";
                }
            }
        }
        content += "\n";
    }
    if (!filterByType || typeFilters.contains("no-input")) {
        // generate a list of all members of the guild who pass the filter and map to their ID
        List<String> noInput = event.getGuild().getMembers().stream().filter(member -> checkMember(member, userFilters, roleFilters)).map(member -> member.getUser().getId()).collect(Collectors.toList());
        for (String type : options.values()) {
            noInput.removeAll(se.getRsvpMembersOfType(type));
        }
        content += "**No input\n======================\n**";
        if (!filterByType & noInput.size() > 10) {
            content += " Too many users to show: " + noInput.size() + " users with no rsvp\n";
        } else
            for (String id : noInput) {
                if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
                    // build and send the embedded message object
                    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
                    MessageUtilities.sendMsg(message, event.getChannel(), null);
                    // clear the content sting
                    content = "*continued. . .* \n";
                }
                Member member = event.getGuild().getMemberById(id);
                content += this.getNameDisplay(mobileFlag, IdFlag, member);
            }
    }
    String footer = uniqueMembers.size() + " unique member(s) appear in this search";
    // build and send the embedded message object
    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).setFooter(footer, null).build()).build();
    MessageUtilities.sendMsg(message, event.getChannel(), null);
}
Also used : Command(ws.nmathe.saber.commands.Command) java.util(java.util) CommandInfo(ws.nmathe.saber.commands.CommandInfo) Member(net.dv8tion.jda.core.entities.Member) Logging(ws.nmathe.saber.utils.Logging) StringUtils(org.apache.commons.lang3.StringUtils) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Collectors(java.util.stream.Collectors) Message(net.dv8tion.jda.core.entities.Message) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Main(ws.nmathe.saber.Main) VerifyUtilities(ws.nmathe.saber.utils.VerifyUtilities) ParsingUtilities(ws.nmathe.saber.utils.ParsingUtilities) Message(net.dv8tion.jda.core.entities.Message) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) Member(net.dv8tion.jda.core.entities.Member)

Example 3 with MessageReceivedEvent

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

the class InitCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    String body;
    if (args.length > 0) {
        boolean isAChannel = false;
        TextChannel chan = null;
        String chanId = null;
        try {
            chanId = args[0].replaceAll("[^\\d]", "");
            chan = event.getGuild().getTextChannelById(chanId);
            if (chan != null)
                isAChannel = true;
        } catch (Exception ignored) {
        }
        if (// use the argument as the new channel's name
        !isAChannel) {
            String chanTitle = args[0].replaceAll("[^A-Za-z0-9_ \\-]", "").replaceAll("[ ]", "_");
            Main.getScheduleManager().createSchedule(event.getGuild().getId(), chanTitle);
            body = "A new schedule channel named **" + chanTitle.toLowerCase() + "** has been created!\n" + "You can now use the create command to create events on that schedule, or the sync command to sync " + "that schedule to a Google Calendar.";
        } else // convert the channel to a schedule
        {
            if (Main.getScheduleManager().isASchedule(chan.getId())) {
                // clear the channel of events
                TextChannel finalChan = chan;
                Main.getDBDriver().getEventCollection().find(eq("channelId", chan.getId())).forEach((Consumer<? super Document>) document -> {
                    String msgId = document.getString("messageId");
                    finalChan.deleteMessageById(msgId).complete();
                    Main.getEntryManager().removeEntry(document.getInteger("_id"));
                });
                body = "The schedule <#" + chanId + "> has been cleared!";
            } else {
                // create a new schedule
                Main.getScheduleManager().createSchedule(chan);
                body = "The channel <#" + chanId + "> has been converted to a schedule channel!\n" + "You can now use the create command to create events on that schedule, or the sync " + "command to sync that schedule to a Google Calendar.";
            }
        }
    } else // create a new schedule using the default name
    {
        Main.getScheduleManager().createSchedule(event.getGuild().getId(), null);
        body = "A new schedule channel named **new_schedule** has been created!\n" + "You can now use the create command to create events on that schedule, or the sync command" + " to sync that schedule to a Google Calendar.";
    }
    MessageUtilities.sendMsg(body, event.getChannel(), null);
}
Also used : Document(org.bson.Document) Command(ws.nmathe.saber.commands.Command) CommandInfo(ws.nmathe.saber.commands.CommandInfo) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Logging(ws.nmathe.saber.utils.Logging) Channel(net.dv8tion.jda.core.entities.Channel) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) List(java.util.List) Permission(net.dv8tion.jda.core.Permission) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) TextChannel(net.dv8tion.jda.core.entities.TextChannel)

Example 4 with MessageReceivedEvent

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

the class PurgeCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    TextChannel channel = event.getGuild().getJDA().getTextChannelById(args[0].replaceAll("[^\\d]", ""));
    // number of messages to remove
    Integer[] count = { 100 };
    // ID of bot to check messages against
    String botId = event.getJDA().getSelfUser().getId();
    processing.put(event.getGuild().getId(), channel.getId());
    channel.getIterableHistory().stream().filter(message -> message.getAuthor().getId().equals(botId) && (count[0]-- > 0)).forEach((message -> {
        message.getChannel().sendTyping().queue();
        // sleep for half a second before continuing
        try {
            Thread.sleep(500);
        } catch (InterruptedException ignored) {
        }
        Bson query = eq("messageId", message.getId());
        if (Main.getDBDriver().getEventCollection().count(query) == 0) {
            MessageUtilities.deleteMsg(message);
        }
    }));
    processing.remove(event.getGuild().getId(), channel.getId());
    // send success message
    String content = "Finished purging old message.";
    MessageUtilities.sendMsg(content, event.getTextChannel(), null);
}
Also used : Bson(org.bson.conversions.Bson) Command(ws.nmathe.saber.commands.Command) CommandInfo(ws.nmathe.saber.commands.CommandInfo) RateLimiter(ws.nmathe.saber.core.RateLimiter) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Map(java.util.Map) MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Filters.eq(com.mongodb.client.model.Filters.eq) Channel(net.dv8tion.jda.core.entities.Channel) Main(ws.nmathe.saber.Main) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Bson(org.bson.conversions.Bson)

Example 5 with MessageReceivedEvent

use of net.dv8tion.jda.core.events.message.MessageReceivedEvent in project commands by aikar.

the class JDACommandManager method getCommandPrefix.

@Override
public String getCommandPrefix(CommandIssuer issuer) {
    MessageReceivedEvent event = ((JDACommandEvent) issuer).getEvent();
    CommandConfig commandConfig = getCommandConfig(event);
    List<String> prefixes = commandConfig.getCommandPrefixes();
    return prefixes.isEmpty() ? "" : prefixes.get(0);
}
Also used : MessageReceivedEvent(net.dv8tion.jda.core.events.message.MessageReceivedEvent)

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