Search in sources :

Example 56 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class MessageHistory method retrieveFuture.

/**
 * Retrieves messages from Discord that were sent more recently than the most recently sent message in
 * MessageHistory's history cache ({@link #getRetrievedHistory()}).
 * Use case for this method is for getting more recent messages after jumping to a specific point in history
 * using something like {@link MessageChannel#getHistoryAround(String, int)}.
 * <br>This method works in the same way as {@link #retrievePast(int)}'s Additional Retrieval mode.
 * <p>
 * <b>Note:</b> This method can only be used after {@link net.dv8tion.jda.api.entities.Message Messages} have already
 * been retrieved from Discord.
 * <p>
 * Possible {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} include:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
 *     <br>Can occur if retrieving in Additional Mode and the Message being used as the marker for the last retrieved
 *         Message was deleted. Currently, to fix this, you need to create a new
 *         {@link net.dv8tion.jda.api.entities.MessageHistory MessageHistory} instance.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost access to the Channel,
 *         typically due to the account being removed from the {@link net.dv8tion.jda.api.entities.Guild Guild}.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>Can occur if the request for history retrieval was executed <i>after</i> JDA lost the
 *         {@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY} permission.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *     <br>The send request was attempted after the channel was deleted.</li>
 * </ul>
 *
 * @param  amount
 *         The amount of {@link net.dv8tion.jda.api.entities.Message Messages} to retrieve.
 *
 * @throws java.lang.IllegalArgumentException
 *         The the {@code amount} is less than {@code 1} or greater than {@code 100}.
 * @throws java.lang.IllegalStateException
 *         If no messages have been retrieved by this MessageHistory.
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} -
 *         Type: {@link java.util.List List}{@literal <}{@link net.dv8tion.jda.api.entities.Message Message}{@literal >}
 *         <br>Retrieved Messages are placed in a List and provided in order of most recent to oldest with most recent
 *         starting at index 0. If the list is empty, there were no more messages left to retrieve.
 */
@Nonnull
@CheckReturnValue
public RestAction<List<Message>> retrieveFuture(int amount) {
    if (amount > 100 || amount < 1)
        throw new IllegalArgumentException("Message retrieval limit is between 1 and 100 messages. No more, no less. Limit provided: " + amount);
    if (history.isEmpty())
        throw new IllegalStateException("No messages have been retrieved yet, so there is no message to act as a marker to retrieve more recent messages based on.");
    Route.CompiledRoute route = Route.Messages.GET_MESSAGE_HISTORY.compile(channel.getId()).withQueryParams("limit", Integer.toString(amount), "after", String.valueOf(history.firstKey()));
    JDAImpl jda = (JDAImpl) getJDA();
    return new RestActionImpl<>(jda, route, (response, request) -> {
        EntityBuilder builder = jda.getEntityBuilder();
        LinkedList<Message> messages = new LinkedList<>();
        DataArray historyJson = response.getArray();
        for (int i = 0; i < historyJson.length(); i++) {
            try {
                messages.add(builder.createMessageWithChannel(historyJson.getObject(i), channel, false));
            } catch (Exception e) {
                LOG.warn("Encountered exception when retrieving messages ", e);
            }
        }
        for (Iterator<Message> it = messages.descendingIterator(); it.hasNext(); ) {
            Message m = it.next();
            history.put(0, m.getIdLong(), m);
        }
        return messages;
    });
}
Also used : JDAImpl(net.dv8tion.jda.internal.JDAImpl) EntityBuilder(net.dv8tion.jda.internal.entities.EntityBuilder) DataArray(net.dv8tion.jda.api.utils.data.DataArray) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) MissingAccessException(net.dv8tion.jda.api.exceptions.MissingAccessException) RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) Route(net.dv8tion.jda.internal.requests.Route) CheckReturnValue(javax.annotation.CheckReturnValue) Nonnull(javax.annotation.Nonnull)

Example 57 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class OptionData method fromData.

/**
 * Parses the provided serialization back into an OptionData instance.
 * <br>This is the reverse function for {@link #toData()}.
 *
 * @param  json
 *         The serialized {@link DataObject} representing the option
 *
 * @throws net.dv8tion.jda.api.exceptions.ParsingException
 *         If the serialized object is missing required fields
 * @throws IllegalArgumentException
 *         If any of the values are failing the respective checks such as length
 *
 * @return The parsed OptionData instance, which can be further configured through setters
 */
