net.dv8tion.jda.api.utils.MemberCachePolicy Java Examples

The following examples show how to use net.dv8tion.jda.api.utils.MemberCachePolicy. 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: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 5 votes vote down vote up
private DefaultShardManagerBuilder applyDefault()
{
    return this.setMemberCachePolicy(MemberCachePolicy.DEFAULT)
               .setChunkingFilter(ChunkingFilter.NONE)
               .disableCache(CacheFlag.CLIENT_STATUS, CacheFlag.ACTIVITY)
               .setLargeThreshold(250);
}
 
Example #2
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 5 votes vote down vote up
private DefaultShardManagerBuilder applyLight()
{
    return this.setMemberCachePolicy(MemberCachePolicy.NONE)
               .setChunkingFilter(ChunkingFilter.NONE)
               .disableCache(EnumSet.allOf(CacheFlag.class))
               .setLargeThreshold(50);
}
 
Example #3
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 5 votes vote down vote up
private DefaultShardManagerBuilder applyIntents()
{
    EnumSet<CacheFlag> disabledCache = EnumSet.allOf(CacheFlag.class);
    for (CacheFlag flag : CacheFlag.values())
    {
        GatewayIntent requiredIntent = flag.getRequiredIntent();
        if (requiredIntent == null || (requiredIntent.getRawValue() & intents) != 0)
            disabledCache.remove(flag);
    }

    boolean enableMembers = (intents & GatewayIntent.GUILD_MEMBERS.getRawValue()) != 0;
    return setChunkingFilter(enableMembers ? ChunkingFilter.ALL : ChunkingFilter.NONE)
            .setMemberCachePolicy(enableMembers ? MemberCachePolicy.ALL : MemberCachePolicy.DEFAULT)
            .setDisabledCache(disabledCache);
}
 
Example #4
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 5 votes vote down vote up
private void checkIntents()
{
    boolean membersIntent = (intents & GatewayIntent.GUILD_MEMBERS.getRawValue()) != 0;
    if (!membersIntent && memberCachePolicy == MemberCachePolicy.ALL)
        throw new IllegalStateException("Cannot use MemberCachePolicy.ALL without GatewayIntent.GUILD_MEMBERS enabled!");
    else if (!membersIntent && chunkingFilter != ChunkingFilter.NONE)
        DefaultShardManager.LOG.warn("Member chunking is disabled due to missing GUILD_MEMBERS intent.");

    if (!automaticallyDisabled.isEmpty())
    {
        JDAImpl.LOG.warn("Automatically disabled CacheFlags due to missing intents");
        // List each missing intent
        automaticallyDisabled.stream()
            .map(it -> "Disabled CacheFlag." + it + " (missing GatewayIntent." + it.getRequiredIntent() + ")")
            .forEach(JDAImpl.LOG::warn);

        // Tell user how to disable this warning
        JDAImpl.LOG.warn("You can manually disable these flags to remove this warning by using disableCache({}) on your DefaultShardManagerBuilder",
            automaticallyDisabled.stream()
                    .map(it -> "CacheFlag." + it)
                    .collect(Collectors.joining(", ")));
        // Only print this warning once
        automaticallyDisabled.clear();
    }

    if (cacheFlags.isEmpty())
        return;

    EnumSet<GatewayIntent> providedIntents = GatewayIntent.getIntents(intents);
    for (CacheFlag flag : cacheFlags)
    {
        GatewayIntent intent = flag.getRequiredIntent();
        if (intent != null && !providedIntents.contains(intent))
            throw new IllegalArgumentException("Cannot use CacheFlag." + flag + " without GatewayIntent." + intent + "!");
    }
}
 
Example #5
Source File: ShardingConfig.java    From JDA with Apache License 2.0 5 votes vote down vote up
public ShardingConfig(int shardsTotal, boolean useShutdownNow, int intents, MemberCachePolicy memberCachePolicy)
{
    this.shardsTotal = shardsTotal;
    this.useShutdownNow = useShutdownNow;
    this.intents = intents;
    this.memberCachePolicy = memberCachePolicy;
}
 
