Search in sources :

Example 6 with TextChannel

use of org.javacord.api.entity.channel.TextChannel in project Javacord by BtoBastian.

the class MessageReactionRemoveAllHandler method handle.

@Override
public void handle(JsonNode packet) {
    long messageId = packet.get("message_id").asLong();
    Optional<Message> message = api.getCachedMessageById(messageId);
    message.ifPresent(msg -> ((MessageImpl) msg).removeAllReactionsFromCache());
    long channelId = packet.get("channel_id").asLong();
    TextChannel channel = api.getTextChannelById(channelId).orElse(null);
    if (channel == null) {
        if (packet.hasNonNull("guild_id")) {
            // we don't know anything about the channel as it is part of a server and not cached
            LoggerUtil.logMissingChannel(logger, channelId);
            return;
        }
        // channel is a private channel:
        channel = PrivateChannelImpl.dispatchPrivateChannelCreateEvent(api, new PrivateChannelImpl(api, channelId, null, null));
    }
    ReactionRemoveAllEvent event = new ReactionRemoveAllEventImpl(api, messageId, channel);
    Optional<Server> optionalServer = channel.asServerChannel().map(ServerChannel::getServer);
    api.getEventDispatcher().dispatchReactionRemoveAllEvent(optionalServer.map(DispatchQueueSelector.class::cast).orElse(api), messageId, optionalServer.orElse(null), channel, event);
}
Also used : TextChannel(org.javacord.api.entity.channel.TextChannel) Message(org.javacord.api.entity.message.Message) Server(org.javacord.api.entity.server.Server) ReactionRemoveAllEventImpl(org.javacord.core.event.message.reaction.ReactionRemoveAllEventImpl) ReactionRemoveAllEvent(org.javacord.api.event.message.reaction.ReactionRemoveAllEvent) PrivateChannelImpl(org.javacord.core.entity.channel.PrivateChannelImpl) ServerChannel(org.javacord.api.entity.channel.ServerChannel) DispatchQueueSelector(org.javacord.core.util.event.DispatchQueueSelector)

Example 7 with TextChannel

use of org.javacord.api.entity.channel.TextChannel in project Javacord by BtoBastian.

the class TypingStartHandler method handle.

@Override
public void handle(JsonNode packet) {
    long userId = packet.get("user_id").asLong();
    long channelId = packet.get("channel_id").asLong();
    TextChannel channel = api.getTextChannelById(channelId).orElse(null);
    ServerImpl server = null;
    if (packet.hasNonNull("guild_id")) {
        long serverId = packet.get("guild_id").asLong();
        server = (ServerImpl) api.getPossiblyUnreadyServerById(serverId).orElseThrow(AssertionError::new);
    }
    MemberImpl member = null;
    if (packet.hasNonNull("member") && server != null) {
        member = new MemberImpl(api, server, packet.get("member"), null);
    }
    if (channel != null) {
        UserStartTypingEvent event = new UserStartTypingEventImpl(channel, userId, member);
        api.getEventDispatcher().dispatchUserStartTypingEvent(server != null ? server : api, server, channel, userId, event);
    }
}
Also used : UserStartTypingEventImpl(org.javacord.core.event.user.UserStartTypingEventImpl) TextChannel(org.javacord.api.entity.channel.TextChannel) ServerImpl(org.javacord.core.entity.server.ServerImpl) MemberImpl(org.javacord.core.entity.user.MemberImpl) UserStartTypingEvent(org.javacord.api.event.user.UserStartTypingEvent)

Example 8 with TextChannel

use of org.javacord.api.entity.channel.TextChannel in project Javacord by BtoBastian.

the class MessageSetImpl method getMessagesAround.

/**
 * Gets up to a given amount of messages in the given channel around a given message in any channel.
 * The given message will be part of the result in addition to the messages around if it was sent in the given
 * channel and does not count towards the limit.
 * Half of the messages will be older than the given message and half of the messages will be newer.
 * If there aren't enough older or newer messages, the actual amount of messages will be less than the given limit.
 * It's also not guaranteed to be perfectly balanced.
 *
 * @param channel The channel of the messages.
 * @param limit The limit of messages to get.
 * @param around Get messages around the message with this id.
 * @return The messages.
 * @see #getMessagesAroundAsStream(TextChannel, long)
 */
