Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ae985b0

Browse files
committed
Forget CSV, JSONs where its at.
player data is now stored in a json file instead of a crappy unreadable csv.
1 parent 64e7a9d commit ae985b0

File tree

9 files changed

+147
-65
lines changed

9 files changed

+147
-65
lines changed

players.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
<dependency>
7070
<groupId>io.discloader</groupId>
7171
<artifactId>discloader</artifactId>
72-
<version>0.2.3</version>
72+
<version>0.2.4</version>
7373
</dependency>
7474
</dependencies>
7575
<repositories>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package codekey.level;
2+
3+
import java.io.File;
4+
import java.io.FileWriter;
5+
import java.io.IOException;
6+
import java.nio.file.Files;
7+
import java.util.HashMap;
8+
import java.util.List;
9+
10+
import org.json.JSONObject;
11+
12+
import codekey.main.Main;
13+
import io.discloader.discloader.entity.util.SnowflakeUtil;
14+
15+
public class JSONParser {
16+
public JSONParser(String fileLocation) throws IOException {
17+
File file = new File(fileLocation);
18+
Main.players = new HashMap<>();
19+
if (file.exists() && !file.isDirectory()) {
20+
String content = "";
21+
List<String> lines = Files.readAllLines(file.toPath());
22+
for (String line : lines) {
23+
content += line;
24+
}
25+
JSONObject json = new JSONObject(content);
26+
long playerID = 0l;
27+
for (String key : json.keySet()) {
28+
JSONObject playerJSON = json.getJSONObject(key);
29+
Main.players.put(playerID = SnowflakeUtil.parse(key), new Player(playerID, playerJSON.optDouble("exp", 0)));
30+
Main.players.get(playerID).setLastMsgID(playerJSON.optLong("lastMsgID", 0l));
31+
}
32+
} else if (!file.exists()) {
33+
FileWriter fw = new FileWriter(file);
34+
fw.write(new JSONObject().toString());
35+
fw.close();
36+
}
37+
}
38+
39+
}

src/main/java/codekey/level/Player.java

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ public class Player {
1818
// private final IGuildMember member;
1919
private double exp;
2020
private Rank rank;
21+
private long lastMsgID;
2122

2223
public Player(long id, double exp) {
2324
this.id = id;
@@ -58,17 +59,38 @@ private void checkForNewRank(GuildMessageCreateEvent event) {
5859
Main.logger.info("Attempting to fix Player Rank desync for " + event.getMessage().getMember());
5960
CompletableFuture<IGuildMember> gcf = event.getMessage().getMember().giveRole(newRole);
6061
gcf.thenAcceptAsync(nm -> {
61-
62+
6263
});
6364
}
6465

65-
// if ((rank != Rank.NO_RANK && rank != Rank.UNKNOWN) && !event.getMessage().getMember().hasRole(newRole) && !event.getMessage().getMember().hasRole(event.getGuild().getRoleByID(Rank.STAFF.getID()))) {
66-
// Main.logger.info("Attempting to fix Player Rank desync for " + event.getMessage().getMember());
67-
// CompletableFuture<IGuildMember> gcf = event.getMessage().getMember().giveRole(event.getGuild().getRoleByID(rank.getID()));
68-
// gcf.thenAcceptAsync((nm) -> {
69-
// Main.logger.info("Fixed Player Rank Desync for " + event.getMessage().getMember());
70-
// });
71-
// }
66+
// if ((rank != Rank.NO_RANK && rank != Rank.UNKNOWN) &&
67+
// !event.getMessage().getMember().hasRole(newRole) &&
68+
// !event.getMessage().getMember().hasRole(event.getGuild().getRoleByID(Rank.STAFF.getID())))
69+
// {
70+
// Main.logger.info("Attempting to fix Player Rank desync for " +
71+
// event.getMessage().getMember());
72+
// CompletableFuture<IGuildMember> gcf =
73+
// event.getMessage().getMember().giveRole(event.getGuild().getRoleByID(rank.getID()));
74+
// gcf.thenAcceptAsync((nm) -> {
75+
// Main.logger.info("Fixed Player Rank Desync for " +
76+
// event.getMessage().getMember());
77+
// });
78+
// }
79+
}
80+
81+
/**
82+
* @return the lastMsgID
83+
*/
84+
public long getLastMsgID() {
85+
return lastMsgID;
86+
}
87+
88+
/**
89+
* @param lastMsgID
90+
* the lastMsgID to set
91+
*/
92+
public void setLastMsgID(long lastMsgID) {
93+
this.lastMsgID = lastMsgID;
7294
}
7395

7496
}

