net.dv8tion.jda.api.JDA Java Examples

The following examples show how to use net.dv8tion.jda.api.JDA. 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: BotListRequest.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the body for the request.
 * The "{total}" and "{shard}" placeholders can only be used when the bot is sharded.
 * @return The body.
 */
private RequestBody getBody(JDA shard) {
    JDA.ShardInfo shardInfo = shard.getShardInfo();
    JSON json = new JSON();
    for(Parameter parameter : parameters) {
        String value = parameter.getValue()
                .replace("{guilds}", String.valueOf(shard.getGuilds().size()));
        value = value
                .replace("{total}", String.valueOf(shardInfo.getShardTotal()))
                .replace("{shard}", String.valueOf(shardInfo.getShardId()));
        Object object;
        if(UDatatypes.isInt(value)) {
            object = Integer.valueOf(value);
        } else {
            object = value;
        }
        json.put(parameter.getKey(), object);
    }
    return RequestBody.create(type, json.marshal());
}
 
Example #2
Source File: BotListRequest.java    From Arraybot with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the request.
 * @param shard The JDA instance involved.
 */
public void send(JDA shard) {
    OkHttpClient client = new OkHttpClient();
    String url = this.url.replace("{id}", shard.getSelfUser().getId());
    Request.Builder request = new Request.Builder()
            .url(url)
            .post(getBody(shard));
    if(!auth.isEmpty()) {
        request.addHeader("Authorization", auth);
    }
    try {
        Response response = client.newCall(request.build()).execute();
        logger.info("POST request to \"{}\" returned status code {}.", url, response.code());
        response.close();
    } catch(IOException exception) {
        logger.error(String.format("An error occurred sending a POST request to \"%s\".", url), exception);
    }
}
 
Example #3
Source File: JDAImpl.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public JDA awaitStatus(@Nonnull Status status, @Nonnull Status... failOn) throws InterruptedException
{
    Checks.notNull(status, "Status");
    Checks.check(status.isInit(), "Cannot await the status %s as it is not part of the login cycle!", status);
    if (getStatus() == Status.CONNECTED)
        return this;
    List<Status> failStatus = Arrays.asList(failOn);
    while (!getStatus().isInit()                         // JDA might disconnect while starting
            || getStatus().ordinal() < status.ordinal()) // Wait until status is bypassed
    {
        if (getStatus() == Status.SHUTDOWN)
            throw new IllegalStateException("Was shutdown trying to await status");
        else if (failStatus.contains(getStatus()))
            return this;
        Thread.sleep(50);
    }
    return this;
}
 
Example #4
Source File: SoundPlayerImpl.java    From DiscordSoundboard with Apache License 2.0 6 votes vote down vote up
/**
 * Get a list of users
 *
 * @return List of soundboard users.
 */
public List<net.dirtydeeds.discordsoundboard.beans.User> getUsers() {
    String userNameToSelect = appProperties.getProperty("username_to_join_channel");
    List<User> users = new ArrayList<>();
    for (net.dv8tion.jda.api.entities.User discordUser : bot.getUsers()) {
        if (discordUser.getJDA().getStatus().equals(JDA.Status.CONNECTED)) {
            boolean selected = false;
            String username = discordUser.getName();
            if (userNameToSelect.equals(username)) {
                selected = true;
            }
            Optional<User> optionalUser = userRepository.findById(discordUser.getId());
            if (optionalUser.isPresent()) {
                User user = optionalUser.get();
                user.setSelected(selected);
                users.add(user);
            } else {
                users.add(new net.dirtydeeds.discordsoundboard.beans.User(discordUser.getId(), username, selected));
            }
        }
    }
    users.sort(Comparator.comparing(User::getUsername));
    userRepository.saveAll(users);
    return users;
}
 
Example #5
Source File: WebSocketClient.java    From JDA with Apache License 2.0 6 votes vote down vote up
@Override
public void run(boolean isLast) throws InterruptedException
{
    if (shutdown)
        return;
    reconnect(true);
    if (isLast)
        return;
    try
    {
        api.awaitStatus(JDA.Status.LOADING_SUBSYSTEMS, JDA.Status.RECONNECT_QUEUED);
    }
    catch (IllegalStateException ex)
    {
        close();
        LOG.debug("Shutdown while trying to reconnect");
    }
}
 