public static CompletableFuture<MessageSet> getMessagesAround(TextChannel channel, int limit, long around) {
    CompletableFuture<MessageSet> future = new CompletableFuture<>();
    channel.getApi().getThreadPool().getExecutorService().submit(() -> {
        try {
            // calculate the half limit.
            int halfLimit = limit / 2;
            // get the newer half
            MessageSet newerMessages = getMessagesAfter(channel, halfLimit, around).join();
            // get the older half + around message
            MessageSet olderMessages = getMessagesBefore(channel, halfLimit + 1, around + 1).join();
            // for example because the around message was from a different channel
            if (olderMessages.getNewestMessage().map(DiscordEntity::getId).map(id -> id != around).orElse(false)) {
                olderMessages = olderMessages.tailSet(olderMessages.getOldestMessage().orElseThrow(AssertionError::new), false);
            }
            // combine the messages into one collection
            Collection<Message> messages = Stream.of(olderMessages, newerMessages).flatMap(Collection::stream).collect(toList());
            // we are done
            future.complete(new MessageSetImpl(messages));
        } catch (Throwable t) {
            future.completeExceptionally(t);
        }
    });
    return future;
}
Also used : MessageSet(org.javacord.api.entity.message.MessageSet) MessageSet(org.javacord.api.entity.message.MessageSet) Arrays(java.util.Arrays) Spliterators(java.util.Spliterators) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) RestMethod(org.javacord.core.util.rest.RestMethod) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) DiscordEntity(org.javacord.api.entity.DiscordEntity) RestRequest(org.javacord.core.util.rest.RestRequest) TextChannel(org.javacord.api.entity.channel.TextChannel) JsonNode(com.fasterxml.jackson.databind.JsonNode) StreamSupport(java.util.stream.StreamSupport) Iterator(java.util.Iterator) Predicate(java.util.function.Predicate) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) NavigableSet(java.util.NavigableSet) DiscordApiImpl(org.javacord.core.DiscordApiImpl) Message(org.javacord.api.entity.message.Message) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Comparator(java.util.Comparator) Collections(java.util.Collections) Spliterator(java.util.Spliterator) CompletableFuture(java.util.concurrent.CompletableFuture) Message(org.javacord.api.entity.message.Message) RestEndpoint(org.javacord.core.util.rest.RestEndpoint) DiscordEntity(org.javacord.api.entity.DiscordEntity)

Example 9 with TextChannel

use of org.javacord.api.entity.channel.TextChannel in project Javacord by BtoBastian.

the class ChannelPinsUpdateHandler method handle.

@Override
public void handle(JsonNode packet) {
    long channelId = packet.get("channel_id").asLong();
    Optional<TextChannel> optionalChannel = api.getTextChannelById(channelId);
    if (optionalChannel.isPresent()) {
        TextChannel channel = optionalChannel.get();
        Instant lastPinTimestamp = packet.hasNonNull("last_pin_timestamp") ? OffsetDateTime.parse(packet.get("last_pin_timestamp").asText()).toInstant() : null;
        ChannelPinsUpdateEvent event = new ChannelPinsUpdateEventImpl(channel, lastPinTimestamp);
        Optional<Server> optionalServer = channel.asServerChannel().map(ServerChannel::getServer);
        api.getEventDispatcher().dispatchChannelPinsUpdateEvent(optionalServer.map(DispatchQueueSelector.class::cast).orElse(api), optionalServer.orElse(null), channel, event);
    } else {
        LoggerUtil.logMissingChannel(logger, channelId);
    }
}
Also used : TextChannel(org.javacord.api.entity.channel.TextChannel) Server(org.javacord.api.entity.server.Server) Instant(java.time.Instant) ChannelPinsUpdateEvent(org.javacord.api.event.message.ChannelPinsUpdateEvent) ChannelPinsUpdateEventImpl(org.javacord.core.event.message.ChannelPinsUpdateEventImpl) ServerChannel(org.javacord.api.entity.channel.ServerChannel) DispatchQueueSelector(org.javacord.core.util.event.DispatchQueueSelector)

Example 10 with TextChannel

use of org.javacord.api.entity.channel.TextChannel in project Javacord by BtoBastian.

the class MessageUpdateHandler method handle.

