Search in sources :

Example 11 with Message

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

the class TestCommand 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++;
    String format = Main.getScheduleManager().getStartAnnounceFormat(entry.getChannelId());
    if (args.length == 2) {
        switch(args[index].toLowerCase()) {
            case "e":
            case "end":
                format = Main.getScheduleManager().getEndAnnounceFormat(entry.getChannelId());
                break;
            case "r":
            case "remind":
                format = Main.getScheduleManager().getReminderFormat(entry.getChannelId());
                break;
        }
    }
    String remindMsg = ParsingUtilities.processText(format, entry, true);
    MessageUtilities.sendMsg(remindMsg, event.getChannel(), null);
}
Also used : ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Message(net.dv8tion.jda.api.entities.Message)

Example 12 with Message

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

the class ScheduleManager method sortSchedule.

/**
 * Reorders the schedule so that entries are displayed by start datetime ascending order in
 * the discord schedule channel
 * @param cId schedule ID
 * @param reverseOrder (boolean) whether or not to reverse the sort order
 */
public void sortSchedule(String cId, boolean reverseOrder) {
    if (this.getScheduleSize(cId) > MAX_SIZE_TO_SYNC)
        return;
    if (this.isLocked(cId))
        return;
    // lock the channel
    this.lock(cId);
    // always unlock the schedule at finish regardless of success or failure
    try {
        // identify which shard is responsible for the schedule
        Document doc = Main.getDBDriver().getScheduleCollection().find(eq("_id", cId)).projection(fields(include("guildId"))).first();
        JDA jda = Main.getShardManager().getJDA(doc.getString("guildId"));
        // find the message channel and send the 'is typing' while processing
        MessageChannel chan = jda.getTextChannelById(cId);
        chan.sendTyping().queue();
        int sortOrder = 1;
        if (reverseOrder)
            sortOrder = -1;
        LinkedList<ScheduleEntry> unsortedEntries = new LinkedList<>();
        Main.getDBDriver().getEventCollection().find(eq("channelId", cId)).sort(new Document("start", sortOrder)).forEach((Consumer<? super Document>) document -> unsortedEntries.add(new ScheduleEntry(document)));
        // selection sort the entries by timestamp
        while (!unsortedEntries.isEmpty()) {
            // continue to send 'is typing'
            chan.sendTyping().queue();
            ScheduleEntry top = unsortedEntries.pop();
            ScheduleEntry min = top;
            for (ScheduleEntry cur : unsortedEntries) {
                Message minMsg = min.getMessageObject();
                Message topMsg = cur.getMessageObject();
                if (minMsg != null && topMsg != null) {
                    OffsetDateTime a = minMsg.getTimeCreated();
                    OffsetDateTime b = topMsg.getTimeCreated();
                    if (a.isAfter(b)) {
                        min = cur;
                    }
                }
            }
            // swap messages and update db
            if (!(min == top)) {
                Message tmp = top.getMessageObject();
                top.setMessageObject(min.getMessageObject());
                Main.getDBDriver().getEventCollection().updateOne(eq("_id", top.getId()), new Document("$set", new Document("messageId", min.getMessageObject().getId())));
                min.setMessageObject(tmp);
                Main.getDBDriver().getEventCollection().updateOne(eq("_id", min.getId()), new Document("$set", new Document("messageId", tmp.getId())));
            }
            // reload display
            top.reloadDisplay();
        }
    } catch (PermissionException e) {
        String m = e.getMessage() + ": Channel ID " + cId;
        Logging.warn(this.getClass(), m);
    } catch (Exception e) {
        Logging.exception(this.getClass(), e);
    } finally {
        // always unlock
        this.unlock(cId);
    }
}
Also used : Message(net.dv8tion.jda.api.entities.Message) Document(org.bson.Document) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Projections.fields(com.mongodb.client.model.Projections.fields) Permission(net.dv8tion.jda.api.Permission) Logging(ws.nmathe.saber.utils.Logging) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Updates.set(com.mongodb.client.model.Updates.set) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Projections.include(com.mongodb.client.model.Projections.include) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) java.time(java.time) Guild(net.dv8tion.jda.api.entities.Guild) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Filters.eq(com.mongodb.client.model.Filters.eq) Main(ws.nmathe.saber.Main) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) Message(net.dv8tion.jda.api.entities.Message) JDA(net.dv8tion.jda.api.JDA) Document(org.bson.Document) PermissionException(net.dv8tion.jda.api.exceptions.PermissionException) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel)

Example 13 with Message

use of net.dv8tion.jda.api.entities.Message in project MantaroBot by Mantaro.

the class Poll method createPoll.