src/main/java/codekey/level/SpamThread.java

Lines changed: 0 additions & 26 deletions
This file was deleted.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package codekey.main;
2+
3+
import java.io.FileWriter;
4+
5+
import org.json.JSONObject;
6+
7+
public class JSONThread extends Thread {
8+
@Override
9+
public void run() {
10+
super.run();
11+
setName("JSONThread");
12+
while (!Thread.currentThread().isInterrupted()) {
13+
try {
14+
Thread.sleep(180000);
15+
} catch (InterruptedException e) {
16+
e.printStackTrace();
17+
break;
18+
}
19+
try {
20+
FileWriter fw = new FileWriter(Main.DATABASE_BACKUP);
21+
JSONObject json = new JSONObject(), playerJSON = new JSONObject(); // cache the playerJSON object instead of creating a new one for each player
22+
Main.players.forEach((id, player) -> {
23+
playerJSON.put("lastMsgID", player.getLastMsgID()).put("exp", player.getExp());
24+
json.put(Long.toUnsignedString(id, 10), playerJSON);
25+
});
26+
fw.write(json.toString());
27+
fw.close();
28+
} catch (Exception e) {
29+
e.printStackTrace();
30+
}
31+
}
32+
}
33+
}

src/main/java/codekey/main/Listener.java

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import java.util.List;
99
import java.util.Map;
1010

