Search in sources :

Example 1 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray 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 2 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project Bean by Xirado.

the class JDAReadyListener method onGuildReady.

@Override
public void onGuildReady(@NotNull GuildReadyEvent event) {
    if (ready)
        return;
    ready = true;
    Bean.getInstance().getExecutor().submit(() -> {
        LOGGER.info("Successfully started {} shards!", Bean.getInstance().getShardManager().getShards().size());
        Bean.getInstance().getInteractionCommandHandler().initialize();
        if (Bean.getInstance().isDebug())
            LOGGER.warn("Development mode enabled.");
        Bean.getInstance().initCommandCheck();
        JdaLavalink lavalink = Bean.getInstance().getLavalink();
        lavalink.setJdaProvider((shard) -> Bean.getInstance().getShardManager().getShardById(shard));
        lavalink.setUserId(event.getJDA().getSelfUser().getId());
        DataObject config = Bean.getInstance().getConfig();
        DataArray nodes = config.optArray("lavalink_nodes").orElse(DataArray.empty());
        nodes.stream(DataArray::getObject).forEach(node -> {
            String url = node.getString("url");
            String password = node.getString("password");
            try {
                lavalink.addNode(new URI(url), password);
            } catch (URISyntaxException e) {
                LOGGER.error("Could not add Lavalink node!", e);
            }
        });
    });
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) JdaLavalink(lavalink.client.io.jda.JdaLavalink) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Example 3 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project Bean by Xirado.

the class XPMessageListener method onMessageReceived.

@Override
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
    if (!event.isFromGuild())
        return;
    if (GuildJoinListener.isGuildBanned(event.getGuild().getIdLong()))
        return;
    if (event.getAuthor().isBot() || event.isWebhookMessage() || event.getMessage().getType().isSystem())
        return;
    if (event.getMessage().getContentRaw().startsWith(GuildManager.getGuildData(event.getGuild()).getPrefix()))
        return;
    GuildData data = GuildManager.getGuildData(event.getGuild());
    DataObject dataObject = data.toData();
    DataArray disabledChannels = dataObject.optArray("no_xp_channels").orElse(DataArray.empty());
    if (disabledChannels.stream(DataArray::getString).anyMatch(x -> x.equals(event.getChannel().getId())))
        return;
    long userId = event.getAuthor().getIdLong();
    long guildId = event.getGuild().getIdLong();
    if (!timeout.containsKey(userId) || (System.currentTimeMillis() - timeout.get(userId)) > TIMEOUT) {
        try (Connection connection = Database.getConnectionFromPool()) {
            if (connection == null)
                return;
            // Current total amount of xp
            long currentTotalXP = RankingSystem.getTotalXP(connection, guildId, userId);
            // Current level
            int level = RankingSystem.getLevel(currentTotalXP);
            // Current relative xp for next level
            long currentXP = currentTotalXP - RankingSystem.getTotalXPNeeded(level);
            // Amount of xp left to level up
            long xpLeft = RankingSystem.getXPToLevelUp(level);
            // Generate random amount of xp between 15 and 25
            int xpAmount = 15 + RANDOM.nextInt(11);
            RankingSystem.addXP(connection, guildId, userId, xpAmount, event.getAuthor().getName(), event.getAuthor().getDiscriminator(), event.getAuthor().getEffectiveAvatarUrl());
            if (xpAmount + currentXP >= xpLeft) {
                try {
                    XPAlertCommand.sendXPAlert(event.getMember(), level + 1, event.getChannel());
                } catch (InsufficientPermissionException ignored) {
                }
                if (data.hasRoleReward(level + 1)) {
                    RoleReward reward = data.getRoleReward(level + 1);
                    Role role = event.getGuild().getRoleById(reward.getRoleId());
                    if (!event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_ROLES)) {
                        Util.sendOwnerDM(EmbedUtil.errorEmbed("Hey! You have set up role-rewards in your guild **" + event.getGuild().getName() + "**, but i do not have the **Manage Roles** permission!\nPlease make sure to give me this permission!"));
                        return;
                    }
                    if (role != null) {
                        if (!event.getGuild().getSelfMember().canInteract(role)) {
                            Util.sendOwnerDM(EmbedUtil.errorEmbed("Hey! You have up role-rewards in your guild **" + event.getGuild().getName() + "**, but the role **" + role.getName() + "** is above me in the role hierarchy!\nPlease make sure to move the role above me, so i can assign them!"));
                            return;
                        }
                        event.getGuild().addRoleToMember(userId, role).queue(s -> {
                        }, e -> {
                        });
                        RoleReward oldReward = data.getLastRoleReward(level);
                        if (oldReward != null) {
                            if (oldReward.doesRemoveOnNextReward()) {
                                Role oldRole = event.getGuild().getRoleById(oldReward.getRoleId());
                                if (oldRole != null) {
                                    event.getGuild().removeRoleFromMember(userId, oldRole).queue(s -> {
                                    }, e -> {
                                    });
                                }
                            }
                        }
                    }
                }
            }
            timeout.put(userId, System.currentTimeMillis());
        } catch (Exception ex) {
            LOGGER.error("Could not update XP!", ex);
        }
    }
}
Also used : Role(net.dv8tion.jda.api.entities.Role) GuildData(at.xirado.bean.data.GuildData) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Connection(java.sql.Connection) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) DataArray(net.dv8tion.jda.api.utils.data.DataArray) InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) RoleReward(at.xirado.bean.misc.objects.RoleReward)