Example #6
Source File: SkyBot.java    From SkyBot with GNU Affero General Public License v3.0 4 votes vote down vote up
private SkyBot() throws Exception {
        // Set our animated emotes as default reactions
        MessageUtils.setErrorReaction("a:_no:577795484060483584");
        MessageUtils.setSuccessReaction("a:_yes:577795293546938369");

        // Load in our container
        final Variables variables = new Variables();
        final DunctebotConfig config = variables.getConfig();
        final CommandManager commandManager = variables.getCommandManager();
        final Logger logger = LoggerFactory.getLogger(SkyBot.class);

        // Set the user-agent of the bot
        WebUtils.setUserAgent("Mozilla/5.0 (compatible; SkyBot/" + Settings.VERSION + "; +https://dunctebot.com;)");
        EmbedUtils.setEmbedBuilder(
            () -> new EmbedBuilder()
                .setColor(Settings.DEFAULT_COLOUR)
//                .setFooter("DuncteBot", Settings.DEFAULT_ICON)
//                .setTimestamp(Instant.now())
        );

        Settings.PREFIX = config.discord.prefix;

        // Set some defaults for rest-actions
        RestAction.setPassContext(true);
        RestAction.setDefaultFailure(ignore(UNKNOWN_MESSAGE));
        // If any rest-action doesn't get executed within 2 minutes we will mark it as failed
        RestAction.setDefaultTimeout(2L, TimeUnit.MINUTES);

        if (variables.useApi()) {
            logger.info(TextColor.GREEN + "Using api for all connections" + TextColor.RESET);
        } else {
            logger.warn("Using SQLite as the database");
            logger.warn("Please note that is is not recommended for production");
        }

        //Load the settings before loading the bot
        GuildSettingsUtils.loadAllSettings(variables);

        //Set the token to a string
        final String token = config.discord.token;

        //But this time we are going to shard it
        final int totalShards = config.discord.totalShards;

        this.activityProvider = (shardId) -> Activity.playing(
            config.discord.prefix + "help | Shard " + (shardId + 1)
        );

        final LongLongPair commandCount = commandManager.getCommandCount();

        logger.info("{} commands with {} aliases loaded.", commandCount.getFirst(), commandCount.getSecond());
        LavalinkManager.ins.start(config, variables.getAudioUtils());

        final EventManager eventManager = new EventManager(variables);
        // Build our shard manager
        final DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.create(
            GatewayIntent.GUILD_MEMBERS,
            GatewayIntent.GUILD_BANS,
            GatewayIntent.GUILD_EMOJIS,
            GatewayIntent.GUILD_VOICE_STATES,
            GatewayIntent.GUILD_MESSAGES
        )
            .setToken(token)
            .setShardsTotal(totalShards)
            .setActivityProvider(this.activityProvider)
            .setBulkDeleteSplittingEnabled(false)
            .setEventManagerProvider((id) -> eventManager)
            // Keep guild owners, voice members and patrons in cache
            .setMemberCachePolicy(MemberCachePolicy.DEFAULT.or(PATRON_POLICY))
//            .setMemberCachePolicy(MemberCachePolicy.NONE)
            // Enable lazy loading
            .setChunkingFilter(ChunkingFilter.NONE)
            // Enable lazy loading for guilds other than our own
//            .setChunkingFilter((guildId) -> guildId == Settings.SUPPORT_GUILD_ID)
            .enableCache(CacheFlag.VOICE_STATE, CacheFlag.EMOTE, CacheFlag.MEMBER_OVERRIDES)
            .disableCache(CacheFlag.ACTIVITY, CacheFlag.CLIENT_STATUS)
            .setHttpClientBuilder(
                new OkHttpClient.Builder()
                    .connectTimeout(30L, TimeUnit.SECONDS)
                    .readTimeout(30L, TimeUnit.SECONDS)
                    .writeTimeout(30L, TimeUnit.SECONDS)
            );

        this.startGameTimer();

        // If lavalink is enabled we will hook it into jda
        if (LavalinkManager.ins.isEnabled()) {
            builder.setVoiceDispatchInterceptor(LavalinkManager.ins.getLavalink().getVoiceInterceptor());
        }

        this.shardManager = builder.build();

        HelpEmbeds.init(commandManager);

        // Load the web server if we are not running "locally"
        // TODO: change this config value to "web_server" or something
        if (!config.discord.local) {
            webRouter = new WebRouter(shardManager, variables);
        }
    }
 
