net.dv8tion.jda.api.requests.RestAction Java Examples

The following examples show how to use net.dv8tion.jda.api.requests.RestAction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<List<Invite>> retrieveInvites()
{
    if (!this.getSelfMember().hasPermission(Permission.MANAGE_SERVER))
        throw new InsufficientPermissionException(this, Permission.MANAGE_SERVER);

    final Route.CompiledRoute route = Route.Invites.GET_GUILD_INVITES.compile(getId());

    return new RestActionImpl<>(getJDA(), route, (response, request) ->
    {
        EntityBuilder entityBuilder = api.getEntityBuilder();
        DataArray array = response.getArray();
        List<Invite> invites = new ArrayList<>(array.length());
        for (int i = 0; i < array.length(); i++)
            invites.add(entityBuilder.createInvite(array.getObject(i)));
        return Collections.unmodifiableList(invites);
    });
}
 
Example #2
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<EnumSet<Region>> retrieveRegions(boolean includeDeprecated)
{
    Route.CompiledRoute route = Route.Guilds.GET_VOICE_REGIONS.compile(getId());
    return new RestActionImpl<>(getJDA(), route, (response, request) ->
    {
        EnumSet<Region> set = EnumSet.noneOf(Region.class);
        DataArray arr = response.getArray();
        for (int i = 0; i < arr.length(); i++)
        {
            DataObject obj = arr.getObject(i);
            if (!includeDeprecated && obj.getBoolean("deprecated"))
                continue;
            String id = obj.getString("id", "");
            Region region = Region.fromKey(id);
            if (region != Region.UNKNOWN)
                set.add(region);
        }
        return set;
    });
}
 
Example #3
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<Member> retrieveMemberById(long id, boolean update)
{
    JDAImpl jda = getJDA();
    if (id == jda.getSelfUser().getIdLong())
        return new CompletedRestAction<>(jda, getSelfMember());

    return new DeferredRestAction<>(jda, Member.class,
            () -> getMember(id, update, jda),
            () -> { // otherwise we need to update the member with a REST request first to get the nickname/roles
                Route.CompiledRoute route = Route.Guilds.GET_MEMBER.compile(getId(), Long.toUnsignedString(id));
                return new RestActionImpl<>(jda, route, (resp, req) -> {
                    MemberImpl member = jda.getEntityBuilder().createMember(this, resp.getObject());
                    jda.getEntityBuilder().updateMemberCache(member);
                    return member;
                });
            });
}
 
Example #4
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<MetaData> retrieveMetaData()
{
    Route.CompiledRoute route = Route.Guilds.GET_GUILD.compile(getId());
    route = route.withQueryParams("with_counts", "true");
    return new RestActionImpl<>(getJDA(), route, (response, request) -> {
        DataObject json = response.getObject();
        int memberLimit = json.getInt("max_members", 0);
        int presenceLimit = json.getInt("max_presences", 5000);
        this.maxMembers = memberLimit;
        this.maxPresences = presenceLimit;
        int approxMembers = json.getInt("approximate_member_count", this.memberCount);
        int approxPresence = json.getInt("approximate_presence_count", 0);
        return new MetaData(memberLimit, presenceLimit, approxPresence, approxMembers);
    });
}
 
Example #5
Source File: JDAImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<User> retrieveUserById(long id, boolean update)
{
    if (id == getSelfUser().getIdLong())
        return new CompletedRestAction<>(this, getSelfUser());

    AccountTypeException.check(getAccountType(), AccountType.BOT);
    return new DeferredRestAction<>(this, User.class,
            () -> !update || isIntent(GatewayIntent.GUILD_MEMBERS) || isIntent(GatewayIntent.GUILD_PRESENCES) ? getUserById(id) : null,
            () -> {
                Route.CompiledRoute route = Route.Users.GET_USER.compile(Long.toUnsignedString(id));
                return new RestActionImpl<>(this, route,
                        (response, request) -> getEntityBuilder().createFakeUser(response.getObject()));
            });
}
 
Example #6
Source File: ShardManager.java    From JDA with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to retrieve a {@link net.dv8tion.jda.api.entities.User User} object based on the provided id.
 * <br>This first calls {@link #getUserById(long)}, and if the return is {@code null} then a request
 * is made to the Discord servers.
 *
 * <p>The returned {@link net.dv8tion.jda.api.requests.RestAction RestAction} can encounter the following Discord errors:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_USER ErrorResponse.UNKNOWN_USER}
 *     <br>Occurs when the provided id does not refer to a {@link net.dv8tion.jda.api.entities.User User}
 *     known by Discord. Typically occurs when developers provide an incomplete id (cut short).</li>
 * </ul>
 *
 * @param  id
 *         The id of the requested {@link net.dv8tion.jda.api.entities.User User}.
 *
 * @throws java.lang.IllegalStateException
 *         If there isn't any active shards.
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: {@link net.dv8tion.jda.api.entities.User User}
 *         <br>On request, gets the User with id matching provided id from Discord.
 */
@Nonnull
@CheckReturnValue
default RestAction<User> retrieveUserById(long id)
{
    JDA api = null;
    for (JDA shard : getShardCache())
    {
        api = shard;
        EnumSet<GatewayIntent> intents = shard.getGatewayIntents();
        User user = shard.getUserById(id);
        boolean isUpdated = intents.contains(GatewayIntent.GUILD_PRESENCES) || intents.contains(GatewayIntent.GUILD_MEMBERS);
        if (user != null && isUpdated)
            return new CompletedRestAction<>(shard, user);
    }

    if (api == null)
        throw new IllegalStateException("no shards active");

    JDAImpl jda = (JDAImpl) api;
    Route.CompiledRoute route = Route.Users.GET_USER.compile(Long.toUnsignedString(id));
    return new RestActionImpl<>(jda, route, (response, request) -> jda.getEntityBuilder().createFakeUser(response.getObject()));
}
 
Example #7
Source File: JDAImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<PrivateChannel> openPrivateChannelById(long userId)
{
    if (selfUser != null && userId == selfUser.getIdLong())
        throw new UnsupportedOperationException("Cannot open private channel with yourself!");
    return new DeferredRestAction<>(this, PrivateChannel.class, () -> {
        User user = getUserById(userId);
        if (user instanceof UserImpl)
            return ((UserImpl) user).getPrivateChannel();
        return null;
    }, () -> {
        Route.CompiledRoute route = Route.Self.CREATE_PRIVATE_CHANNEL.compile();
        DataObject body = DataObject.empty().put("recipient_id", userId);
        return new RestActionImpl<>(this, route, body,
            (response, request) -> getEntityBuilder().createPrivateChannel(response.getObject()));
    });
}
 
Example #8
Source File: GuildImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public RestAction<Ban> retrieveBanById(@Nonnull String userId)
{
    if (!getSelfMember().hasPermission(Permission.BAN_MEMBERS))
        throw new InsufficientPermissionException(this, Permission.BAN_MEMBERS);

    Checks.isSnowflake(userId, "User ID");

    Route.CompiledRoute route = Route.Guilds.GET_BAN.compile(getId(), userId);
    return new RestActionImpl<>(getJDA(), route, (response, request) ->
    {

        EntityBuilder builder = api.getEntityBuilder();
        DataObject bannedObj = response.getObject();
        DataObject user = bannedObj.getObject("user");
        return new Ban(builder.createFakeUser(user), bannedObj.getString("reason", null));
    });
}
 
Example #9
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> clearReactionsById(@Nonnull String messageId, @Nonnull Emote emote)
{
    Checks.notNull(emote, "Emote");
    return clearReactionsById(messageId, emote.getName() + ":" + emote.getId());
}
 
Example #10
Source File: DeferredRestAction.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public void queue(Consumer<? super T> success, Consumer<? super Throwable> failure)
{
    Consumer<? super T> finalSuccess;
    if (success != null)
        finalSuccess = success;
    else
        finalSuccess = RestAction.getDefaultSuccess();

    if (type == null)
    {
        BooleanSupplier checks = this.isAction;
        if (checks != null && checks.getAsBoolean())
            getAction().queue(success, failure);
        else
            finalSuccess.accept(null);
        return;
    }

    T value = valueSupplier.get();
    if (value == null)
    {
        getAction().queue(success, failure);
    }
    else
    {
        finalSuccess.accept(value);
    }
}
 
Example #11
Source File: AbstractMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> addReaction(@Nonnull String unicode)
{
    unsupported();
    return null;
}
 
Example #12
Source File: MessageServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public <T> void sendTempMessageSilent(Function<T, RestAction<Message>> action, T embed, int sec) {
    sendMessageSilentQueue(action, embed, message -> {
        JDA jda = message.getJDA();
        long messageId = message.getIdLong();
        long channelId = message.getChannel().getIdLong();
        ChannelType type = message.getChannelType();
        scheduler.schedule(() -> {
            MessageChannel channel = DiscordUtils.getChannel(jda, type, channelId);
            if (channel != null) {
                channel.retrieveMessageById(messageId).queue(this::delete);
            }
        }, new DateTime().plusSeconds(sec).toDate());
    });
}
 
Example #13
Source File: RestActionOperator.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<O> deadline(long timestamp)
{
    this.deadline = timestamp;
    action.deadline(timestamp);
    return this;
}
 
Example #14
Source File: GuildImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@Deprecated
public RestAction<String> retrieveVanityUrl()
{
    if (!getSelfMember().hasPermission(Permission.MANAGE_SERVER))
        throw new InsufficientPermissionException(this, Permission.MANAGE_SERVER);
    if (!getFeatures().contains("VANITY_URL"))
        throw new IllegalStateException("This guild doesn't have a vanity url");

    Route.CompiledRoute route = Route.Guilds.GET_VANITY_URL.compile(getId());

    return new RestActionImpl<>(getJDA(), route,
        (response, request) -> response.getObject().getString("code"));
}
 
Example #15
Source File: DelayRestAction.java    From JDA with Apache License 2.0 5 votes vote down vote up
public DelayRestAction(RestAction<T> action, TimeUnit unit, long delay, ScheduledExecutorService scheduler)
{
    super(action);
    this.unit = unit;
    this.delay = delay;
    this.scheduler = scheduler == null ? action.getJDA().getRateLimitPool() : scheduler;
}
 
Example #16
Source File: JDAImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Webhook> retrieveWebhookById(@Nonnull String webhookId)
{
    Checks.isSnowflake(webhookId, "Webhook ID");

    Route.CompiledRoute route = Route.Webhooks.GET_WEBHOOK.compile(webhookId);

    return new RestActionImpl<>(this, route, (response, request) ->
    {
        DataObject object = response.getObject();
        EntityBuilder builder = getEntityBuilder();
        return builder.createWebhook(object);
    });
}
 
Example #17
Source File: RestActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<T> deadline(long timestamp)
{
    this.deadline = timestamp;
    return this;
}
 
Example #18
Source File: InviteImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public static RestAction<Invite> resolve(final JDA api, final String code, final boolean withCounts)
{
    Checks.notNull(code, "code");
    Checks.notNull(api, "api");

    Route.CompiledRoute route = Route.Invites.GET_INVITE.compile(code);
    
    if (withCounts)
        route = route.withQueryParams("with_counts", "true");

    JDAImpl jda = (JDAImpl) api;
    return new RestActionImpl<>(api, route, (response, request) ->
            jda.getEntityBuilder().createInvite(response.getObject()));
}
 
Example #19
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> pinMessageById(@Nonnull String messageId)
{
    checkPermission(Permission.MESSAGE_READ, "You cannot pin a message in a channel you can't access. (MESSAGE_READ)");
    checkPermission(Permission.MESSAGE_MANAGE, "You need MESSAGE_MANAGE to pin or unpin messages.");

    //Call MessageChannel's default method
    return TextChannel.super.pinMessageById(messageId);
}
 
Example #20
Source File: AbstractMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> addReaction(@Nonnull Emote emote)
{
    unsupported();
    return null;
}
 
Example #21
Source File: AbstractMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> removeReaction(@Nonnull Emote emote, @Nonnull User user)
{
    unsupported();
    return null;
}
 
Example #22
Source File: FlatMapErrorRestAction.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public T complete(boolean shouldQueue) throws RateLimitedException
{
    try
    {
        return action.complete(shouldQueue);
    }
    catch (Throwable error)
    {
        try
        {
            if (check.test(error))
            {
                RestAction<? extends T> then = map.apply(error);
                if (then == null)
                    throw new IllegalStateException("FlatMapError operand is null", error);
                return then.complete(shouldQueue);
            }
        }
        catch (Throwable e)
        {
            if (e instanceof IllegalStateException && e.getCause() == error)
                throw (IllegalStateException) e;
            else if (e instanceof RateLimitedException)
                throw (RateLimitedException) Helpers.appendCause(e, error);
            else
                fail(Helpers.appendCause(e, error));
        }
        fail(error);
    }
    throw new AssertionError("Unreachable");
}
 
Example #23
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> unpinMessageById(@Nonnull String messageId)
{
    checkPermission(Permission.MESSAGE_READ, "You cannot unpin a message in a channel you can't access. (MESSAGE_READ)");
    checkPermission(Permission.MESSAGE_MANAGE, "You need MESSAGE_MANAGE to pin or unpin messages.");

    //Call MessageChannel's default method
    return TextChannel.super.unpinMessageById(messageId);
}
 
Example #24
Source File: JDAImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<ApplicationInfo> retrieveApplicationInfo()
{
    AccountTypeException.check(getAccountType(), AccountType.BOT);
    Route.CompiledRoute route = Route.Applications.GET_BOT_APPLICATION.compile();
    return new RestActionImpl<>(this, route, (response, request) ->
    {
        ApplicationInfo info = getEntityBuilder().createApplicationInfo(response.getObject());
        this.clientId = info.getId();
        return info;
    });
}
 
Example #25
Source File: ReceivedMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> clearReactions(@Nonnull String unicode)
{
    if (!isFromGuild())
        throw new IllegalStateException("Cannot clear reactions from a message in a Group or PrivateChannel.");
    return getTextChannel().clearReactionsById(getId(), unicode);
}
 
Example #26
Source File: AbstractMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> clearReactions()
{
    unsupported();
    return null;
}
 
Example #27
Source File: RestActionOperator.java    From JDA with Apache License 2.0 5 votes vote down vote up
protected Consumer<? super Throwable> contextWrap(@Nullable Consumer<? super Throwable> callback)
{
    if (callback instanceof ContextException.ContextConsumer)
        return callback;
    else if (RestAction.isPassContext())
        return ContextException.here(callback == null ? RestAction.getDefaultFailure() : callback);
    return callback;
}
 
Example #28
Source File: AbstractMessage.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Void> removeReaction(@Nonnull String unicode, @Nonnull User user)
{
    unsupported();
    return null;
}
 
Example #29
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public RestAction<Message> retrieveMessageById(@Nonnull String messageId)
{
    checkPermission(Permission.MESSAGE_READ);
    checkPermission(Permission.MESSAGE_HISTORY);

    //Call MessageChannel's default method
    return TextChannel.super.retrieveMessageById(messageId);
}
 
Example #30
Source File: FlatMapRestAction.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public void queue(@Nullable Consumer<? super O> success, @Nullable Consumer<? super Throwable> failure)
{
    Consumer<? super Throwable> contextFailure = contextWrap(failure);
    action.queue((result) -> {
        if (condition != null && !condition.test(result))
            return;
        RestAction<O> then = supply(result);
        if (then == null)
            doFailure(contextFailure, new IllegalStateException("FlatMap operand is null"));
        else
            then.queue(success, contextFailure);
    }, contextFailure);
}