Search in sources :

Example 6 with DataObject

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

the class Authenticator method isAuthenticated.

public boolean isAuthenticated(byte[] token) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(token);
    if (!users.containsKey(byteBuffer))
        return false;
    DataObject object = users.get(byteBuffer);
    long generationTime = object.getLong("generation_time");
    OffsetDateTime maxAge = OffsetDateTime.of(LocalDateTime.ofEpochSecond(generationTime, 0, ZoneOffset.UTC), ZoneOffset.UTC).plusDays(3);
    if (maxAge.isBefore(OffsetDateTime.now())) {
        invalidate(byteBuffer);
        return false;
    }
    return true;
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject) OffsetDateTime(java.time.OffsetDateTime) ByteBuffer(java.nio.ByteBuffer)

Example 7 with DataObject

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

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

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

the class GuildManager method createGuildData.

private static GuildData createGuildData(Guild guild) {
    DataObject json = DataObject.empty().put("id", guild.getIdLong()).put("name", guild.getName()).put("owner", guild.getOwnerIdLong()).put("created", guild.getTimeCreated().toString()).put("joined", guild.getSelfMember().getTimeJoined().toString()).put("command_prefix", "+").put("vip", false).put("language", guild.getLocale().toString());
    updateGuildData(guild.getIdLong(), json);
    return new GuildData(guild.getIdLong(), json);
}
Also used : DataObject(net.dv8tion.jda.api.utils.data.DataObject)

Example 10 with DataObject

use of net.dv8tion.jda.api.utils.data.DataObject in project SkyBot by DuncteBot.

the class CommandManager method runCustomCommand.

private void runCustomCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    final CustomCommand cusomCommand = (CustomCommand) cmd;
    if (cusomCommand.getGuildId() != event.getGuild().getIdLong()) {
        return;
    }
    try {
        MDC.put("command.custom.message", cusomCommand.getMessage());
        final Parser parser = CommandUtils.getParser(new CommandContext(invoke, args, event, variables));
        final String message = parser.parse(cusomCommand.getMessage());
        final MessageConfig.Builder messageBuilder = MessageConfig.Builder.fromEvent(event);
        final DataObject object = parser.get("embed");
        boolean hasContent = false;
        if (!message.isEmpty()) {
            messageBuilder.setMessage("\u200B" + message);
            hasContent = true;
        }
        if (object != null) {
            final JDAImpl jda = (JDAImpl) event.getJDA();
            final EmbedBuilder embed = new EmbedBuilder(jda.getEntityBuilder().createMessageEmbed(object));
            messageBuilder.addEmbed(true, embed);
            hasContent = true;
        }
        if (hasContent) {
            sendMsg(messageBuilder.build());
        }
        parser.clear();
    } catch (Exception e) {
        sendMsg(MessageConfig.Builder.fromEvent(event).setMessage("Error with parsing custom command: " + e.getMessage()).build());
        Sentry.captureException(e);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CustomCommand(ml.duncte123.skybot.objects.command.custom.CustomCommand) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) DataObject(net.dv8tion.jda.api.utils.data.DataObject) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) JDAImpl(net.dv8tion.jda.internal.JDAImpl) Parser(com.jagrosh.jagtag.Parser)

Aggregations

DataObject (net.dv8tion.jda.api.utils.data.DataObject)198 DataArray (net.dv8tion.jda.api.utils.data.DataArray)58 Nonnull (javax.annotation.Nonnull)53 IOException (java.io.IOException)15 ArrayList (java.util.ArrayList)15 BufferedReader (java.io.BufferedReader)13 InputStreamReader (java.io.InputStreamReader)13 URL (java.net.URL)13 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)13 Route (net.dv8tion.jda.internal.requests.Route)12 TLongObjectHashMap (gnu.trove.map.hash.TLongObjectHashMap)11 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)11 JDAImpl (net.dv8tion.jda.internal.JDAImpl)11 EntityBuilder (net.dv8tion.jda.internal.entities.EntityBuilder)11 RestActionImpl (net.dv8tion.jda.internal.requests.RestActionImpl)11 UnlockHook (net.dv8tion.jda.internal.utils.UnlockHook)11 GuildImpl (net.dv8tion.jda.internal.entities.GuildImpl)10 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)9 Guild (net.dv8tion.jda.api.entities.Guild)9 ParsingException (net.dv8tion.jda.api.exceptions.ParsingException)9