Add initial code
This commit is contained in:
parent
8d1ffd7bfd
commit
5c71558469
21 changed files with 4733 additions and 30 deletions
|
|
@ -4,13 +4,13 @@ import com.google.gson.Gson;
|
|||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
|
||||
//You can add more fields in this class, if your input json matches the structure
|
||||
//You will need a valid config.json in the package com.freya02.bot for this to work
|
||||
public class Config {
|
||||
@SuppressWarnings("unused") private String token;
|
||||
@SuppressWarnings("unused") private DBConfig dbConfig;
|
||||
@SuppressWarnings("unused") private String prefix;
|
||||
@SuppressWarnings("unused") private DBConfig mariadb;
|
||||
|
||||
/**
|
||||
* Returns the configuration object for this bot
|
||||
|
|
@ -19,18 +19,18 @@ public class Config {
|
|||
* @throws IOException if the config JSON could not be read
|
||||
*/
|
||||
public static Config readConfig() throws IOException {
|
||||
System.out.println(Path.of("config.json"));
|
||||
try (InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("config.json")) {
|
||||
assert in != null;
|
||||
Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
|
||||
return new Gson().fromJson(reader, Config.class);
|
||||
} catch (IOException e) {
|
||||
throw new IOException("""
|
||||
config.json was not found in the root folder (of the project), did you forget to put it ?
|
||||
config.json was not found in the root folder (of the project), did you forget to create it ?
|
||||
Example structure:
|
||||
|
||||
{
|
||||
"token": "[your_bot_token_here]"
|
||||
"token": "[your_bot_token_here]",
|
||||
"prefix": "!"
|
||||
}
|
||||
""", e);
|
||||
}
|
||||
|
|
@ -39,17 +39,19 @@ public class Config {
|
|||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
public String getPrefix() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
public DBConfig getDbConfig() {
|
||||
return dbConfig;
|
||||
return mariadb;
|
||||
}
|
||||
|
||||
public static class DBConfig {
|
||||
@SuppressWarnings("unused") private String serverName, user, password, dbName;
|
||||
@SuppressWarnings("unused") private int portNumber;
|
||||
@SuppressWarnings("unused") private String host, user, password, database;
|
||||
|
||||
public String getServerName() {
|
||||
return serverName;
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
|
|
@ -60,12 +62,8 @@ public class Config {
|
|||
return password;
|
||||
}
|
||||
|
||||
public String getDbName() {
|
||||
return dbName;
|
||||
}
|
||||
|
||||
public int getPortNumber() {
|
||||
return portNumber;
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,8 @@ import net.dv8tion.jda.api.JDA;
|
|||
import net.dv8tion.jda.api.JDABuilder;
|
||||
import net.dv8tion.jda.api.entities.*;
|
||||
import net.dv8tion.jda.api.requests.GatewayIntent;
|
||||
import net.hypr.doki.listeners.LevellingListener;
|
||||
import org.apache.commons.dbcp2.BasicDataSource;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
|
|
@ -14,22 +16,24 @@ public class Doki {
|
|||
private static final Logger LOGGER = Logging.getLogger();
|
||||
private static JDA jda;
|
||||
private static Config config;
|
||||
private static String prefix;
|
||||
private static final BasicDataSource dataSource = new BasicDataSource();
|
||||
|
||||
|
||||
private Doki(JDA jda, Config config) {
|
||||
Doki.jda = jda;
|
||||
Doki.config = config;
|
||||
Doki.prefix = config.getPrefix();
|
||||
}
|
||||
|
||||
public JDA getJDA() {
|
||||
return jda;
|
||||
}
|
||||
|
||||
public static Doki start() throws IOException, InterruptedException {
|
||||
@SuppressWarnings("InstantiationOfUtilityClass")
|
||||
private static void start() throws IOException, InterruptedException {
|
||||
config = Config.readConfig();
|
||||
|
||||
final JDA jda = JDABuilder.createLight(config.getToken())
|
||||
.setActivity(Activity.customStatus("Banned from everywhere"))
|
||||
.enableIntents(GatewayIntent.MESSAGE_CONTENT)
|
||||
.addEventListeners(new LevellingListener())
|
||||
.build()
|
||||
.awaitReady();
|
||||
|
||||
|
|
@ -39,16 +43,34 @@ public class Doki {
|
|||
for (Guild guild : jda.getGuildCache()) {
|
||||
LOGGER.info("\t- {} ({})", guild.getName(), guild.getId());
|
||||
}
|
||||
LOGGER.info("Registered prefix: " + config.getPrefix());
|
||||
|
||||
return new Doki(jda, config);
|
||||
Config.DBConfig dbConfig = config.getDbConfig();
|
||||
dataSource.setDriverClassName("org.mariadb.jdbc.Driver");
|
||||
dataSource.setUrl("jdbc:mariadb://" + dbConfig.getHost() + "/" + dbConfig.getDatabase());
|
||||
dataSource.setUsername(dbConfig.getUser());
|
||||
dataSource.setPassword(dbConfig.getPassword());
|
||||
dataSource.setMaxTotal(15);
|
||||
dataSource.setMaxIdle(5);
|
||||
dataSource.setMinIdle(2);
|
||||
dataSource.setInitialSize(20);
|
||||
|
||||
new Doki(jda, config);
|
||||
}
|
||||
|
||||
public static BasicDataSource getDataSource() { return dataSource; }
|
||||
|
||||
public static JDA getJDA() { return jda; }
|
||||
|
||||
public static String getPrefix() { return prefix; }
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
jda = start().getJDA();
|
||||
start();
|
||||
jda = getJDA();
|
||||
CommandsBuilder.newBuilder(437970062922612737L)
|
||||
.textCommandBuilder(textCommandsBuilder -> textCommandsBuilder.addPrefix("oki!"))
|
||||
.build(jda, "net.hypr.doki.commands"); //Registering listeners is taken care of by the lib
|
||||
.textCommandBuilder(textCommandsBuilder -> textCommandsBuilder.addPrefix(config.getPrefix()))
|
||||
.build(jda, "net.hypr.doki.commands");
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Unable to start the bot", e);
|
||||
System.exit(-1);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package net.hypr.doki.commands;
|
||||
|
||||
import com.freya02.botcommands.api.annotations.CommandMarker;
|
||||
import com.freya02.botcommands.api.prefixed.CommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.TextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Category;
|
||||
|
|
@ -11,10 +12,11 @@ import net.dv8tion.jda.api.entities.SelfUser;
|
|||
|
||||
import java.awt.*;
|
||||
|
||||
@Category("Misc")
|
||||
@CommandMarker
|
||||
@Category("Utils")
|
||||
@Description("Get about info")
|
||||
public class About extends TextCommand {
|
||||
@JDATextCommand(name = "about")
|
||||
@JDATextCommand(name = "about", aliases = {"doki"})
|
||||
public void execute(CommandEvent event) {
|
||||
JDA jda = event.getJDA();
|
||||
SelfUser selfUser = jda.getSelfUser();
|
||||
|
|
|
|||
52
src/main/java/net/hypr/doki/commands/Leaderboard.java
Normal file
52
src/main/java/net/hypr/doki/commands/Leaderboard.java
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
package net.hypr.doki.commands;
|
||||
|
||||
import com.freya02.botcommands.api.annotations.CommandMarker;
|
||||
import com.freya02.botcommands.api.prefixed.CommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.TextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Category;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Description;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.JDATextCommand;
|
||||
import net.dv8tion.jda.api.EmbedBuilder;
|
||||
import net.hypr.doki.utils.DBUtils;
|
||||
import net.hypr.doki.utils.UserRecord;
|
||||
|
||||
import java.awt.*;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
@CommandMarker
|
||||
@Category("Levelling")
|
||||
@Description("Get the global leaderboard")
|
||||
public class Leaderboard extends TextCommand {
|
||||
@JDATextCommand(name = "leaderboard", order = 1, aliases = { "lb" })
|
||||
public void execute(CommandEvent event) throws SQLException {
|
||||
List<UserRecord> userRecords = DBUtils.getAllUserRecords(event.getGuild().getIdLong());
|
||||
// Sort the leaderboard highest level first
|
||||
userRecords.sort((o1, o2) -> o2.totalXp - o1.totalXp);
|
||||
EmbedBuilder whoIsEmbed = buildLeaderboardEmbed(userRecords, event);
|
||||
event.reply(whoIsEmbed.build()).queue();
|
||||
}
|
||||
|
||||
private EmbedBuilder buildLeaderboardEmbed(List<UserRecord> userRecords , CommandEvent event) {
|
||||
StringBuilder leaderboard = new StringBuilder();
|
||||
int idx = 1;
|
||||
for (UserRecord record : userRecords) {
|
||||
leaderboard
|
||||
.append("**")
|
||||
.append(idx)
|
||||
.append(".** ")
|
||||
.append(record.username)
|
||||
.append(" - ")
|
||||
.append(record.level)
|
||||
.append(" (")
|
||||
.append(record.totalXp)
|
||||
.append(" Total XP)\n");
|
||||
idx += 1;
|
||||
if (idx > 10) break; // Break out after 10 records is reached
|
||||
}
|
||||
return new EmbedBuilder()
|
||||
.setTitle(event.getGuild().getName() + " Leaderboard")
|
||||
.setDescription(leaderboard)
|
||||
.setColor(new Color(210,138,39));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +1,14 @@
|
|||
package net.hypr.doki.commands;
|
||||
|
||||
import com.freya02.botcommands.api.annotations.CommandMarker;
|
||||
import com.freya02.botcommands.api.prefixed.CommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.TextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Category;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Description;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.JDATextCommand;
|
||||
|
||||
@Category("Misc")
|
||||
@CommandMarker
|
||||
@Category("Utils")
|
||||
@Description("Pong!")
|
||||
public class Ping extends TextCommand {
|
||||
@JDATextCommand(name = "ping")
|
||||
|
|
|
|||
46
src/main/java/net/hypr/doki/commands/Rank.java
Normal file
46
src/main/java/net/hypr/doki/commands/Rank.java
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
package net.hypr.doki.commands;
|
||||
|
||||
import com.freya02.botcommands.api.annotations.CommandMarker;
|
||||
import com.freya02.botcommands.api.prefixed.BaseCommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.CommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.TextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Category;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Description;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.JDATextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.TextOption;
|
||||
import net.dv8tion.jda.api.EmbedBuilder;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import net.hypr.doki.utils.DBUtils;
|
||||
import net.hypr.doki.utils.UserRecord;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
@CommandMarker
|
||||
@Category("Levelling")
|
||||
@Description("Get a user's rank")
|
||||
public class Rank extends TextCommand {
|
||||
@JDATextCommand(name = "rank", order = 1)
|
||||
public void execute(BaseCommandEvent event, @TextOption Member member) throws SQLException {
|
||||
UserRecord userRecord = DBUtils.getUserRecord(member.getIdLong(), event.getGuild().getIdLong());
|
||||
EmbedBuilder rankEmbed = buildRankEmbed(member, userRecord);
|
||||
event.reply(rankEmbed.build()).queue();
|
||||
}
|
||||
|
||||
@JDATextCommand(name = "rank", order = 2)
|
||||
public void execute(CommandEvent event) throws SQLException {
|
||||
UserRecord userRecord = DBUtils.getUserRecord(event.getMember().getIdLong(), event.getGuild().getIdLong());
|
||||
EmbedBuilder whoIsEmbed = buildRankEmbed(event.getMember(), userRecord);
|
||||
event.reply(whoIsEmbed.build()).queue();
|
||||
}
|
||||
|
||||
private EmbedBuilder buildRankEmbed(Member user, UserRecord userRecord) {
|
||||
int xpToNextLevel = (((userRecord.level + 1) * 5) * 40) - userRecord.xp;
|
||||
return new EmbedBuilder()
|
||||
.setAuthor(user.getUser().getName(), null, user.getEffectiveAvatarUrl())
|
||||
.setThumbnail(user.getEffectiveAvatarUrl())
|
||||
.addField("Level", String.valueOf(userRecord.level), true)
|
||||
.addField("XP", String.valueOf(userRecord.xp), true)
|
||||
.addField("XP Until level " + (userRecord.level + 1), String.valueOf(xpToNextLevel), true)
|
||||
.setColor(user.getColor());
|
||||
}
|
||||
}
|
||||
63
src/main/java/net/hypr/doki/commands/WhoIs.java
Normal file
63
src/main/java/net/hypr/doki/commands/WhoIs.java
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
package net.hypr.doki.commands;
|
||||
|
||||
import com.freya02.botcommands.api.annotations.CommandMarker;
|
||||
import com.freya02.botcommands.api.prefixed.BaseCommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.CommandEvent;
|
||||
import com.freya02.botcommands.api.prefixed.TextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Category;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.Description;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.JDATextCommand;
|
||||
import com.freya02.botcommands.api.prefixed.annotations.TextOption;
|
||||
import net.dv8tion.jda.api.EmbedBuilder;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import net.dv8tion.jda.api.entities.Role;
|
||||
import net.dv8tion.jda.api.entities.User;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@CommandMarker
|
||||
@Category("Utils")
|
||||
@Description("Get information about a user")
|
||||
public class WhoIs extends TextCommand {
|
||||
@JDATextCommand(name = "whois", order = 1)
|
||||
public void execute(BaseCommandEvent event, @TextOption(example = "<@437970062922612737>") Member user) {
|
||||
EmbedBuilder whoIsEmbed = buildUserEmbed(user, (CommandEvent) event);
|
||||
event.reply(whoIsEmbed.build()).queue();
|
||||
}
|
||||
|
||||
@JDATextCommand(name = "whois", order = 2)
|
||||
public void execute(BaseCommandEvent event, @TextOption(example = "<@437970062922612737>") User user) {
|
||||
EmbedBuilder whoIsEmbed = buildUserEmbed((Member) user, (CommandEvent) event);
|
||||
event.reply(whoIsEmbed.build()).queue();
|
||||
}
|
||||
|
||||
@JDATextCommand(name = "whois", order = 3)
|
||||
public void execute(CommandEvent event) {
|
||||
EmbedBuilder whoIsEmbed = buildUserEmbed(event.getMember(), event);
|
||||
event.reply(whoIsEmbed.build()).queue();
|
||||
}
|
||||
|
||||
private EmbedBuilder buildUserEmbed(Member user, CommandEvent event) {
|
||||
return new EmbedBuilder()
|
||||
.setAuthor(user.getUser().getName(), null, user.getEffectiveAvatarUrl())
|
||||
.setThumbnail(user.getEffectiveAvatarUrl())
|
||||
.addField("Information",
|
||||
"**Mention:** " + user.getAsMention() +
|
||||
"\n**ID:** " + user.getId(), true)
|
||||
.addField("Joined",
|
||||
"**Discord:** " +
|
||||
Duration.between(user.getTimeCreated(), OffsetDateTime.now()).toDays() + " days ago\n" +
|
||||
"**->** <t:" + user.getTimeCreated().toEpochSecond() + ":f>\n**Guild:** " +
|
||||
Duration.between(user.getTimeJoined(), OffsetDateTime.now()).toDays() + " days ago\n" +
|
||||
"**->** <t:" + user.getTimeJoined().toEpochSecond() + ":f>", true)
|
||||
.addField("Guild-Specific",
|
||||
"**Nickname:** " + user.getNickname() + "\n**Roles (" + ((long) user.getRoles().size() + 1) + "):** `@everyone`, " +
|
||||
user.getRoles().stream().map(Role::getAsMention)
|
||||
.collect(Collectors.joining(", ")) +
|
||||
"\n**Owner:**" + (user.isOwner() ? "Yes" : "No"), false)
|
||||
.addField("Guild", event.getGuild().getName(), false)
|
||||
.setColor(user.getColor());
|
||||
}
|
||||
}
|
||||
64
src/main/java/net/hypr/doki/listeners/LevellingListener.java
Normal file
64
src/main/java/net/hypr/doki/listeners/LevellingListener.java
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package net.hypr.doki.listeners;
|
||||
|
||||
import com.freya02.botcommands.api.Logging;
|
||||
import net.dv8tion.jda.api.entities.Guild;
|
||||
import net.dv8tion.jda.api.entities.User;
|
||||
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
|
||||
import net.dv8tion.jda.api.hooks.ListenerAdapter;
|
||||
import net.hypr.doki.Doki;
|
||||
import net.hypr.doki.utils.DBUtils;
|
||||
import net.hypr.doki.utils.LevellingUtils;
|
||||
import net.hypr.doki.utils.UserRecord;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class LevellingListener extends ListenerAdapter {
|
||||
@Override
|
||||
public void onMessageReceived(MessageReceivedEvent event) {
|
||||
Logger log = Logging.getLogger();
|
||||
/* Ignore the message if one of the following conditions is met:
|
||||
- Message is from self user
|
||||
- Message is from bot
|
||||
- Message is command (starts with bot prefix)
|
||||
*/
|
||||
if (
|
||||
Doki.getJDA().getSelfUser().getId().equals(event.getAuthor().getId()) ||
|
||||
event.getAuthor().isBot() ||
|
||||
event.getMessage().getContentStripped().startsWith(Doki.getPrefix())
|
||||
) {
|
||||
log.debug("Ignoring self/bot message with ID " + event.getMessageId());
|
||||
return;
|
||||
}
|
||||
|
||||
User user = event.getAuthor();
|
||||
Guild guild = event.getGuild();
|
||||
boolean userIsInDb = DBUtils.doesUserRecordExist(user.getIdLong(), guild.getIdLong());
|
||||
if (userIsInDb) {
|
||||
try {
|
||||
UserRecord rec = DBUtils.getUserRecord(user.getIdLong(), guild.getIdLong());
|
||||
Duration timeSinceLastMessage = Duration.between(
|
||||
rec.lastMessage.toLocalDateTime(),
|
||||
LocalDateTime.now()
|
||||
);
|
||||
if (timeSinceLastMessage.compareTo(Duration.ofHours(1)) > 0) {
|
||||
// it has been over an hour since the user last sent a message that affected XP
|
||||
LevellingUtils.incrementXp(log, rec);
|
||||
} else {
|
||||
log.debug("Ignoring message ID " + event.getMessageId() + " as not enough time has passed");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} else {
|
||||
log.info("No record of user ID " + user.getId() + " in server " + guild.getId() + ", creating blank record");
|
||||
try {
|
||||
DBUtils.createUserRecord(user.getIdLong(), guild.getIdLong(), user.getName());
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
157
src/main/java/net/hypr/doki/utils/DBUtils.java
Normal file
157
src/main/java/net/hypr/doki/utils/DBUtils.java
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
package net.hypr.doki.utils;
|
||||
|
||||
import com.freya02.botcommands.api.Logging;
|
||||
import net.hypr.doki.Doki;
|
||||
import org.apache.commons.dbcp2.BasicDataSource;
|
||||
import org.apache.commons.dbutils.QueryRunner;
|
||||
import org.apache.commons.dbutils.ResultSetHandler;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.sql.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class DBUtils {
|
||||
/**
|
||||
* Checks if the user record exists
|
||||
* @param user_id User ID to search for
|
||||
* @param server_id Server ID to search for
|
||||
* @return Whether the record exists or not
|
||||
*/
|
||||
public static boolean doesUserRecordExist(long user_id, long server_id) {
|
||||
Logger log = Logging.getLogger();
|
||||
BasicDataSource dataSource = Doki.getDataSource();
|
||||
QueryRunner qr = new QueryRunner(dataSource);
|
||||
ResultSetHandler<Set<BigInteger>> resultSetHandler = rs -> {
|
||||
Set<BigInteger> rows = new HashSet<>();
|
||||
while (rs.next()) {
|
||||
rows.add(BigInteger.valueOf(rs.getLong(1)));
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
|
||||
// Find out if the user is already in the DB
|
||||
try {
|
||||
log.debug("Searching DB for (usr" + user_id + ",srv:" + server_id + ")");
|
||||
Set<BigInteger> foundIds = qr.query("SELECT user_id FROM users WHERE user_id = " + user_id + " AND server_id = " + server_id, resultSetHandler);
|
||||
log.debug("Matching records: " + foundIds.size());
|
||||
return !foundIds.isEmpty();
|
||||
} catch (SQLException ignored) {
|
||||
log.debug("An SQL error occurred");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new user record
|
||||
* @param user_id The users ID
|
||||
* @param server_id The server ID
|
||||
* @param username The users username
|
||||
* @throws SQLException A SQL exception
|
||||
*/
|
||||
public static void createUserRecord(long user_id, long server_id, String username) throws SQLException {
|
||||
Logger log = Logging.getLogger();
|
||||
log.info("Creating record (usr:" + user_id + ",srv:" + server_id + ",unm:" + username + ")");
|
||||
BasicDataSource dataSource = Doki.getDataSource();
|
||||
Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"INSERT INTO users (user_id, server_id, username, last_message) VALUES (?, ?, ?, ?)"
|
||||
);
|
||||
stmt.setLong(1, user_id);
|
||||
stmt.setLong(2, server_id);
|
||||
stmt.setString(3, username);
|
||||
stmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));
|
||||
stmt.execute();
|
||||
log.info("Record (usr:" + user_id + ",srv:" + server_id + ",unm:" + username + ") created!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a user record
|
||||
* @param user_id User ID of the record to update
|
||||
* @param server_id Server ID of the record to update
|
||||
* @param now The current time
|
||||
* @param xp The new XP count
|
||||
* @param totalXp The new total XP count
|
||||
* @param level The new level
|
||||
* @throws SQLException A SQL exception
|
||||
*/
|
||||
public static void updateUserRecord(long user_id, long server_id, Timestamp now, int xp, int totalXp, int level) throws SQLException {
|
||||
Logger log = Logging.getLogger();
|
||||
log.info("Updating record (usr:" + user_id + ",srv:" + server_id + ")");
|
||||
BasicDataSource dataSource = Doki.getDataSource();
|
||||
Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"UPDATE users SET last_message = ?, xp = ?, total_xp = ?, level = ? WHERE user_id = ? AND server_id = ?"
|
||||
);
|
||||
stmt.setTimestamp(1, now);
|
||||
stmt.setInt(2, xp);
|
||||
stmt.setInt(3, totalXp);
|
||||
stmt.setInt(4, level);
|
||||
stmt.setLong(5, user_id);
|
||||
stmt.setLong(6, server_id);
|
||||
stmt.executeQuery();
|
||||
log.info("Updated record (usr:" + user_id + ",srv:" + server_id + ")!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a user record
|
||||
* @param user_id The User ID of the record to get
|
||||
* @param server_id The Server ID of the record to get
|
||||
* @return The found UserRecord
|
||||
* @throws SQLException A SQL exception
|
||||
*/
|
||||
public static UserRecord getUserRecord(long user_id, long server_id) throws SQLException {
|
||||
BasicDataSource dataSource = Doki.getDataSource();
|
||||
Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"SELECT user_id, server_id, username, last_message, xp, total_xp, level FROM users WHERE user_id = ? AND server_id = ?"
|
||||
);
|
||||
stmt.setLong(1, user_id);
|
||||
stmt.setLong(2, server_id);
|
||||
ResultSet rs = stmt.executeQuery();
|
||||
rs.next();
|
||||
return new UserRecord(
|
||||
rs.getLong("user_id"),
|
||||
rs.getLong("server_id"),
|
||||
rs.getString("username"),
|
||||
rs.getTimestamp("last_message"),
|
||||
rs.getInt("xp"),
|
||||
rs.getInt("total_xp"),
|
||||
rs.getInt("level")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all user records for a server
|
||||
* @param server_id The Server ID
|
||||
* @return A List of UserRecords
|
||||
* @throws SQLException A SQL exception
|
||||
*/
|
||||
public static List<UserRecord> getAllUserRecords(long server_id) throws SQLException {
|
||||
BasicDataSource dataSource = Doki.getDataSource();
|
||||
Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(
|
||||
"SELECT user_id, username, last_message, xp, total_xp, level FROM users WHERE server_id = ?"
|
||||
);
|
||||
stmt.setLong(1, server_id);
|
||||
ResultSet rs = stmt.executeQuery();
|
||||
List<UserRecord> userRecordList = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
userRecordList.add(new UserRecord(
|
||||
rs.getLong("user_id"),
|
||||
server_id,
|
||||
rs.getString("username"),
|
||||
rs.getTimestamp("last_message"),
|
||||
rs.getInt("xp"),
|
||||
rs.getInt("total_xp"),
|
||||
rs.getInt("level")
|
||||
));
|
||||
}
|
||||
return userRecordList;
|
||||
}
|
||||
}
|
||||
|
||||
35
src/main/java/net/hypr/doki/utils/LevellingUtils.java
Normal file
35
src/main/java/net/hypr/doki/utils/LevellingUtils.java
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package net.hypr.doki.utils;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Random;
|
||||
|
||||
public class LevellingUtils {
|
||||
public static void incrementXp(Logger logger, UserRecord userRecord) throws SQLException {
|
||||
Random random = new Random();
|
||||
// Random increment between 15 and 25
|
||||
int xpInc = (random.nextInt(10) + 16) * 3;
|
||||
int xpNew = userRecord.xp + xpInc;
|
||||
int totalXp = userRecord.xp + xpInc;
|
||||
int levelNew = userRecord.level;
|
||||
if (xpNew >= ((userRecord.level + 1) * 5) * 40) {
|
||||
levelNew ++;
|
||||
xpNew = 0;
|
||||
}
|
||||
DBUtils.updateUserRecord(
|
||||
userRecord.user_id,
|
||||
userRecord.server_id,
|
||||
Timestamp.valueOf(LocalDateTime.now()),
|
||||
xpNew,
|
||||
totalXp,
|
||||
levelNew
|
||||
);
|
||||
logger.info("Incremented " + userRecord.username + "'s XP in " + userRecord.server_id + " (" + userRecord.xp + " -> " + xpNew + ")");
|
||||
if (levelNew > userRecord.level) {
|
||||
logger.info("Incremented " + userRecord.username + "'s level in " + userRecord.server_id + " (" + userRecord.level + " -> " + levelNew + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
49
src/main/java/net/hypr/doki/utils/UserRecord.java
Normal file
49
src/main/java/net/hypr/doki/utils/UserRecord.java
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
package net.hypr.doki.utils;
|
||||
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
public class UserRecord {
|
||||
public final long user_id;
|
||||
public final long server_id;
|
||||
public final String username;
|
||||
public final Timestamp lastMessage;
|
||||
public final int xp;
|
||||
public int totalXp;
|
||||
public final int level;
|
||||
|
||||
/**
|
||||
* Instantiates a new UserRecord
|
||||
* @param user_id The User ID
|
||||
* @param server_id The Server/Guild ID
|
||||
* @param username The Username
|
||||
*/
|
||||
public UserRecord (long user_id, long server_id, String username) {
|
||||
this.user_id = user_id;
|
||||
this.server_id = server_id;
|
||||
this.username = username;
|
||||
this.lastMessage = new Timestamp(0);
|
||||
this.xp = 0;
|
||||
this.level = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new UserRecord
|
||||
* @param user_id The User ID
|
||||
* @param server_id The Server/Guild ID
|
||||
* @param username The Username
|
||||
* @param lastMessage The timestamp of the user's last message
|
||||
* @param xp The user's XP
|
||||
* @param totalXp The user's total XP
|
||||
* @param level The user's level
|
||||
*/
|
||||
public UserRecord (long user_id, long server_id, String username, Timestamp lastMessage, int xp, int totalXp, int level) {
|
||||
this.user_id = user_id;
|
||||
this.server_id = server_id;
|
||||
this.username = username;
|
||||
this.lastMessage = lastMessage;
|
||||
this.xp = xp;
|
||||
this.totalXp = totalXp;
|
||||
this.level = level;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue