net.dv8tion.jda.api.AccountType Java Examples

The following examples show how to use net.dv8tion.jda.api.AccountType. 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: LavalinkTest.java    From Lavalink-Client with MIT License 6 votes vote down vote up
@BeforeAll
static void setUp() throws Exception {
    JDABuilder jdaBuilder = new JDABuilder(AccountType.BOT)
            .setToken(getSystemProperty(PROPERTY_TOKEN));

    JDA selfId = jdaBuilder.build();
    lavalink = new JdaLavalink(selfId.retrieveApplicationInfo().submit().get(30, TimeUnit.SECONDS).getId(), 1, integer -> jda);
    selfId.shutdown();

    lavalink.addNode(new URI("ws://localhost:5555"), "youshallnotpass");

    jda = jdaBuilder
            .addEventListeners(lavalink)
            .build();

    Thread.sleep(2000);

    assertTrue(lavalink.getNodes().get(0).isAvailable(), "Could not connect to lavalink server");
}
 
Example #2
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 #3
Source File: DiscordService.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
private void startPlayerBot(final String token) {
	this.builder = new JDABuilder(AccountType.BOT);
	this.builder.setEventManager(new AnnotatedEventManager());
	this.builder.addEventListeners(this);
	this.builder.setToken(token);
	try {
		this.jda = this.builder.build();
	} catch (final LoginException a) {
		a.printStackTrace();
	}
}
 
Example #4
Source File: GuildImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public boolean checkVerification()
{
    if (getJDA().getAccountType() == AccountType.BOT)
        return true;
    if(canSendVerification)
        return true;

    switch (verificationLevel)
    {
        case VERY_HIGH:
            break; // we already checked for a verified phone number
        case HIGH:
            if (ChronoUnit.MINUTES.between(getSelfMember().getTimeJoined(), OffsetDateTime.now()) < 10)
                break;
        case MEDIUM:
            if (ChronoUnit.MINUTES.between(getJDA().getSelfUser().getTimeCreated(), OffsetDateTime.now()) < 5)
                break;
        case LOW:
            if (!getJDA().getSelfUser().isVerified())
                break;
        case NONE:
            canSendVerification = true;
            return true;
        case UNKNOWN:
            return true; // try and let discord decide
    }
    return false;
}
 
Example #5
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 #6
Source File: SessionControllerAdapter.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public ShardedGateway getShardedGateway(@Nonnull JDA api)
{
    AccountTypeException.check(api.getAccountType(), AccountType.BOT);
    return new RestActionImpl<ShardedGateway>(api, Route.Misc.GATEWAY_BOT.compile())
    {
        @Override
        public void handleResponse(Response response, Request<ShardedGateway> request)
        {
            try
            {
                if (response.isOk())
                {
                    DataObject object = response.getObject();

                    String url = object.getString("url");
                    int shards = object.getInt("shards");

                    request.onSuccess(new ShardedGateway(url, shards));
                }
                else if (response.code == 401)
                {
                    api.shutdownNow();
                    throw new LoginException("The provided token is invalid!");
                }
                else
                {
                    request.onFailure(new LoginException("When verifying the authenticity of the provided token, Discord returned an unknown response:\n" +
                            response.toString()));
                }
            }
            catch (Exception e)
            {
                request.onFailure(e);
            }
        }
    }.priority().complete();
}
 
Example #7
Source File: WebSocketClient.java    From JDA with Apache License 2.0 4 votes vote down vote up
protected String getToken()
{
    if (api.getAccountType() == AccountType.BOT)
        return api.getToken().substring("Bot ".length());
    return api.getToken();
}
 