11+
import org.json.JSONObject;
12+
1113
import codekey.level.Player;
1214
import codekey.level.PlayerUtils;
1315
import io.discloader.discloader.common.event.DisconnectEvent;
@@ -23,8 +25,6 @@
2325
* https://discord.gg/PAH8y8W on 9/22/17.
2426
*/
2527
public class Listener extends EventListenerAdapter {
26-
27-
public static ArrayList<IUser> lastMessage = new ArrayList<>();
2828
/**
2929
* Map of the last time a user was given EXP indexed by the user's
3030
* {@link IUser#getID() id}
@@ -79,7 +79,7 @@ public void GuildMessageCreate(GuildMessageCreateEvent e) {
7979
Main.logger.info("Gave " + author + " " + exp + "EXP");
8080
try {
8181
// Once player gets the new score, update the database file.
82-
writeToCSV();
82+
writeToJSON();
8383
} catch (Exception ex) {
8484
System.out.println("Unable to write file... Dming the creator");
8585
ex.printStackTrace();
@@ -88,7 +88,7 @@ public void GuildMessageCreate(GuildMessageCreateEvent e) {
8888
}
8989
}
9090

91-
private void writeToCSV() throws IOException {
91+
protected void writeToCSV() throws IOException {
9292
BufferedWriter writer = new BufferedWriter(new FileWriter(Main.DATABASE));
9393
List<Player> players = new ArrayList<>(Main.players.values());
9494
for (int i = 0; i < players.size(); i++) {
@@ -99,15 +99,28 @@ private void writeToCSV() throws IOException {
9999
writer.close();
100100
}
101101

102+
protected void writeToJSON() throws IOException {
103+
FileWriter fw = new FileWriter(Main.DATABASE);
104+
JSONObject json = new JSONObject(), playerJSON = new JSONObject(); // cache the playerJSON object instead of creating a new one for each player
105+
Main.players.forEach((id, player) -> {
106+
playerJSON.put("lastMsgID", player.getLastMsgID()).put("exp", player.getExp());
107+
json.put(Long.toUnsignedString(id, 10), playerJSON);
108+
});
109+
fw.write(json.toString());
110+
fw.close();
111+
}
112+
102113
public void Ready(ReadyEvent e) {
103114
Main.logger.info("Codekey is now ready to communicate with Discord");
104115
}
105116

106117
@Override
107118
public void Disconnected(DisconnectEvent e) {
108-
if (e.getClientFrame().getCloseCode() == 1007 || e.getServerFrame().getCloseCode() == 1007) {
109-
System.exit(1);
110-
}
119+
Main.logger.severe("Got disconnected from the gateway");
120+
// if (e.getClientFrame().getCloseCode() == 1007 ||
121+
// e.getServerFrame().getCloseCode() == 1007) {
122+
// System.exit(1);
123+
// }
111124
}
112125

113126
}

src/main/java/codekey/main/Main.java

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@
44
import java.io.FileWriter;
55
import java.io.IOException;
66
import java.nio.file.Files;
7-
import java.nio.file.Paths;
87
import java.util.List;
98
import java.util.Map;
109
import java.util.logging.Logger;
1110

1211
import com.google.gson.Gson;
1312

14-
import codekey.level.CSVParser;
13+
import codekey.level.JSONParser;
1514
import codekey.level.Player;
1615
import codekey.main.commands.CommandStatus;
16+
import io.discloader.discloader.client.command.CommandHelp;
1717
import io.discloader.discloader.client.logger.DLLogger;
1818
import io.discloader.discloader.common.DLOptions;
1919
import io.discloader.discloader.common.DiscLoader;
@@ -26,52 +26,52 @@
2626
public class Main {
2727

2828
public static String token;
29-
public static final String DATABASE = "data.csv";
30-
public static final String DATABASE_BACKUP = "data_backup.csv";
29+
public static final String DATABASE = "players.json";
30+
public static final String DATABASE_BACKUP = "players_backup.json";
3131
// To avoid uploading my token to github, I am going to read it from a file.
32-
private static final String TOKEN_FILE = "token.txt";
33-
// data.csv contains the database.
32+
private static final String CONFIG_FILE = "options.json";
33+
// players.json contains the database.
3434
public static Map<Long, Player> players;
3535
public static DiscLoader loader;
3636

3737
public static final String PREFIX = "~";
3838

39-
4039
public static final Logger logger = new DLLogger("Codekey").getLogger();
4140

42-
public static Config config; // because having to change the PREFIX string every time I upload a new build it annoying
43-
41+
public static Config config; // because having to change the PREFIX string every time I upload a new build it
42+
// annoying
43+
4444
public static void main(String[] args) throws Exception {
4545
try {
4646
readConfig();
4747
} catch (IOException e) {
4848
e.printStackTrace();
4949
logger.severe("Failed to load the config file.");
50+
System.exit(1);
5051
}
51-
new CSVParser(DATABASE);
52+
new JSONParser(DATABASE);
5253
// DLOptions options = new DLOptions(token);
53-
loader = new DiscLoader(new DLOptions(config.auth.token, config.prefix)).addEventListener(new Listener()).login().get();
54+
loader = new DiscLoader(new DLOptions(config.auth.token, config.prefix, false)).addEventListener(new Listener()).login().get();
5455
CommandRegistry.registerCommand(new CommandStatus(), "status");
56+
CommandRegistry.registerCommand(new CommandHelp(), "help");
5557
// JDA jda = new
5658
// JDABuilder(AccountType.BOT).setToken(token).addEventListener(new
5759
// Listener()).buildBlocking();
58-
new CSVThread().start();
60+
new JSONThread().start();
5961
// new SpamThread().start();
6062
}
6163

62-
// // This is probably the best way...
63-
// private static void readToken() throws IOException {
64-
// BufferedReader reader = new BufferedReader(new FileReader(TOKEN_FILE));
65-
// token = reader.readLine();
66-
// reader.close();
67-
// }
68-
64+
/**
65+
* Reads the config file from disk
66+
*
67+
* @throws IOException
68+
*/
6969
private static void readConfig() throws IOException {
7070
Gson gson = new Gson();
71-
File options = new File("options.json");
71+
File options = new File(CONFIG_FILE);
7272
if (options.exists() && !options.isDirectory()) {
73-
String content = "";
74-
List<String> lines = Files.readAllLines(Paths.get("./options.json"));
73+
String content = ""; // something to concatenate the lines into
74+
List<String> lines = Files.readAllLines(options.toPath()); // pretty self explanatory
7575
for (String line : lines)
7676
content += line;
7777
config = gson.fromJson(content, Config.class);

src/main/java/codekey/main/commands/CommandStatus.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class CommandStatus extends Command {
1818

1919
public CommandStatus() {
2020
setUnlocalizedName("status");
21-
21+
setDescription("Displays your player info.");
2222
}
2323

2424
@Override

0 commit comments

Comments
 (0)