@Override
public void handle(JsonNode packet) {
    long messageId = packet.get("id").asLong();
    long channelId = packet.get("channel_id").asLong();
    Optional<TextChannel> optionalChannel = api.getTextChannelById(channelId);
    if (!optionalChannel.isPresent()) {
        LoggerUtil.logMissingChannel(logger, channelId);
        return;
    }
    TextChannel channel = optionalChannel.get();
    Optional<MessageImpl> message = api.getCachedMessageById(messageId).map(msg -> (MessageImpl) msg);
    message.ifPresent(msg -> {
        boolean newPinnedFlag = packet.hasNonNull("pinned") ? packet.get("pinned").asBoolean() : msg.isPinned();
        boolean oldPinnedFlag = msg.isPinned();
        if (newPinnedFlag != oldPinnedFlag) {
            msg.setPinned(newPinnedFlag);
            if (newPinnedFlag) {
                CachedMessagePinEvent event = new CachedMessagePinEventImpl(msg);
                Optional<Server> optionalServer = msg.getChannel().asServerChannel().map(ServerChannel::getServer);
                api.getEventDispatcher().dispatchCachedMessagePinEvent(optionalServer.map(DispatchQueueSelector.class::cast).orElse(api), msg, optionalServer.orElse(null), msg.getChannel(), event);
            } else {
                CachedMessageUnpinEvent event = new CachedMessageUnpinEventImpl(msg);
                Optional<Server> optionalServer = msg.getChannel().asServerChannel().map(ServerChannel::getServer);
                api.getEventDispatcher().dispatchCachedMessageUnpinEvent(optionalServer.map(DispatchQueueSelector.class::cast).orElse(api), msg, optionalServer.orElse(null), msg.getChannel(), event);
            }
        }
    });
    MessageEditEvent editEvent = null;
    if (packet.has("edited_timestamp") && !packet.get("edited_timestamp").isNull()) {
        message.ifPresent(msg -> {
            msg.setLastEditTime(OffsetDateTime.parse(packet.get("edited_timestamp").asText()).toInstant());
            msg.setMentionsEveryone(packet.get("mention_everyone").asBoolean());
        });
        long editTimestamp = OffsetDateTime.parse(packet.get("edited_timestamp").asText()).toInstant().toEpochMilli();
        long lastKnownEditTimestamp = lastKnownEditTimestamps.getOrDefault(messageId, 0L);
        lastKnownEditTimestamps.put(messageId, editTimestamp);
        boolean isMostLikelyAnEdit = true;
        long offset = api.getTimeOffset() == null ? 0 : api.getTimeOffset();
        if (editTimestamp == lastKnownEditTimestamp) {
            isMostLikelyAnEdit = false;
        } else if (System.currentTimeMillis() + offset - editTimestamp > 5000) {
            isMostLikelyAnEdit = false;
        }
        String oldContent = message.map(Message::getContent).orElse(null);
        List<Embed> oldEmbeds = message.map(Message::getEmbeds).orElse(null);
        String newContent = null;
        if (packet.has("content")) {
            newContent = packet.get("content").asText();
            String finalNewContent = newContent;
            message.ifPresent(msg -> msg.setContent(finalNewContent));
        }
        List<Embed> newEmbeds = null;
        if (packet.has("embeds")) {
            newEmbeds = new ArrayList<>();
            for (JsonNode embedJson : packet.get("embeds")) {
                Embed embed = new EmbedImpl(embedJson);
                newEmbeds.add(embed);
            }
            List<Embed> finalNewEmbeds = newEmbeds;
            message.ifPresent(msg -> msg.setEmbeds(finalNewEmbeds));
        }
        if (oldContent != null && newContent != null && !oldContent.equals(newContent)) {
            // If the old content doesn't match the new content it's for sure an edit
            isMostLikelyAnEdit = true;
        }
        if (oldEmbeds != null && newEmbeds != null) {
            if (newEmbeds.size() != oldEmbeds.size()) {
                isMostLikelyAnEdit = true;
            } else {
                for (int i = 0; i < newEmbeds.size(); i++) {
                    if (!((EmbedBuilderDelegateImpl) newEmbeds.get(i).toBuilder().getDelegate()).toJsonNode().toString().equals(((EmbedBuilderDelegateImpl) oldEmbeds.get(i).toBuilder().getDelegate()).toJsonNode().toString())) {
                        isMostLikelyAnEdit = true;
                    }
                }
            }
        }
        if (isMostLikelyAnEdit) {
            editEvent = new MessageEditEventImpl(api, messageId, channel, newContent, newEmbeds, oldContent, oldEmbeds);
        }
    }
    if (editEvent != null) {
        dispatchEditEvent(editEvent);
    }
}
Also used : CachedMessagePinEventImpl(org.javacord.core.event.message.CachedMessagePinEventImpl) Server(org.javacord.api.entity.server.Server) CachedMessageUnpinEvent(org.javacord.api.event.message.CachedMessageUnpinEvent) Embed(org.javacord.api.entity.message.embed.Embed) CachedMessageUnpinEventImpl(org.javacord.core.event.message.CachedMessageUnpinEventImpl) MessageEditEventImpl(org.javacord.core.event.message.MessageEditEventImpl) CachedMessagePinEvent(org.javacord.api.event.message.CachedMessagePinEvent) JsonNode(com.fasterxml.jackson.databind.JsonNode) EmbedImpl(org.javacord.core.entity.message.embed.EmbedImpl) ServerChannel(org.javacord.api.entity.channel.ServerChannel) DispatchQueueSelector(org.javacord.core.util.event.DispatchQueueSelector) MessageEditEvent(org.javacord.api.event.message.MessageEditEvent) TextChannel(org.javacord.api.entity.channel.TextChannel) MessageImpl(org.javacord.core.entity.message.MessageImpl)

Aggregations

TextChannel (org.javacord.api.entity.channel.TextChannel)12 Server (org.javacord.api.entity.server.Server)7 DispatchQueueSelector (org.javacord.core.util.event.DispatchQueueSelector)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 ServerChannel (org.javacord.api.entity.channel.ServerChannel)6 Message (org.javacord.api.entity.message.Message)5 ServerImpl (org.javacord.core.entity.server.ServerImpl)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 List (java.util.List)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Emoji (org.javacord.api.entity.emoji.Emoji)2 ComponentType (org.javacord.api.entity.message.component.ComponentType)2 DiscordApiImpl (org.javacord.core.DiscordApiImpl)2 Member (org.javacord.core.entity.user.Member)2 MemberImpl (org.javacord.core.entity.user.MemberImpl)2 RestEndpoint (org.javacord.core.util.rest.RestEndpoint)2 RestMethod (org.javacord.core.util.rest.RestMethod)2