Example #8
Source File: TextChannelImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
@SuppressWarnings("ConstantConditions")
public List<CompletableFuture<Void>> purgeMessagesById(@Nonnull long... messageIds)
{
    if (messageIds == null || messageIds.length == 0)
        return Collections.emptyList();
    if (getJDA().getAccountType() != AccountType.BOT
        || !getGuild().getSelfMember().hasPermission(this, Permission.MESSAGE_MANAGE))
        return TextChannel.super.purgeMessagesById(messageIds);

    // remove duplicates and sort messages
    List<CompletableFuture<Void>> list = new LinkedList<>();
    TreeSet<Long> bulk = new TreeSet<>(Comparator.reverseOrder());
    TreeSet<Long> norm = new TreeSet<>(Comparator.reverseOrder());
    long twoWeeksAgo = TimeUtil.getDiscordTimestamp(System.currentTimeMillis() - (14 * 24 * 60 * 60 * 1000) + 10000);
    for (long messageId : messageIds)
    {
        if (messageId > twoWeeksAgo)
            bulk.add(messageId);
        else
            norm.add(messageId);
    }

    // delete chunks of 100 messages each
    if (!bulk.isEmpty())
    {
        List<String> toDelete = new ArrayList<>(100);
        while (!bulk.isEmpty())
        {
            toDelete.clear();
            for (int i = 0; i < 100 && !bulk.isEmpty(); i++)
                toDelete.add(Long.toUnsignedString(bulk.pollLast()));
            if (toDelete.size() == 1)
                list.add(deleteMessageById(toDelete.get(0)).submit());
            else if (!toDelete.isEmpty())
                list.add(deleteMessages0(toDelete).submit());
        }
    }

    // delete messages too old for bulk delete
    if (!norm.isEmpty())
    {
        for (long message : norm)
            list.add(deleteMessageById(message).submit());
    }
    return list;
}
 
Example #9
Source File: PrivateChannelImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
private void checkBot()
{
    if (getUser().isBot() && getJDA().getAccountType() == AccountType.BOT)
        throw new UnsupportedOperationException("Cannot send a private message between bots.");
}
 
Example #10
Source File: AuthorizationConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
public AccountType getAccountType()
{
    return AccountType.BOT;
}
 
Example #11
Source File: JDAImpl.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public AccountType getAccountType()
{
    return authConfig.getAccountType();
}
 
Example #12
Source File: MessageEmbed.java    From JDA with Apache License 2.0 4 votes vote down vote up
/**
 * Whether this MessageEmbed can be used in a message.
 *
 * <p>Total Character Limits
 * <ul>
 *     <li>Bot: {@value #EMBED_MAX_LENGTH_BOT}</li>
 *     <li>Client: {@value #EMBED_MAX_LENGTH_CLIENT}</li>
 * </ul>
 *
 * @param  type
 *         The {@link net.dv8tion.jda.api.AccountType AccountType} to inspect
 *
 * @throws java.lang.IllegalArgumentException
 *         If the provided AccountType is {@code null} or not supported by this operation
 *
 * @return True, if this MessageEmbed can be used to send messages for this specified AccountType
 *
 * @see    #getLength()
 *
 * @deprecated Use {@link #isSendable()} instead
 */
@Deprecated
@ForRemoval
@DeprecatedSince("4.2.0")
public boolean isSendable(@Nonnull AccountType type)
{
    Checks.notNull(type, "AccountType");
    final int length = getLength();
    if (isEmpty())
        return false;

    switch (type)
    {
        case BOT: return length <= EMBED_MAX_LENGTH_BOT;
        case CLIENT: return length <= EMBED_MAX_LENGTH_CLIENT;
        default: throw new IllegalArgumentException(String.format("Cannot check against AccountType '%s'!", type));
    }
}
 
Example #13
Source File: AccountTypeException.java    From JDA with Apache License 2.0 4 votes vote down vote up
public static void check(AccountType actualType, AccountType requiredType)
{
    if (actualType != requiredType)
        throw new AccountTypeException(requiredType);
}
 
Example #14
Source File: Main.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  new JDABuilder(AccountType.BOT)
      .setToken(System.getProperty("botToken"))
      .addEventListeners(new Main())
      .build();
}
 