Example #6
Source File: WebSocketClient.java    From JDA with Apache License 2.0 5 votes vote down vote up
public void ready()
{
    if (initiating)
    {
        initiating = false;
        processingReady = false;
        if (firstInit)
        {
            firstInit = false;
            if (api.getGuilds().size() >= 2000) //Show large warning when connected to >=2000 guilds
            {
                JDAImpl.LOG.warn(" __      __ _    ___  _  _  ___  _  _   ___  _ ");
                JDAImpl.LOG.warn(" \\ \\    / //_\\  | _ \\| \\| ||_ _|| \\| | / __|| |");
                JDAImpl.LOG.warn("  \\ \\/\\/ // _ \\ |   /| .` | | | | .` || (_ ||_|");
                JDAImpl.LOG.warn("   \\_/\\_//_/ \\_\\|_|_\\|_|\\_||___||_|\\_| \\___|(_)");
                JDAImpl.LOG.warn("You're running a session with over 2000 connected");
                JDAImpl.LOG.warn("guilds. You should shard the connection in order");
                JDAImpl.LOG.warn("to split the load or things like resuming");
                JDAImpl.LOG.warn("connection might not work as expected.");
                JDAImpl.LOG.warn("For more info see https://git.io/vrFWP");
            }
            JDAImpl.LOG.info("Finished Loading!");
            api.handleEvent(new ReadyEvent(api, api.getResponseTotal()));
        }
        else
        {
            updateAudioManagerReferences();
            JDAImpl.LOG.info("Finished (Re)Loading!");
            api.handleEvent(new ReconnectedEvent(api, api.getResponseTotal()));
        }
    }
    else
    {
        JDAImpl.LOG.debug("Successfully resumed Session!");
        api.handleEvent(new ResumedEvent(api, api.getResponseTotal()));
    }
    api.setStatus(JDA.Status.CONNECTED);
}
 
Example #7
Source File: ShardCacheViewImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Override
public JDA getElementById(int id)
{
    return generator.get()
        .map(view -> view.getElementById(id))
        .filter(Objects::nonNull)
        .findFirst().orElse(null);
}
 
Example #8
Source File: GuildUpdateOwnerEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GuildUpdateOwnerEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild, @Nullable Member oldOwner,
                             long prevId, long nextId)
{
    super(api, responseNumber, guild, oldOwner, guild.getOwner(), IDENTIFIER);
    this.prevId = prevId;
    this.nextId = nextId;
}
 
Example #9
Source File: WebSocketClient.java    From JDA with Apache License 2.0 5 votes vote down vote up
public WebSocketClient(JDAImpl api, Compression compression, int gatewayIntents)
{
    this.api = api;
    this.executor = api.getGatewayPool();
    this.shardInfo = api.getShardInfo();
    this.compression = compression;
    this.gatewayIntents = gatewayIntents;
    this.chunkManager = new MemberChunkManager(this);
    this.shouldReconnect = api.isAutoReconnect();
    this.connectNode = new StartingNode();
    setupHandlers();
    try
    {
        api.getSessionController().appendSession(connectNode);
    }
    catch (RuntimeException | Error e)
    {
        LOG.error("Failed to append new session to session controller queue. Shutting down!", e);
        this.api.setStatus(JDA.Status.SHUTDOWN);
        this.api.handleEvent(
            new ShutdownEvent(api, OffsetDateTime.now(), 1006));
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        else
            throw (Error) e;
    }
}
 
Example #10
Source File: GenericPrivateMessageReactionEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GenericPrivateMessageReactionEvent(@Nonnull JDA api, long responseNumber, @Nullable User user, @Nonnull MessageReaction reaction, long userId)
{
    super(api, responseNumber, reaction.getMessageIdLong(), (PrivateChannel) reaction.getChannel());
    this.userId = userId;
    this.issuer = user;
    this.reaction = reaction;
}
 
Example #11
Source File: WebSocketClient.java    From JDA with Apache License 2.0 5 votes vote down vote up
protected void sendIdentify()
{
    LOG.debug("Sending Identify-packet...");
    PresenceImpl presenceObj = (PresenceImpl) api.getPresence();
    DataObject connectionProperties = DataObject.empty()
        .put("$os", System.getProperty("os.name"))
        .put("$browser", "JDA")
        .put("$device", "JDA")
        .put("$referring_domain", "")
        .put("$referrer", "");
    DataObject payload = DataObject.empty()
        .put("presence", presenceObj.getFullPresence())
        .put("token", getToken())
        .put("properties", connectionProperties)
        .put("v", JDAInfo.DISCORD_GATEWAY_VERSION)
        .put("large_threshold", api.getLargeThreshold());
    //We only provide intents if they are not the default (all) for backwards compatibility
    // Discord has additional enforcements put in place even if you specify to subscribe to all intents
    if (api.useIntents())
        payload.put("intents", gatewayIntents);

    DataObject identify = DataObject.empty()
            .put("op", WebSocketCode.IDENTIFY)
            .put("d", payload);
    if (shardInfo != null)
    {
        payload
            .put("shard", DataArray.empty()
                .add(shardInfo.getShardId())
                .add(shardInfo.getShardTotal()));
    }
    send(identify.toString(), true);
    handleIdentifyRateLimit = true;
    identifyTime = System.currentTimeMillis();
    sentAuthInfo = true;
    api.setStatus(JDA.Status.AWAITING_LOGIN_CONFIRMATION);
}
 
Example #12
Source File: DisconnectEvent.java    From JDA with Apache License 2.0 5 votes vote down vote up
public DisconnectEvent(
    @Nonnull JDA api,
    @Nullable WebSocketFrame serverCloseFrame, @Nullable WebSocketFrame clientCloseFrame,
    boolean closedByServer, @Nonnull OffsetDateTime disconnectTime)
{
    super(api);
    this.serverCloseFrame = serverCloseFrame;
    this.clientCloseFrame = clientCloseFrame;
    this.closedByServer = closedByServer;
    this.disconnectTime = disconnectTime;
}
 
