Search in sources :

Example 1 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Bean by Xirado.

the class GuildDataRoute method handle.

@Override
public Object handle(Request request, Response response) throws Exception {
    String authHeader = request.headers("authorization");
    if (authHeader == null || !authHeader.startsWith("Token ")) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String token = authHeader.substring(7);
    byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
    if (!Bean.getInstance().getAuthenticator().isAuthenticated(tokenBytes)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Invalid token (Try logging out and in again)").toString();
    }
    DataObject user = Bean.getInstance().getAuthenticator().getUser(tokenBytes);
    DataObject body = DataObject.fromJson(request.bodyAsBytes());
    if (body.isNull("guild") || body.isNull("data")) {
        response.status(400);
        return DataObject.empty().put("code", 400).put("message", "Bad request").toString();
    }
    long guildId = Long.parseUnsignedLong(body.getString("guild"));
    long userId = user.getLong("id");
    ShardManager manager = Bean.getInstance().getShardManager();
    Guild guild = manager.getGuildById(guildId);
    if (guild == null) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    Member member;
    try {
        member = guild.retrieveMemberById(userId).complete();
    } catch (ErrorResponseException ex) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", ex.getMessage()).toString();
    }
    if (!member.hasPermission(Permission.ADMINISTRATOR)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    GuildData guildData = GuildManager.getGuildData(guild);
    // Stuff to update
    DataObject updatedData = body.getObject("data");
    // old data
    DataObject currentData = guildData.toData();
    for (String key : updatedData.keys()) {
        if (ALLOWED_SETTINGS.contains(key))
            currentData.put(key, updatedData.get(key));
    }
    guildData.update();
    return user.toString();
}
Also used : GuildData(at.xirado.bean.data.GuildData) DataObject(net.dv8tion.jda.api.utils.data.DataObject) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member)

Example 2 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Bean by Xirado.

the class GuildsRoute method handle.

@Override
public Object handle(Request request, Response response) throws Exception {
    String authHeader = request.headers("authorization");
    if (authHeader == null || !authHeader.startsWith("Token ")) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Unauthorized").toString();
    }
    String token = authHeader.substring(7);
    byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
    Authenticator authenticator = Bean.getInstance().getAuthenticator();
    if (!authenticator.isAuthenticated(tokenBytes)) {
        response.status(401);
        return DataObject.empty().put("code", 401).put("message", "Invalid token (Try logging out and in again)").toString();
    }
    if (authenticator.isAccessTokenExpired(tokenBytes))
        authenticator.refreshAccessToken(tokenBytes);
    DataObject object = authenticator.getData(tokenBytes);
    DiscordCredentials credentials = authenticator.getCredentials(tokenBytes);
    String accessToken = credentials.getAccessToken();
    DataObject guilds = WebServer.retrieveGuilds(accessToken);
    if (guilds.isNull("guilds")) {
        DataObject o = DataObject.empty();
        o.put("http_code", guilds.getInt("http_code"));
        if (!guilds.isNull("code"))
            o.put("code", guilds.getInt("code"));
        if (!guilds.isNull("message"))
            o.put("message", guilds.getString("message"));
        return o.toString();
    }
    ShardManager shardManager = Bean.getInstance().getShardManager();
    List<DataObject> adminGuilds = guilds.getArray("guilds").stream(DataArray::getObject).filter(obj -> Permission.getPermissions(obj.getLong("permissions")).contains(Permission.ADMINISTRATOR) || obj.getBoolean("owner")).collect(Collectors.toList());
    DataArray guildArray = DataArray.empty();
    List<DataObject> nonInvitedGuilds = new ArrayList<>();
    for (DataObject guild : adminGuilds) {
        String name = guild.getString("name");
        long id = guild.getLong("id");
        String iconHash = guild.isNull("icon") ? null : guild.getString("icon");
        boolean botJoined = shardManager.getGuildById(id) != null;
        DataObject o = DataObject.empty();
        o.put("name", name);
        o.put("id", id + "");
        if (iconHash != null)
            o.put("icon", DiscordUtils.getIconUrl(id + "", iconHash));
        o.put("bot_joined", botJoined);
        StringBuilder initials = new StringBuilder();
        for (String s : name.split("\\s+")) {
            initials.append(s.charAt(0));
        }
        o.put("initials", initials.toString());
        if (botJoined)
            guildArray.add(o);
        else
            nonInvitedGuilds.add(o);
    }
    guildArray.addAll(nonInvitedGuilds);
    return DataObject.empty().put("guilds", guildArray).put("base_invite_url", InviteURLRoute.getInviteURL()).put("http_code", guilds.getInt("http_code")).toString();
}
Also used : DataArray(net.dv8tion.jda.api.utils.data.DataArray) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) DiscordCredentials(at.xirado.bean.backend.DiscordCredentials) DiscordUtils(at.xirado.bean.backend.DiscordUtils) Authenticator(at.xirado.bean.backend.Authenticator) Permission(net.dv8tion.jda.api.Permission) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayList(java.util.ArrayList) List(java.util.List) WebServer(at.xirado.bean.backend.WebServer) Request(spark.Request) Response(spark.Response) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Route(spark.Route) Bean(at.xirado.bean.Bean) DiscordCredentials(at.xirado.bean.backend.DiscordCredentials) ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) DataArray(net.dv8tion.jda.api.utils.data.DataArray) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Authenticator(at.xirado.bean.backend.Authenticator)