Example 4 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project Bean by Xirado.

the class GuildData method addRoleReward.

@CheckReturnValue
public GuildData addRoleReward(int level, long roleId, boolean persist, boolean removeOnNextReward) {
    RoleReward roleReward = new RoleReward(level, roleId, persist, removeOnNextReward);
    List<RoleReward> currentRewards = new ArrayList<>(getRoleRewards());
    if (hasRoleReward(level))
        currentRewards.removeIf(reward -> reward.getLevel() == level);
    currentRewards.add(roleReward);
    DataArray array = DataArray.empty();
    for (RoleReward reward : currentRewards) {
        array.add(DataObject.empty().put("persistant", reward.isPersistant()).put("level", reward.getLevel()).put("role_id", reward.getRoleId()).put("remove_on_next_reward", reward.doesRemoveOnNextReward()));
    }
    dataObject.put("role_rewards", array);
    return this;
}
Also used : net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Checks(net.dv8tion.jda.internal.utils.Checks) java.util(java.util) Logger(org.slf4j.Logger) Permission(net.dv8tion.jda.api.Permission) LoggerFactory(org.slf4j.LoggerFactory) SQLBuilder(at.xirado.bean.data.database.SQLBuilder) Collectors(java.util.stream.Collectors) CollectionUtils(org.apache.commons.collections4.CollectionUtils) CheckReturnValue(javax.annotation.CheckReturnValue) SQLException(java.sql.SQLException) RoleReward(at.xirado.bean.misc.objects.RoleReward) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Bean(at.xirado.bean.Bean) DataArray(net.dv8tion.jda.api.utils.data.DataArray) RoleReward(at.xirado.bean.misc.objects.RoleReward) CheckReturnValue(javax.annotation.CheckReturnValue)

Example 5 with DataArray

use of net.dv8tion.jda.api.utils.data.DataArray in project JDA by DV8FromTheWorld.

the class CommandListUpdateActionImpl method finalizeData.

@Override
protected RequestBody finalizeData() {
    DataArray json = DataArray.empty();
    json.addAll(commands);
    return getRequestBody(json);
}
Also used : DataArray(net.dv8tion.jda.api.utils.data.DataArray)

Aggregations

DataArray (net.dv8tion.jda.api.utils.data.DataArray)67 DataObject (net.dv8tion.jda.api.utils.data.DataObject)40 Nonnull (javax.annotation.Nonnull)21 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)14 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)10 JDAImpl (net.dv8tion.jda.internal.JDAImpl)9 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)8 ArrayList (java.util.ArrayList)8 Route (net.dv8tion.jda.internal.requests.Route)8 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)7 Collectors (java.util.stream.Collectors)6 CheckReturnValue (javax.annotation.CheckReturnValue)6 TemplateRole (net.dv8tion.jda.api.entities.templates.TemplateRole)5 ParsingException (net.dv8tion.jda.api.exceptions.ParsingException)5 GuildImpl (net.dv8tion.jda.internal.entities.GuildImpl)5 Bean (at.xirado.bean.Bean)4 java.util (java.util)4 OnlineStatus (net.dv8tion.jda.api.OnlineStatus)4 Template (net.dv8tion.jda.api.entities.templates.Template)4 CacheView (net.dv8tion.jda.api.utils.cache.CacheView)4