private void createPoll(Context ctx, Message message, I18nContext languageContext) {
    runningPoll = ReactionOperations.create(message, TimeUnit.MILLISECONDS.toSeconds(timeout), new ReactionOperation() {

        @Override
        public int add(MessageReactionAddEvent e) {
            // always return false anyway lul
            return Operation.IGNORED;
        }

        @Override
        public void onExpire() {
            if (getChannel() == null)
                return;
            var user = ctx.getAuthor();
            var embedBuilder = new EmbedBuilder().setTitle(languageContext.get("commands.poll.result_header")).setDescription(String.format(languageContext.get("commands.poll.result_screen"), user.getName(), name)).setFooter(languageContext.get("commands.poll.thank_note"), null);
            var react = new AtomicInteger(0);
            var counter = new AtomicInteger(0);
            getChannel().retrieveMessageById(message.getIdLong()).queue(message -> {
                var votes = message.getReactions().stream().filter(r -> react.getAndIncrement() <= options.length).map(r -> String.format(languageContext.get("commands.poll.vote_results"), r.getCount() - 1, options[counter.getAndIncrement()])).collect(Collectors.joining("\n"));
                embedBuilder.addField(languageContext.get("commands.poll.results"), "```diff\n" + votes + "```", false);
                getChannel().sendMessageEmbeds(embedBuilder.build()).queue();
            });
            getRunningPolls().remove(getChannel().getId());
        }

        @Override
        public void onCancel() {
            getChannel().sendMessageFormat(languageContext.get("commands.poll.cancelled"), EmoteReference.CORRECT).queue();
            onExpire();
        }
    }, reactions(options.length));
}
Also used : ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.core.ReactionOperation) Message(net.dv8tion.jda.api.entities.Message) Color(java.awt.Color) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Permission(net.dv8tion.jda.api.Permission) Utils(net.kodehawa.mantarobot.utils.Utils) HashMap(java.util.HashMap) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) Collectors(java.util.stream.Collectors) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) Lobby(net.kodehawa.mantarobot.commands.interaction.Lobby) TimeUnit(java.util.concurrent.TimeUnit) Future(java.util.concurrent.Future) Stream(java.util.stream.Stream) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Map(java.util.Map) MantaroData(net.kodehawa.mantarobot.data.MantaroData) ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.core.ReactionOperation) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 14 with Message

use of net.dv8tion.jda.api.entities.Message in project c0debaseBot by Biospheere.

the class ClearCommand method execute.

@Override
public void execute(final String[] args, final Message message) {
    if (args.length == 0) {
        final EmbedBuilder embedBuilder = getEmbed(message.getMember());
        embedBuilder.appendDescription("!clear <Amount>");
        message.getTextChannel().sendMessage(embedBuilder.build()).queue();
    } else {
        int i = 0;
        try {
            i = Integer.valueOf(args[0]);
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
        final MessageHistory history = new MessageHistory(message.getTextChannel());
        final List<Message> messages = history.retrievePast(i + 1).complete();
        message.getTextChannel().deleteMessages(messages).queue();
        final EmbedBuilder embedBuilder = DiscordUtils.getDefaultEmbed(message.getMember());
        embedBuilder.setColor(message.getGuild().getSelfMember().getColor());
        embedBuilder.appendDescription("Es wurden **" + (i) + "** Nachrichten gelöscht");
        message.getTextChannel().sendMessage(embedBuilder.build()).queue();
    }
}
Also used : MessageHistory(net.dv8tion.jda.api.entities.MessageHistory) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Message(net.dv8tion.jda.api.entities.Message)

Example 15 with Message

use of net.dv8tion.jda.api.entities.Message in project lavaplayer by sedmelluq.

the class MusicScheduler method updateTrackBox.

private void updateTrackBox(boolean newMessage) {
    AudioTrack track = player.getPlayingTrack();
    if (track == null || newMessage) {
        Message message = boxMessage.getAndSet(null);
        if (message != null) {
            message.delete();
        }
    }
    if (track != null) {
        Message message = boxMessage.get();
        String box = TrackBoxBuilder.buildTrackBox(80, track, player.isPaused(), player.getVolume());
        if (message != null) {
            message.editMessage(box).queue();
        } else {
            if (creatingBoxMessage.compareAndSet(false, true)) {
                messageDispatcher.sendMessage(box, created -> {
                    boxMessage.set(created);
                    creatingBoxMessage.set(false);
                }, error -> {
                    creatingBoxMessage.set(false);
                });
            }
        }
    }
}
Also used : Message(net.dv8tion.jda.api.entities.Message) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Aggregations

Message (net.dv8tion.jda.api.entities.Message)18 Collectors (java.util.stream.Collectors)7 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)7 java.util (java.util)5 ScheduleEntry (ws.nmathe.saber.core.schedule.ScheduleEntry)5 JDA (net.dv8tion.jda.api.JDA)4 Permission (net.dv8tion.jda.api.Permission)4 Role (net.dv8tion.jda.api.entities.Role)4 TextChannel (net.dv8tion.jda.api.entities.TextChannel)4 java.time (java.time)3 TimeUnit (java.util.concurrent.TimeUnit)3 Consumer (java.util.function.Consumer)3 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)3 Guild (net.dv8tion.jda.api.entities.Guild)3 Member (net.dv8tion.jda.api.entities.Member)3 MantaroData (net.kodehawa.mantarobot.data.MantaroData)3 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)3 Document (org.bson.Document)3 Main (ws.nmathe.saber.Main)3 Logging (ws.nmathe.saber.utils.Logging)3