Skip to content

Commit

Permalink
feat(command): Completed LevelUpRole implementation (#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
Seb committed Apr 13, 2022
1 parent 47d0e32 commit e2636e4
Show file tree
Hide file tree
Showing 3 changed files with 253 additions and 10 deletions.
208 changes: 208 additions & 0 deletions src/main/java/de/voidtech/gerald/commands/utils/ExperienceCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package main.java.de.voidtech.gerald.commands.utils;

import java.awt.Color;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import main.java.de.voidtech.gerald.annotations.Command;
import main.java.de.voidtech.gerald.commands.AbstractCommand;
import main.java.de.voidtech.gerald.commands.CommandCategory;
import main.java.de.voidtech.gerald.commands.CommandContext;
import main.java.de.voidtech.gerald.entities.Experience;
import main.java.de.voidtech.gerald.entities.LevelUpRole;
import main.java.de.voidtech.gerald.entities.Server;
import main.java.de.voidtech.gerald.service.ExperienceService;
import main.java.de.voidtech.gerald.service.ServerService;
import main.java.de.voidtech.gerald.util.ParsingUtils;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.MessageEmbed;

@Command
public class ExperienceCommand extends AbstractCommand {

@Autowired
private ServerService serverService;

@Autowired
private ExperienceService xpService;

@Override
public void executeInternal(CommandContext context, List<String> args) {
Server server = serverService.getServer(context.getGuild().getId());
if (args.isEmpty()) sendLevelCard(context.getChannel(), context.getMember(), server.getId());
else {
String ID = ParsingUtils.filterSnowflake(args.get(0));
if (ParsingUtils.isSnowflake(ID)) {
Member mentionedMember = context.getGuild().getMemberById(ID);
if (mentionedMember == null) context.getChannel().sendMessage("**You need to mention another member to see their XP!**").queue();
else sendLevelCard(context.getChannel(), mentionedMember, server.getId());
} else {
switch (args.get(0)) {
case "levels":
showAllLevelRoles(context.getChannel(), server, context.getGuild());
break;
case "addrole":
addLevelUpRole(context.getChannel(), args, server);
break;
case "removerole":
removeLevelUpRole(context.getChannel(), args, server);
break;
}
}
}
}

private void addLevelUpRole(MessageChannel channel, List<String> args, Server server) {
if (args.size() < 3) {
channel.sendMessage("**You need to supply more arguments! Make sure you have a level and a role mention or ID!**").queue();
return;
}

String level = args.get(1);
if (!ParsingUtils.isInteger(level)) {
channel.sendMessage("**You need to provide a valid number for the level!**").queue();
return;
}

if (xpService.serverHasRoleForLevel(server.getId(), Integer.parseInt(level))) {
channel.sendMessage("**There is already a role set up for this level!**").queue();
return;
}

String roleID = ParsingUtils.filterSnowflake(args.get(2));
if (!ParsingUtils.isSnowflake(roleID)) {
channel.sendMessage("**Please provide a valid role mention or role ID**").queue();
return;
}

Guild guild = channel.getJDA().getGuildById(server.getGuildID());
if (guild.getRoleById(roleID) == null) {
channel.sendMessage("**Please provide a valid role mention or role ID**").queue();
return;
}

LevelUpRole role = new LevelUpRole(roleID, server.getId(), Integer.parseInt(level));
xpService.saveLevelUpRole(role);
MessageEmbed newRoleEmbed = new EmbedBuilder()
.setColor(Color.ORANGE)
.setTitle("Added Level Up Role!")
.setDescription("Level: `" + level + "`\nRole: <@&" + roleID + ">")
.build();
channel.sendMessageEmbeds(newRoleEmbed).queue();
}

private void removeLevelUpRole(MessageChannel channel, List<String> args, Server server) {
if (args.size() < 2) {
channel.sendMessage("**You need to provide a level to remove the role from!**").queue();
return;
}

String level = args.get(1);
if (!ParsingUtils.isInteger(level)) {
channel.sendMessage("**You need to provide a valid number for the level!**").queue();
return;
}

if (!xpService.serverHasRoleForLevel(server.getId(), Integer.parseInt(level))) {
channel.sendMessage("**There isn't a role set up for this level!**").queue();
return;
}

xpService.removeLevelUpRole(Integer.parseInt(level), server.getId());
MessageEmbed roleDeletedEmbed = new EmbedBuilder()
.setColor(Color.ORANGE)
.setTitle("Removed Level Up Role!")
.setDescription("Role for level `" + level + "` has been removed")
.build();
channel.sendMessageEmbeds(roleDeletedEmbed).queue();
}

private void showAllLevelRoles(MessageChannel channel, Server server, Guild guild) {
List<LevelUpRole> levelUpRoles = xpService.getAllLevelUpRolesForServer(server.getId());
if (levelUpRoles.isEmpty())
channel.sendMessage("**There are no level roles set up in this server! See the help page for more info!**").queue();
else {
String roleMessage = "";
for (LevelUpRole role : levelUpRoles) {
roleMessage += "`" + role.getLevel() + "` - " + "<@&" + role.getRoleID() + ">\n";
}
MessageEmbed levelRolesEmbed = new EmbedBuilder()
.setColor(Color.ORANGE)
.setTitle("Level up roles for " + guild.getName())
.setDescription(roleMessage)
.build();
channel.sendMessageEmbeds(levelRolesEmbed).queue();
}
}

private void sendLevelCard(MessageChannel channel, Member member, long serverID) {
Experience userXP = xpService.getUserExperience(member.getId(), serverID);
MessageEmbed experienceEmbed = new EmbedBuilder()
.setColor(member.getColorRaw())
.setThumbnail(member.getEffectiveAvatarUrl())
.setTitle(member.getUser().getName() + "'s Experience")
.setDescription("**Level:** `" + userXP.getLevel() +
"`\n**XP towards next level:** `" + userXP.getCurrentExperience() +
"`\n**XP Needed for next level:** `" + xpService.xpNeededForLevel(userXP.getLevel() + 1) + "`")
.build();
channel.sendMessageEmbeds(experienceEmbed).queue();
}

@Override
public String getDescription() {
return "You know the drill, the more messages you send, the more experience you gain!\n"
+ "You can gain up to 15 experience per minute.\n"
+ "Server admins can configure roles that are given to you when you reach a certain level.\n"
+ "To stop people from checking their XP, you can disable the XP command.\n"
+ "If you want to stop people from gaining XP, disable the r-xp routine.";
}

@Override
public String getUsage() {
return "xp\n"
+ "xp levels\n"
+ "xp addrole [level] [role]\n"
+ "xp removerole [level]\n"
+ "xp leaderboard";
}

@Override
public String getName() {
return "xp";
}

@Override
public CommandCategory getCommandCategory() {
return CommandCategory.UTILS;
}

@Override
public boolean isDMCapable() {
return false;
}

@Override
public boolean requiresArguments() {
return false;
}

@Override
public String[] getCommandAliases() {
return new String[] {"level", "rank"};
}

@Override
public boolean canBeDisabled() {
return true;
}

@Override
public boolean isSlashCompatible() {
return false;
}

}
2 changes: 1 addition & 1 deletion src/main/java/de/voidtech/gerald/entities/Experience.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public Experience(String userID, long serverID) {
this.userID = userID;
this.serverID = serverID;
this.messageCount = 0;
this.level = 1;
this.level = 0;
this.lastMessageTime = 0;
this.experienceGainedToNextLevel = 0;
}
Expand Down
53 changes: 44 additions & 9 deletions src/main/java/de/voidtech/gerald/service/ExperienceService.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class ExperienceService {

private static final int EXPERIENCE_DELAY = 0; //Delay between incrementing XP in seconds

private Experience getUserExperience(String userID, long serverID) {
public Experience getUserExperience(String userID, long serverID) {
try(Session session = sessionFactory.openSession())
{
Experience xp = (Experience) session.createQuery("FROM Experience WHERE userID = :userID AND serverID = :serverID")
Expand Down Expand Up @@ -57,7 +57,7 @@ private ServerExperienceConfig getServerExperienceConfig(long serverID) {
}
}

private List<LevelUpRole> getRolesForLevel(long id, long level) {
private List<LevelUpRole> getRolesForLevelFromServer(long id, long level) {
try(Session session = sessionFactory.openSession())
{
@SuppressWarnings("unchecked")
Expand All @@ -69,6 +69,28 @@ private List<LevelUpRole> getRolesForLevel(long id, long level) {
}
}

public List<LevelUpRole> getAllLevelUpRolesForServer(long id) {
try(Session session = sessionFactory.openSession())
{
@SuppressWarnings("unchecked")
List<LevelUpRole> roles = (List<LevelUpRole>) session.createQuery("FROM LevelUpRole WHERE serverID = :serverID")
.setParameter("serverID", id)
.list();
return roles;
}
}

public boolean serverHasRoleForLevel(long id, long level) {
try(Session session = sessionFactory.openSession())
{
LevelUpRole role = (LevelUpRole) session.createQuery("FROM LevelUpRole WHERE serverID = :serverID AND level = :level")
.setParameter("serverID", id)
.setParameter("level", level)
.uniqueResult();
return role != null;
}
}

private void saveUserExperience(Experience userXP) {
try(Session session = sessionFactory.openSession())
{
Expand All @@ -87,22 +109,35 @@ private void saveServerExperienceConfig(ServerExperienceConfig config) {
}
}

public void saveLevelUpRole(LevelUpRole role) {
try(Session session = sessionFactory.openSession())
{
session.getTransaction().begin();
session.saveOrUpdate(role);
session.getTransaction().commit();
}
}


private void removeLevelUpRole(LevelUpRole role) {
public void removeLevelUpRole(long level, long serverID) {
try(Session session = sessionFactory.openSession())
{
session.getTransaction().begin();
session.createQuery("DELETE FROM LevelUpRole WHERE roleID = :roleID AND serverID = :serverID")
.setParameter("roleID", role.getRoleID())
.setParameter("serverID", role.getServerID())
session.createQuery("DELETE FROM LevelUpRole WHERE level = :level AND serverID = :serverID")
.setParameter("level", level)
.setParameter("serverID", serverID)
.executeUpdate();
session.getTransaction().commit();
}
}

public long xpNeededForLevel(long level) {
return 5 * (level ^ 2) + (50 * level) + 100;
}

private long xpToNextLevel(long currentLevel, long currentXP) {
long nextLevel = currentLevel + 1;
return 5 * (nextLevel ^ 2) + (50 * nextLevel) + 100 - currentXP;
return xpNeededForLevel(nextLevel) - currentXP;
}

private int generateExperience() {
Expand Down Expand Up @@ -136,14 +171,14 @@ public void updateUserExperience(Member member, String guildID, String channelID
private void performLevelUpActions(Experience userXP, Server server, Member member, String channelID) {
ServerExperienceConfig config = getServerExperienceConfig(server.getId());

List<LevelUpRole> roles = getRolesForLevel(server.getId(), userXP.getLevel());
List<LevelUpRole> roles = getRolesForLevelFromServer(server.getId(), userXP.getLevel());
if (roles.isEmpty()) return;

List<Role> memberRoles = member.getRoles();

for (LevelUpRole role : roles) {
Role roleToBeGiven = member.getGuild().getRoleById(role.getRoleID());
if (roleToBeGiven == null) removeLevelUpRole(role);
if (roleToBeGiven == null) removeLevelUpRole(role.getLevel(), role.getServerID());
else {
if (!memberRoles.contains(roleToBeGiven)) {
member.getGuild().addRoleToMember(member, roleToBeGiven).complete();
Expand Down

0 comments on commit e2636e4

Please sign in to comment.