Example 3 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project cjda-util by RainbowDashLabs.

the class DiscordResolver method getUser.

/**
 * Get a user object by id, name or tag.
 *
 * @param userString string for lookup
 *
 * @return user object or null if no user is found
 */
public static Optional<User> getUser(ShardManager shardManager, String userString) {
    if (userString == null) {
        return Optional.empty();
    }
    User user = null;
    var idRaw = getIdRaw(userString);
    if (idRaw.isPresent()) {
        user = byId(userString, shardManager::getUserById);
    }
    if (user == null && DISCORD_TAG.matcher(userString).matches()) {
        user = shardManager.getUserByTag(userString);
    }
    if (user == null) {
        return shardManager.getUserCache().stream().filter(cu -> cu.getName().toLowerCase().startsWith(userString.toLowerCase())).findFirst();
    }
    return Optional.of(user);
}
Also used : Arrays(java.util.Arrays) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) ISnowflake(net.dv8tion.jda.api.entities.ISnowflake) Collection(java.util.Collection) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) User(net.dv8tion.jda.api.entities.User) Objects(java.util.Objects) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) Role(net.dv8tion.jda.api.entities.Role) Verifier.isValidId(de.chojo.jdautil.parsing.Verifier.isValidId) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Comparator(java.util.Comparator) Collections(java.util.Collections) Verifier.getIdRaw(de.chojo.jdautil.parsing.Verifier.getIdRaw) User(net.dv8tion.jda.api.entities.User)

Example 4 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project Utility by anweisen.

the class DiscordBot method init.