Example #15
Source File: MessageChannel.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Attempts to get a {@link net.dv8tion.jda.api.entities.Message Message} from the Discord's servers that has
 * the same id as the id provided.
 * <br>Note: when retrieving a Message, you must retrieve it from the channel it was sent in!
 *
 * <p><b>Only bots can use this endpoint! A similar behaviour can be simulated using {@link #getHistoryAround(long, int)}!</b>
 *
 * <p>The following {@link net.dv8tion.jda.api.requests.ErrorResponse ErrorResponses} are possible:
 * <ul>
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_ACCESS MISSING_ACCESS}
 *     <br>The request was attempted after the account lost access to the {@link net.dv8tion.jda.api.entities.Guild Guild}
 *         typically due to being kicked or removed, or after {@link net.dv8tion.jda.api.Permission#MESSAGE_READ Permission.MESSAGE_READ}
 *         was revoked in the {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#MISSING_PERMISSIONS MISSING_PERMISSIONS}
 *     <br>The request was attempted after the account lost {@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY Permission.MESSAGE_HISTORY}
 *         in the {@link net.dv8tion.jda.api.entities.TextChannel TextChannel}.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_MESSAGE UNKNOWN_MESSAGE}
 *     <br>The provided {@code id} does not refer to a message sent in this channel or the message has already been deleted.</li>
 *
 *     <li>{@link net.dv8tion.jda.api.requests.ErrorResponse#UNKNOWN_CHANNEL UNKNOWN_CHANNEL}
 *     <br>The request was attempted after the channel was deleted.</li>
 * </ul>
 *
 * @param  messageId
 *         The id of the sought after Message
 *
 * @throws net.dv8tion.jda.api.exceptions.AccountTypeException
 *         If the currently logged in account is not from {@link net.dv8tion.jda.api.AccountType#BOT AccountType.BOT}
 * @throws IllegalArgumentException
 *         if the provided {@code messageId} is null or empty.
 * @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
 *         If this is a {@link net.dv8tion.jda.api.entities.TextChannel TextChannel} and the logged in account does not have
 *         <ul>
 *             <li>{@link net.dv8tion.jda.api.Permission#MESSAGE_READ Permission.MESSAGE_READ}</li>
 *             <li>{@link net.dv8tion.jda.api.Permission#MESSAGE_HISTORY Permission.MESSAGE_HISTORY}</li>
 *         </ul>
 *
 * @return {@link net.dv8tion.jda.api.requests.RestAction RestAction} - Type: Message
 *         <br>The Message defined by the provided id.
 */
@Nonnull
@CheckReturnValue
default RestAction<Message> retrieveMessageById(@Nonnull String messageId)
{
    AccountTypeException.check(getJDA().getAccountType(), AccountType.BOT);
    Checks.isSnowflake(messageId, "Message ID");

    JDAImpl jda = (JDAImpl) getJDA();
    Route.CompiledRoute route = Route.Messages.GET_MESSAGE.compile(getId(), messageId);
    return new RestActionImpl<>(jda, route,
        (response, request) -> jda.getEntityBuilder().createMessage(response.getObject(), MessageChannel.this, false));
}
 
Example #16
Source File: AccountTypeException.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * The required {@link net.dv8tion.jda.api.AccountType AccountType} for the operation
 *
 * @return AccountType
 */
public AccountType getRequiredType()
{
    return requiredType;
}
 
Example #17
Source File: AccountTypeException.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new AccountTypeException instance
 *
 * @param requiredType
 *        The required {@link net.dv8tion.jda.api.AccountType AccountType} for the operation
 * @param message
 *        A specialized message
 */
public AccountTypeException(AccountType requiredType, String message)
{
    super(message);
    this.requiredType = requiredType;
}
 
Example #18
Source File: AccountTypeException.java    From JDA with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new AccountTypeException instance
 *
 * @param requiredType
 *        The required {@link net.dv8tion.jda.api.AccountType AccountType} for the operation
 */
public AccountTypeException(AccountType requiredType)
{
    this(requiredType, "The current AccountType is not valid for the attempted action. Required AccountType: " + requiredType);
}
 
Example #19
Source File: EmbedMethods.java    From Arraybot with Apache License 2.0 2 votes vote down vote up
/**
 * Checks whether or not the embed can be sent.
 * @param messageEmbed A message embed object.
 * @return True if it can, false otherwise.
 */
public boolean canSend(MessageEmbed messageEmbed) {
    return messageEmbed != null && messageEmbed.isSendable(AccountType.BOT);
}