Search in sources :

Example 1 with RoleReward

use of at.xirado.bean.misc.objects.RoleReward in project Bean by Xirado.

the class GuildMemberJoinListener method onGuildMemberJoin.

@Override
public void onGuildMemberJoin(@NotNull GuildMemberJoinEvent event) {
    if (GuildJoinListener.isGuildBanned(event.getGuild().getIdLong()))
        return;
    if (!event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_ROLES))
        return;
    GuildData guildData = GuildManager.getGuildData(event.getGuild());
    Bean.getInstance().getScheduledExecutor().schedule(() -> {
        long totalXP = RankingSystem.getTotalXP(event.getGuild().getIdLong(), event.getUser().getIdLong());
        int level = RankingSystem.getLevel(totalXP);
        if (level > 0) {
            List<RoleReward> roleRewards = guildData.getEffectiveRoleRewards(level);
            Set<Role> rolesToAdd = new HashSet<>(event.getMember().getRoles());
            for (RoleReward reward : roleRewards) {
                if (reward.isPersistant()) {
                    Role role = event.getGuild().getRoleById(reward.getRoleId());
                    if (role != null && event.getGuild().getSelfMember().canInteract(role))
                        rolesToAdd.add(role);
                }
            }
            if (!rolesToAdd.isEmpty())
                event.getGuild().modifyMemberRoles(event.getMember(), rolesToAdd).queue();
        }
    }, 10, TimeUnit.SECONDS);
}
Also used : Role(net.dv8tion.jda.api.entities.Role) GuildData(at.xirado.bean.data.GuildData) RoleReward(at.xirado.bean.misc.objects.RoleReward) HashSet(java.util.HashSet)

Example 2 with RoleReward

use of at.xirado.bean.misc.objects.RoleReward 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 3 with RoleReward

use of at.xirado.bean.misc.objects.RoleReward in project Bean by Xirado.

the class GuildData method getEffectiveRoleRewards.

/**
 * Returns a {@link Set Set} of {@link RoleReward RoleRewards} that should be applied to a member with a given level.
 * This is not the same as {@link #getAllRoleRewardsUpTo(int)}!
 *
 * @param level The level
 * @return A Set of RoleRewards
 */
public List<RoleReward> getEffectiveRoleRewards(int level) {
    List<RoleReward> rewardList = new ArrayList<>(getAllRoleRewardsUpTo(level));
    if (rewardList.isEmpty())
        return Collections.emptyList();
    rewardList.sort(Comparator.comparingInt(RoleReward::getLevel));
    List<RoleReward> result = new ArrayList<>();
    RoleReward previous = null;
    for (RoleReward reward : rewardList) {
        if (previous != null && previous.doesRemoveOnNextReward()) {
            result.remove(previous);
        }
        result.add(reward);
        previous = reward;
    }
    return result;
}
Also used : RoleReward(at.xirado.bean.misc.objects.RoleReward)

Example 4 with RoleReward

use of at.xirado.bean.misc.objects.RoleReward in project Bean by Xirado.

the class GuildData method getLastRoleReward.

public RoleReward getLastRoleReward(int starting) {
    if (starting < 1)
        return null;
    List<RoleReward> rewards = getRoleRewards();
    AtomicInteger integer = new AtomicInteger(starting);
    while (integer.get() > 0) {
        RoleReward reward = rewards.stream().filter(reward1 -> reward1.getLevel() == integer.get()).findFirst().orElse(null);
        if (reward != null)
            return reward;
        integer.decrementAndGet();
    }
    return null;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RoleReward(at.xirado.bean.misc.objects.RoleReward)

Example 5 with RoleReward

use of at.xirado.bean.misc.objects.RoleReward 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)

Aggregations

RoleReward (at.xirado.bean.misc.objects.RoleReward)6 DataArray (net.dv8tion.jda.api.utils.data.DataArray)3 GuildData (at.xirado.bean.data.GuildData)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 CheckReturnValue (javax.annotation.CheckReturnValue)2 Role (net.dv8tion.jda.api.entities.Role)2 DataObject (net.dv8tion.jda.api.utils.data.DataObject)2 Bean (at.xirado.bean.Bean)1 SQLBuilder (at.xirado.bean.data.database.SQLBuilder)1 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 java.util (java.util)1 HashSet (java.util.HashSet)1 Collectors (java.util.stream.Collectors)1 Permission (net.dv8tion.jda.api.Permission)1 net.dv8tion.jda.api.entities (net.dv8tion.jda.api.entities)1 InsufficientPermissionException (net.dv8tion.jda.api.exceptions.InsufficientPermissionException)1 Checks (net.dv8tion.jda.internal.utils.Checks)1 CollectionUtils (org.apache.commons.collections4.CollectionUtils)1 Logger (org.slf4j.Logger)1