protected final void init() throws Exception {
    if (initialized)
        throw new IllegalStateException("init() was already called");
    initialized = true;
    builder = builder().validate();
    DiscordBotBuilder.logger.debug("Building bot with following configuration:" + "\n\t" + config + "\n\t" + builder + "\n\t" + (builder.databaseConfig == null ? "BotDatabaseConfig{null}" : builder.databaseConfig));
    boolean requireDatabase = builder.databaseConfig != null || !builder.tables.isEmpty() || builder.requireDatabase;
    if (builder.databaseConfig == null) {
        builder.databaseConfig = new BotDatabaseConfig("guilds", "guildId", null, null, null);
    }
    if (requireDatabase) {
        database = config.createDatabase();
        database.connect();
        builder.tables.forEach((ExceptionallyBiConsumer<String, SQLColumn[]>) database::createTable);
    } else {
        database = Database.unsupported();
    }
    builder.fileLanguages.addAll(config.getLanguageFiles());
    commandManager = new DefaultCommandManager(builder.databaseConfig.getPrefixColumn() == null ? new ConstantPrefixProvider(config.getDefaultPrefix()) : new DatabasePrefixProvider(config.getDefaultPrefix(), database, builder.databaseConfig.getGuildTable(), builder.databaseConfig.getGuildKeyColumn(), builder.databaseConfig.getPrefixColumn())).setUseEmbeds(builder.useEmbeds);
    if (builder.databaseConfig.getTeamRoleColumn() != null) {
        commandManager.setTeamRoleManager(new DatabaseTeamRoleManager(database, builder.databaseConfig.getGuildTable(), builder.databaseConfig.getGuildKeyColumn(), builder.databaseConfig.getTeamRoleColumn()));
    }
    if (builder.databaseConfig.getLanguageColumn() != null) {
        LanguageManager languageManager = new DatabaseLanguageManager(database, builder.databaseConfig.getGuildTable(), builder.databaseConfig.getGuildKeyColumn(), builder.databaseConfig.getLanguageColumn());
        commandManager.setLanguageManager(languageManager);
        for (String filename : builder.fileLanguages) languageManager.readFile(filename);
        for (String filename : builder.resourceLanguages) languageManager.readResource(filename);
        languageManager.setDefaultLanguage(config.getDefaultLanguage());
    } else if (!builder.fileLanguages.isEmpty() || !builder.resourceLanguages.isEmpty()) {
        DiscordBotBuilder.logger.warn("Languages were registered but no database for language management is setup!");
        LanguageManager languageManager = new ConstantLanguageManager();
        commandManager.setLanguageManager(languageManager);
        for (String filename : builder.fileLanguages) languageManager.readFile(filename);
        for (String filename : builder.resourceLanguages) languageManager.readResource(filename);
        languageManager.setDefaultLanguage(config.getDefaultLanguage());
    }
    builder.parsers.forEach((key, parser) -> commandManager.getParserContext().registerParser(key, parser.getFirst(), parser.getSecond()));
    commandManager.register(builder.commands);
    builder.taskCommands.forEach(pair -> commandManager.register(pair.getFirst(), pair.getSecond()));
    List<GatewayIntent> intents = Arrays.asList(builder.intents);
    if (!intents.contains(GatewayIntent.DIRECT_MESSAGES))
        DiscordBotBuilder.logger.warn("Missing GatewayIntent.DIRECT_MESSAGES, no commands will be available in private chats");
    if (!intents.contains(GatewayIntent.GUILD_MESSAGES))
        DiscordBotBuilder.logger.warn("Missing GatewayIntent.GUILD_MESSAGES, no commands will be available in guild chats");
    DefaultShardManagerBuilder shardManagerBuilder = DefaultShardManagerBuilder.create(config.getToken(), intents).setCallbackPoolProvider(newThreadPoolProvider("Callback")).setEventPoolProvider(newThreadPoolProvider("Events")).setShardsTotal(config.getShards()).setMemberCachePolicy(builder.memberCachePolicy).setEventManagerProvider(shardId -> eventManager).setStatusProvider(shardId -> config.getOnlineStatus()).addEventListeners(new CommandListener(commandManager), this);
    if (builder.chunkingFilter != null)
        shardManagerBuilder.setChunkingFilter(builder.chunkingFilter);
    builder.builderSettings.forEach(action -> action.accept(shardManagerBuilder));
    builder.listener.forEach(shardManagerBuilder::addEventListeners);
    for (CacheFlag cache : CacheFlag.values()) {
        if (builder.cacheFlags.contains(cache)) {
            shardManagerBuilder.enableCache(cache);
        } else {
            shardManagerBuilder.disableCache(cache);
        }
    }
    shardManager = shardManagerBuilder.build();
    builder.shardManagerSettings.forEach(action -> action.accept(shardManager));
    if (!builder.customSlashCommands.isEmpty())
        getJDA().updateCommands().addCommands(builder.customSlashCommands).queue();
    else if (!builder.disableAutoSlashCommands)
        commandManager.setupSlashCommands(getJDA());
    getJDA().retrieveApplicationInfo().queue(applicationInfo -> this.applicationInfo = applicationInfo);
    onStart();
    if (!builder.activities.isEmpty()) {
        new Timer("BotActivityChanger").schedule(new TimerTask() {

            private int index = 0;

            @Override
            public void run() {
                if (index >= builder.activities.size()) {
                    index = 0;
                }
                Supplier<? extends Activity> activitySupplier = builder.activities.get(index);
                Activity activity = activitySupplier.get();
                shardManager.setActivity(activity);
                index++;
            }
        }, 3000, builder.activityUpdateRate * 1000L);
    }
}
Also used : DatabasePrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.DatabasePrefixProvider) ThreadPoolProvider(net.dv8tion.jda.api.sharding.ThreadPoolProvider) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) DefaultShardManagerBuilder(net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder) ConstantLanguageManager(net.anweisen.utilities.jda.manager.impl.language.ConstantLanguageManager) ReadyEvent(net.dv8tion.jda.api.events.ReadyEvent) Supplier(java.util.function.Supplier) Status(net.dv8tion.jda.api.JDA.Status) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) ConfigProvider(net.anweisen.utilities.jda.manager.bot.config.ConfigProvider) SQLColumn(net.anweisen.utilities.database.SQLColumn) CommandManager(net.anweisen.utilities.jda.manager.CommandManager) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExceptionallyBiConsumer(net.anweisen.utilities.common.function.ExceptionallyBiConsumer) LanguageManager(net.anweisen.utilities.jda.manager.language.LanguageManager) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) DefaultCommandManager(net.anweisen.utilities.jda.manager.impl.DefaultCommandManager) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) Nonnull(javax.annotation.Nonnull) Database(net.anweisen.utilities.database.Database) ExecutorService(java.util.concurrent.ExecutorService) ConstantPrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.ConstantPrefixProvider) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) NamedThreadFactory(net.anweisen.utilities.common.collection.NamedThreadFactory) ActionEventListener(net.anweisen.utilities.jda.manager.listener.manager.ActionEventListener) Activity(net.dv8tion.jda.api.entities.Activity) BotConfigCreator(net.anweisen.utilities.jda.manager.bot.config.BotConfigCreator) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Consumer(java.util.function.Consumer) SubscribeEvent(net.dv8tion.jda.api.hooks.SubscribeEvent) CheckReturnValue(javax.annotation.CheckReturnValue) CommandListener(net.anweisen.utilities.jda.manager.listener.CommandListener) CombinedEventManager(net.anweisen.utilities.jda.manager.listener.manager.CombinedEventManager) DatabaseTeamRoleManager(net.anweisen.utilities.jda.manager.impl.DatabaseTeamRoleManager) ILogger(net.anweisen.utilities.common.logging.ILogger) Preconditions(com.google.common.base.Preconditions) IEventManager(net.dv8tion.jda.api.hooks.IEventManager) FileDocument(net.anweisen.utilities.common.config.FileDocument) DatabaseLanguageManager(net.anweisen.utilities.jda.manager.impl.language.DatabaseLanguageManager) ApplicationInfo(net.dv8tion.jda.api.entities.ApplicationInfo) ConstantPrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.ConstantPrefixProvider) CacheFlag(net.dv8tion.jda.api.utils.cache.CacheFlag) DatabasePrefixProvider(net.anweisen.utilities.jda.manager.impl.prefix.DatabasePrefixProvider) Activity(net.dv8tion.jda.api.entities.Activity) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) DefaultCommandManager(net.anweisen.utilities.jda.manager.impl.DefaultCommandManager) DatabaseTeamRoleManager(net.anweisen.utilities.jda.manager.impl.DatabaseTeamRoleManager) CommandListener(net.anweisen.utilities.jda.manager.listener.CommandListener) ConstantLanguageManager(net.anweisen.utilities.jda.manager.impl.language.ConstantLanguageManager) DefaultShardManagerBuilder(net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder) ConstantLanguageManager(net.anweisen.utilities.jda.manager.impl.language.ConstantLanguageManager) LanguageManager(net.anweisen.utilities.jda.manager.language.LanguageManager) DatabaseLanguageManager(net.anweisen.utilities.jda.manager.impl.language.DatabaseLanguageManager) DatabaseLanguageManager(net.anweisen.utilities.jda.manager.impl.language.DatabaseLanguageManager) Supplier(java.util.function.Supplier)