Example #7
Source File: ShardingConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
public MemberCachePolicy getMemberCachePolicy()
{
    return memberCachePolicy;
}
 
Example #8
Source File: ShardingConfig.java    From JDA with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static ShardingConfig getDefault()
{
    return new ShardingConfig(1, false, GatewayIntent.ALL_INTENTS, MemberCachePolicy.ALL);
}
 
Example #9
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Configure the member caching policy.
 * This will decide whether to cache a member (and its respective user).
 * <br>All members are cached by default. If a guild is enabled for chunking, all members will be cached for it.
 *
 * <p>You can use this to define a custom caching policy that will greatly improve memory usage.
 * <p>It is not recommended to disable {@link GatewayIntent#GUILD_MEMBERS GatewayIntent.GUILD_MEMBERS} when
 * using {@link MemberCachePolicy#ALL MemberCachePolicy.ALL} as the members cannot be removed from cache by a leave event without this intent.
 *
 * <h2>Example</h2>
 * <pre>{@code
 * public void configureCache(DefaultShardManagerBuilder builder) {
 *     // Cache members who are in a voice channel
 *     MemberCachePolicy policy = MemberCachePolicy.VOICE;
 *     // Cache members who are in a voice channel
 *     // AND are also online
 *     policy = policy.and(MemberCachePolicy.ONLINE);
 *     // Cache members who are in a voice channel
 *     // AND are also online
 *     // OR are the owner of the guild
 *     policy = policy.or(MemberCachePolicy.OWNER);
 *     // Cache members who have a role with the name "Moderator"
 *     policy = (member) -> member.getRoles().stream().map(Role::getName).anyMatch("Moderator"::equals);
 *
 *     builder.setMemberCachePolicy(policy);
 * }
 * }</pre>
 *
 * @param  policy
 *         The {@link MemberCachePolicy} or null to use default {@link MemberCachePolicy#ALL}
 *
 * @return The DefaultShardManagerBuilder instance. Useful for chaining.
 *
 * @see    MemberCachePolicy
 * @see    #setEnabledIntents(Collection)
 *
 * @since  4.2.0
 */
@Nonnull
public DefaultShardManagerBuilder setMemberCachePolicy(@Nullable MemberCachePolicy policy)
{
    if (policy == null)
        this.memberCachePolicy = MemberCachePolicy.ALL;
    else
        this.memberCachePolicy = policy;
    return this;
}
 
Example #10
Source File: DefaultShardManagerBuilder.java    From JDA with Apache License 2.0 3 votes vote down vote up
/**
 * Enable typing and presence update events.
 * <br>These events cover the majority of traffic happening on the gateway and thus cause a lot
 * of bandwidth usage. Disabling these events means the cache for users might become outdated since
 * user properties are only updated by presence updates.
 * <br>Default: true
 *
 * <h2>Notice</h2>
 * This disables the majority of member cache and related events. If anything in your project
 * relies on member state you should keep this enabled.
 *
 * @param  enabled
 *         True, if guild subscriptions should be enabled
 *
 * @return The DefaultShardManagerBuilder instance. Useful for chaining.
 *
 * @since  4.1.0
 *
 * @deprecated This is now superceded by {@link #setDisabledIntents(Collection)} and {@link #setMemberCachePolicy(MemberCachePolicy)}.
 *             To get identical behavior you can do {@code setMemberCachePolicy(VOICE).setDisabledIntents(GatewayIntent.GUILD_PRESENCES, GatewayIntent.GUILD_MESSAGE_TYPING, GatewayIntent.GUILD_MEMBERS)}
 */
@Nonnull
@Deprecated
@ReplaceWith("setDisabledIntents(...).setMemberCachePolicy(...)")
@DeprecatedSince("4.2.0")
public DefaultShardManagerBuilder setGuildSubscriptionsEnabled(boolean enabled)
{
    if (!enabled)
    {
        setMemberCachePolicy(MemberCachePolicy.VOICE);
        intents &= ~JDABuilder.GUILD_SUBSCRIPTIONS;
    }
    return this;
}