Example #13
Source File: GuildActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
public GuildActionImpl(JDA api, String name)
{
    super(api, Route.Guilds.CREATE_GUILD.compile());
    this.setName(name);

    this.roles = new LinkedList<>();
    this.channels = new LinkedList<>();
    // public role is the first element
    this.roles.add(new RoleData(0));
}
 
Example #14
Source File: BotManager.java    From Arraybot with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the author's URL.
 * @param shard The shard.
 */
private void setAuthorUrl(JDA shard) {
    User author = shard.getUserById(configuration.getBotAuthors()[0]);
    if(author != null) {
        Cache.INSTANCE.setAuthorIconUrl(author.getAvatarUrl());
    }
}
 
Example #15
Source File: DeferredRestAction.java    From JDA with Apache License 2.0 5 votes vote down vote up
public DeferredRestAction(JDA api, Class<T> type,
                          Supplier<T> valueSupplier,
                          Supplier<R> actionSupplier)
{
    this.api = api;
    this.type = type;
    this.valueSupplier = valueSupplier;
    this.actionSupplier = actionSupplier;
}
 
Example #16
Source File: CompletedRestAction.java    From JDA with Apache License 2.0 4 votes vote down vote up
public CompletedRestAction(JDA api, T value, Throwable error)
{
    this.api = api;
    this.value = value;
    this.error = error;
}
 
Example #17
Source File: RoleCreateEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public RoleCreateEvent(@Nonnull JDA api, long responseNumber, @Nonnull Role createdRole)
{
    super(api, responseNumber, createdRole);
}
 
Example #18
Source File: WebSocketClient.java    From JDA with Apache License 2.0 4 votes vote down vote up
public JDA getJDA()
{
    return api;
}
 
Example #19
Source File: GenericTextChannelEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public GenericTextChannelEvent(@Nonnull JDA api, long responseNumber, @Nonnull TextChannel channel)
{
    super(api, responseNumber);
    this.channel = channel;
}
 
Example #20
Source File: DiscordGuildMessageSentEvent.java    From DiscordSRV with GNU General Public License v3.0 4 votes vote down vote up
public DiscordGuildMessageSentEvent(JDA jda, Message message) {
    super(jda);
    this.channel = message.getTextChannel();
    this.guild = message.getGuild();
    this.message = message;
}
 
Example #21
Source File: GenericGuildMemberEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public GenericGuildMemberEvent(@Nonnull JDA api, long responseNumber, @Nonnull Member member)
{
    super(api, responseNumber, member.getGuild());
    this.member = member;
}
 
Example #22
Source File: RoleUpdatePermissionsEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public RoleUpdatePermissionsEvent(@Nonnull JDA api, long responseNumber, @Nonnull Role role, long oldPermissionsRaw)
{
    super(api, responseNumber, role, Permission.getPermissions(oldPermissionsRaw), role.getPermissions(), IDENTIFIER);
    this.oldPermissionsRaw = oldPermissionsRaw;
    this.newPermissionsRaw = role.getPermissionsRaw();
}
 
Example #23
Source File: GuildBanEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public GuildBanEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild, @Nonnull User user)
{
    super(api, responseNumber, guild);
    this.user = user;
}
 
Example #24
Source File: TextChannelUpdatePermissionsEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public TextChannelUpdatePermissionsEvent(@Nonnull JDA api, long responseNumber, @Nonnull TextChannel channel, @Nonnull List<IPermissionHolder> permHolders)
{
    super(api, responseNumber, channel);
    this.changed = permHolders;
}
 
Example #25
Source File: PrioritizingSessionController.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
@Nonnull
@Override
public String getGateway(@Nonnull JDA api) {
    throw new UnsupportedOperationException();
}
 
Example #26
Source File: TextChannelDeleteEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public TextChannelDeleteEvent(@Nonnull JDA api, long responseNumber, @Nonnull TextChannel channel)
{
    super(api, responseNumber, channel);
}
 
Example #27
Source File: Context.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public JDA getJDA() {
    return getEvent().getJDA();
}
 
Example #28
Source File: VoiceChannelCreateEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public VoiceChannelCreateEvent(@Nonnull JDA api, long responseNumber, @Nonnull VoiceChannel channel)
{
    super(api, responseNumber, channel);
}
 
Example #29
Source File: MantaroBot.java    From MantaroBot with GNU General Public License v3.0 4 votes vote down vote up
public JDA getShardGuild(long guildId) {
    return getShardManager().getShardById((int) ((guildId >> 22) % getShardManager().getShardsTotal()));
}
 
Example #30
Source File: GuildAvailableEvent.java    From JDA with Apache License 2.0 4 votes vote down vote up
public GuildAvailableEvent(@Nonnull JDA api, long responseNumber, @Nonnull Guild guild)
{
    super(api, responseNumber, guild);
}