Example 5 with ShardManager

use of net.dv8tion.jda.api.sharding.ShardManager in project SkyBot by duncte123.

the class ShardInfoCommand method embedTable.

private void embedTable(CommandContext ctx) {
    final EmbedBuilder embedBuilder = new EmbedBuilder();
    final int currentShard = ctx.getJDA().getShardInfo().getShardId();
    final ShardManager shardManager = ctx.getJDA().getShardManager();
    final ShardCacheView shardCache = shardManager.getShardCache();
    final List<JDA> shards = new ArrayList<>(shardCache.asList());
    Collections.reverse(shards);
    for (final JDA shard : shards) {
        final StringBuilder valueBuilder = new StringBuilder();
        final LongLongPair channelStats = getConnectedVoiceChannels(shard);
        valueBuilder.append("**Status:** ").append(getShardStatus(shard)).append("\n**Ping:** ").append(shard.getGatewayPing()).append("\n**Guilds:** ").append(shard.getGuildCache().size()).append("\n**VCs:** ").append(channelStats.getFirst()).append(" / ").append(channelStats.getSecond());
        final int shardId = shard.getShardInfo().getShardId();
        embedBuilder.addField(String.format("Shard #%s%s", shardId, shardId == currentShard ? " (current)" : ""), valueBuilder.toString(), true);
    }
    final long connectedShards = shardCache.applyStream((s) -> s.filter((shard) -> shard.getStatus() == JDA.Status.CONNECTED).count());
    final String avgPing = new DecimalFormat("###").format(shardManager.getAverageGatewayPing());
    final long guilds = shardManager.getGuildCache().size();
    final LongLongPair channelStats = getConnectedVoiceChannels(shardManager);
    embedBuilder.addField("Total/Average", String.format("**Connected:** %s\n**Ping:** %s\n**Guilds:** %s\n**VCs:** %s / %s", connectedShards, avgPing, guilds, channelStats.getFirst(), channelStats.getSecond()), false);
    sendEmbed(ctx, embedBuilder);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) LongLongPair(ml.duncte123.skybot.objects.pairs.LongLongPair) JDA(net.dv8tion.jda.api.JDA) ShardCacheView(net.dv8tion.jda.api.utils.cache.ShardCacheView) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager)

Aggregations

ShardManager (net.dv8tion.jda.api.sharding.ShardManager)37 JDA (net.dv8tion.jda.api.JDA)16 Guild (net.dv8tion.jda.api.entities.Guild)15 Member (net.dv8tion.jda.api.entities.Member)15 User (net.dv8tion.jda.api.entities.User)13 ArrayList (java.util.ArrayList)10 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 Permission (net.dv8tion.jda.api.Permission)8 TextChannel (net.dv8tion.jda.api.entities.TextChannel)7 Arrays (java.util.Arrays)5 Nonnull (javax.annotation.Nonnull)5 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)4 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)4 ZoneOffset (java.time.ZoneOffset)3 Executors (java.util.concurrent.Executors)3 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)3 Nullable (javax.annotation.Nullable)3 CommandContext (ml.duncte123.skybot.objects.command.CommandContext)3 LongLongPair (ml.duncte123.skybot.objects.pairs.LongLongPair)3