@Nonnull
public static OptionData fromData(@Nonnull DataObject json) {
    String name = json.getString("name");
    String description = json.getString("description");
    OptionType type = OptionType.fromKey(json.getInt("type"));
    OptionData option = new OptionData(type, name, description);
    option.setRequired(json.getBoolean("required"));
    option.setAutoComplete(json.getBoolean("autocomplete"));
    if (type == OptionType.INTEGER || type == OptionType.NUMBER) {
        if (!json.isNull("min_value")) {
            if (json.isType("min_value", DataType.INT))
                option.setMinValue(json.getLong("min_value"));
            else if (json.isType("min_value", DataType.FLOAT))
                option.setMinValue(json.getDouble("min_value"));
        }
        if (!json.isNull("max_value")) {
            if (json.isType("max_value", DataType.INT))
                option.setMaxValue(json.getLong("max_value"));
            else if (json.isType("max_value", DataType.FLOAT))
                option.setMaxValue(json.getDouble("max_value"));
        }
    }
    if (type == OptionType.CHANNEL) {
        option.setChannelTypes(json.optArray("channel_types").map(it -> it.stream(DataArray::getInt).map(ChannelType::fromId).collect(Collectors.toSet())).orElse(Collections.emptySet()));
    }
    json.optArray("choices").ifPresent(choices1 -> choices1.stream(DataArray::getObject).forEach(o -> {
        if (o.isType("value", DataType.FLOAT))
            option.addChoice(o.getString("name"), o.getDouble("value"));
        else if (o.isType("value", DataType.INT))
            option.addChoice(o.getString("name"), o.getLong("value"));
        else
            option.addChoice(o.getString("name"), o.get("value").toString());
    }));
    return option;
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Checks(net.dv8tion.jda.internal.utils.Checks) java.util(java.util) SerializableData(net.dv8tion.jda.api.utils.data.SerializableData) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) DataType(net.dv8tion.jda.api.utils.data.DataType) Command(net.dv8tion.jda.api.interactions.commands.Command) Collectors(java.util.stream.Collectors) ChannelType(net.dv8tion.jda.api.entities.ChannelType) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ChannelType(net.dv8tion.jda.api.entities.ChannelType) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Nonnull(javax.annotation.Nonnull)

Example 58 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class SlashCommandData method fromData.

/**
 * Parses the provided serialization back into a SlashCommandData instance.
 * <br>This is the reverse function for {@link SlashCommandData#toData()}.
 *
 * @param  object
 *         The serialized {@link DataObject} representing the command
 *
 * @throws net.dv8tion.jda.api.exceptions.ParsingException
 *         If the serialized object is missing required fields
 * @throws IllegalArgumentException
 *         If any of the values are failing the respective checks such as length
 *
 * @return The parsed SlashCommandData instance, which can be further configured through setters
 *
 * @see    CommandData#fromData(DataObject)
 * @see    Commands#fromList(Collection)
 */
@Nonnull
static SlashCommandData fromData(@Nonnull DataObject object) {
    Checks.notNull(object, "DataObject");
    String name = object.getString("name");
    Command.Type commandType = Command.Type.fromId(object.getInt("type", 1));
    if (commandType != Command.Type.SLASH)
        throw new IllegalArgumentException("Cannot convert command of type " + commandType + " to SlashCommandData!");
    String description = object.getString("description");
    DataArray options = object.optArray("options").orElseGet(DataArray::empty);
    CommandDataImpl command = new CommandDataImpl(name, description);
    options.stream(DataArray::getObject).forEach(opt -> {
        OptionType type = OptionType.fromKey(opt.getInt("type"));
        switch(type) {
            case SUB_COMMAND:
                command.addSubcommands(SubcommandData.fromData(opt));
                break;
            case SUB_COMMAND_GROUP:
                command.addSubcommandGroups(SubcommandGroupData.fromData(opt));
                break;
            default:
                command.addOptions(OptionData.fromData(opt));
        }
    });
    return command;
}
Also used : Command(net.dv8tion.jda.api.interactions.commands.Command) CommandDataImpl(net.dv8tion.jda.internal.interactions.CommandDataImpl) DataArray(net.dv8tion.jda.api.utils.data.DataArray) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Nonnull(javax.annotation.Nonnull)

Example 59 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class WebSocketClient method onDispatch.

protected void onDispatch(DataObject raw) {
    String type = raw.getString("t");
    long responseTotal = api.getResponseTotal();
    if (!raw.isType("d", DataType.OBJECT)) {
        // Needs special handling due to content of "d" being an array
        if (type.equals("PRESENCES_REPLACE")) {
            final DataArray payload = raw.getArray("d");
            final List<DataObject> converted = convertPresencesReplace(responseTotal, payload);
            final SocketHandler handler = getHandler("PRESENCE_UPDATE");
            LOG.trace("{} -> {}", type, payload);
            for (DataObject o : converted) {
                handler.handle(responseTotal, o);
                // Send raw event after cache has been updated - including comment
                if (api.isRawEvents())
                    api.handleEvent(new RawGatewayEvent(api, responseTotal, o));
            }
        } else {
            LOG.debug("Received event with unhandled body type JSON: {}", raw);
        }
        return;
    }
    DataObject content = raw.getObject("d");
    LOG.trace("{} -> {}", type, content);
    JDAImpl jda = (JDAImpl) getJDA();
    try {
        switch(type) {
            // INIT types
            case "READY":
                reconnectTimeoutS = 2;
                api.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
                processingReady = true;
                handleIdentifyRateLimit = false;
                // first handle the ready payload before applying the session id
                // this prevents a possible race condition with the cache of the guild setup controller
                // otherwise the audio connection requests that are currently pending might be removed in the process
                handlers.get("READY").handle(responseTotal, raw);
                sessionId = content.getString("session_id");
                break;
            case "RESUMED":
                reconnectTimeoutS = 2;
                sentAuthInfo = true;
                if (!processingReady) {
                    initiating = false;
                    ready();
                } else {
                    LOG.debug("Resumed while still processing initial ready");
                    jda.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
                }
                break;
            default:
                long guildId = content.getLong("guild_id", 0L);
                if (api.isUnavailable(guildId) && !type.equals("GUILD_CREATE") && !type.equals("GUILD_DELETE")) {
                    LOG.debug("Ignoring {} for unavailable guild with id {}. JSON: {}", type, guildId, content);
                    break;
                }
                SocketHandler handler = handlers.get(type);
                if (handler != null)
                    handler.handle(responseTotal, raw);
                else
                    LOG.debug("Unrecognized event:\n{}", raw);
        }
        // Send raw event after cache has been updated
        if (api.isRawEvents())
            api.handleEvent(new RawGatewayEvent(api, responseTotal, raw));
    } catch (ParsingException ex) {
        LOG.warn("Got an unexpected Json-parse error. Please redirect the following message to the devs:\n\tJDA {}\n\t{}\n\t{} -> {}", JDAInfo.VERSION, ex.getMessage(), type, content, ex);
    } catch (Exception ex) {
        LOG.error("Got an unexpected error. Please redirect the following message to the devs:\n\tJDA {}\n\t{} -> {}", JDAInfo.VERSION, type, content, ex);
    }
    if (responseTotal % EventCache.TIMEOUT_AMOUNT == 0)
        jda.getEventCache().timeout(responseTotal);
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) ParsingException(net.dv8tion.jda.api.exceptions.ParsingException) JDAImpl(net.dv8tion.jda.internal.JDAImpl) DataArray(net.dv8tion.jda.api.utils.data.DataArray) ParsingException(net.dv8tion.jda.api.exceptions.ParsingException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) DataFormatException(java.util.zip.DataFormatException) IOException(java.io.IOException)

Example 60 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class AutoCompleteCallbackActionImpl method toData.

@Override
protected DataObject toData() {
    DataObject data = DataObject.empty();
    DataArray array = DataArray.empty();
    choices.forEach(choice -> {
        DataObject json = DataObject.empty().put("name", choice.getName());
        switch(type) {
            case INTEGER:
                json.put("value", choice.getAsLong());
                break;
            case NUMBER:
                json.put("value", choice.getAsDouble());
                break;
            case STRING:
                json.put("value", choice.getAsString());
                break;
        }
        array.add(json);
    });
    data.put("choices", array);
    return DataObject.empty().put("type", ResponseType.COMMAND_AUTOCOMPLETE_CHOICES.getRaw()).put("data", data);
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Aggregations

DataArray (net.dv8tion.jda.api.utils.data.DataArray)67 DataObject (net.dv8tion.jda.api.utils.data.DataObject)40 Nonnull (javax.annotation.Nonnull)21 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)14 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)10 JDAImpl (net.dv8tion.jda.internal.JDAImpl)9 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)8 ArrayList (java.util.ArrayList)8 Route (net.dv8tion.jda.internal.requests.Route)8 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)7 Collectors (java.util.stream.Collectors)6 CheckReturnValue (javax.annotation.CheckReturnValue)6 TemplateRole (net.dv8tion.jda.api.entities.templates.TemplateRole)5 ParsingException (net.dv8tion.jda.api.exceptions.ParsingException)5 GuildImpl (net.dv8tion.jda.internal.entities.GuildImpl)5 Bean (at.xirado.bean.Bean)4 java.util (java.util)4 OnlineStatus (net.dv8tion.jda.api.OnlineStatus)4 Template (net.dv8tion.jda.api.entities.templates.Template)4 CacheView (net.dv8tion.jda.api.utils.cache.CacheView)4