Skip to content

Commit ae42936

Browse files
Merge pull request #1 from LearnerCouncil/Joinlist
Joinlist
2 parents 3704289 + 4896b3d commit ae42936

File tree

5 files changed

+173
-16
lines changed

5 files changed

+173
-16
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
<dependency>
4747
<groupId>ch.qos.logback</groupId>
4848
<artifactId>logback-classic</artifactId>
49-
<version>1.4.4</version>
49+
<version>1.2.8</version>
5050
</dependency>
5151
</dependencies>
5252
</project>

src/main/java/rocks/learnercouncil/cameron/Cameron.java

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public static void main(String[] args) throws InterruptedException, LoginExcepti
5151
new ReportCommand(),
5252
new KickCommand(),
5353
new BanCommand(),
54+
new JoinlistCommand(),
5455
//Events
5556
new EditEvent(),
5657
new MessageEvent(),
@@ -73,14 +74,38 @@ public static void main(String[] args) throws InterruptedException, LoginExcepti
7374
PronounsCommand.initializeRoles(guild);
7475
Cameron.logger.info("Found Guild: " + guild.getName());
7576
MessageCache.initializeMessages(guild);
76-
//Currently guild commands but may be changed to global commands on release
77-
//i.e. jda.updateCommands().addCommands(...).queue();
78-
guild.updateCommands().addCommands(Commands.slash("ping", "Ping Pong!"), Commands.slash("request", "Request Access to the server"), Commands.slash("rps", "Play 'Rock, Paper, Scissors' with Cameron"), Commands.slash("say", "Make cameron say something").addOption(OptionType.STRING, "message", "The thing to Cameron will say", true).setDefaultEnabled(false), Commands.slash("sayembed", "Make cameron say something as an embed").addOptions(
79-
new OptionData(OptionType.STRING, "color", "The color of the sidebar of the embed", true, true), new OptionData(OptionType.STRING, "title", "The title of the embed", true), new OptionData(OptionType.STRING, "message", "The thing cameron will say", true)).setDefaultEnabled(false), Commands.slash("pronouns", "Set your pronouns"), Commands.slash("whois", "Check the information of a certain user").addOption(OptionType.USER, "user", "The usre to get the information of", true), Commands.slash("report", "Report a user").addOptions(new OptionData(OptionType.USER, "user", "The user you're reporting.", true), new OptionData(OptionType.STRING, "reason", "The reason you're reporting them.", true)), Commands.slash("kick", "Kicks a user").addOptions(new OptionData(OptionType.USER, "user", "the user to kick", true), new OptionData(OptionType.STRING, "reason", "the reason you're kicking them", false)).setDefaultEnabled(false),
80-
Commands.slash("ban", "Kicks a user").addOptions(
77+
//Global commands don't seem to work, even after waiting for the alotted time, so for the time being I'm sticking to guild commands.
78+
guild.updateCommands().addCommands(
79+
Commands.slash("ping", "Ping Pong!"),
80+
Commands.slash("request", "Request Access to the server"),
81+
Commands.slash("rps", "Play 'Rock, Paper, Scissors' with Cameron"),
82+
Commands.slash("say", "Make cameron say something")
83+
.addOption(OptionType.STRING, "message", "The thing to Cameron will say", true)
84+
.setDefaultEnabled(false),
85+
Commands.slash("sayembed", "Make cameron say something as an embed")
86+
.addOptions(
87+
new OptionData(OptionType.STRING, "color", "The color of the sidebar of the embed", true, true),
88+
new OptionData(OptionType.STRING, "title", "The title of the embed", true),
89+
new OptionData(OptionType.STRING, "message", "The thing cameron will say", true))
90+
.setDefaultEnabled(false),
91+
Commands.slash("pronouns", "Set your pronouns"),
92+
Commands.slash("whois", "Check the information of a certain user").addOption(OptionType.USER, "user", "The usre to get the information of", true),
93+
Commands.slash("report", "Report a user")
94+
.addOptions(
95+
new OptionData(OptionType.USER, "user", "The user you're reporting.", true),
96+
new OptionData(OptionType.STRING, "reason", "The reason you're reporting them.", true)),
97+
Commands.slash("kick", "Kicks a user").addOptions(
8198
new OptionData(OptionType.USER, "user", "the user to kick", true),
82-
new OptionData(OptionType.STRING, "reason", "the reason you're kicking them", false),
83-
new OptionData(OptionType.INTEGER, "delete_history_days", "The amount of days of recent message history from this user you want to delete.", false)).setDefaultEnabled(false)
99+
new OptionData(OptionType.STRING, "reason", "the reason you're kicking them", false))
100+
.setDefaultEnabled(false),
101+
Commands.slash("ban", "Kicks a user")
102+
.addOptions(
103+
new OptionData(OptionType.USER, "user", "the user to kick", true),
104+
new OptionData(OptionType.STRING, "reason", "the reason you're kicking them", false),
105+
new OptionData(OptionType.INTEGER, "delete_history_days", "The amount of days of recent message history from this user you want to delete.", false))
106+
.setDefaultEnabled(false),
107+
Commands.slash("joinlist", "Request access to the Minecraft Server")
108+
.addOption(OptionType.STRING, "username", "Your Minecraft username", true)
84109
).queue(c -> logger.info("Loaded Commands"));
85110
guild.loadMembers().onSuccess(l -> {
86111
logger.info("Loaded Members");
@@ -142,6 +167,7 @@ public static JDA getJDA() {
142167
return jda;
143168
}
144169

170+
@NotNull
145171
public static Guild getGuild() {
146172
return guild;
147173
}
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
package rocks.learnercouncil.cameron.commands;
2+
3+
import net.dv8tion.jda.api.EmbedBuilder;
4+
import net.dv8tion.jda.api.entities.MessageEmbed;
5+
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
6+
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
7+
import net.dv8tion.jda.api.hooks.ListenerAdapter;
8+
import net.dv8tion.jda.api.interactions.components.buttons.Button;
9+
import okhttp3.OkHttpClient;
10+
import okhttp3.Request;
11+
import okhttp3.Response;
12+
import org.jetbrains.annotations.NotNull;
13+
import rocks.learnercouncil.cameron.Cameron;
14+
15+
import java.awt.Color;
16+
import java.io.IOException;
17+
import java.time.Instant;
18+
import java.util.*;
19+
import java.util.List;
20+
import java.util.concurrent.TimeUnit;
21+
import java.util.regex.Matcher;
22+
import java.util.regex.Pattern;
23+
24+
public class JoinlistCommand extends ListenerAdapter {
25+
26+
private static final OkHttpClient client = new OkHttpClient();
27+
28+
private static final Button acceptButton = Button.success("jl_accept", "Accept");
29+
private static final Button denyButton = Button.danger("jl_deny", "Deny");
30+
31+
@Override
32+
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
33+
if(event.getOption("username") == null) return;
34+
String username = Objects.requireNonNull(event.getOption("username")).getAsString();
35+
String jsonString = sendRequest(username);
36+
if(jsonString.startsWith("#ERR INVALID_CHARS")) {
37+
String invalid_characters = jsonString.split(":")[1];
38+
StringBuilder stringBuilder = new StringBuilder();
39+
for(char character : invalid_characters.toCharArray()) {
40+
stringBuilder.append('\'');
41+
stringBuilder.append(character);
42+
stringBuilder.append("', ");
43+
}
44+
event.reply("The username you typed contains characters that can't be in a Minecraft username: " + stringBuilder.substring(0, stringBuilder.length() - 2) +
45+
"Please check to make sure you spelled your username correctly.").setEphemeral(true).queue();
46+
return;
47+
}
48+
if(jsonString.isEmpty()) {
49+
event.reply("I can't find the minecraft username '" + username + "', check that it's spelled correctly.").setEphemeral(true).queue();
50+
return;
51+
}
52+
Map<String, String> json = parseJson(jsonString);
53+
if(json.containsKey("error")) {
54+
event.reply("I can't find the minecraft username '" + username + "', check that it's spelled correctly.").setEphemeral(true).queue();
55+
return;
56+
}
57+
if (!json.containsKey("id")) return;
58+
if(event.getMember() == null) return;
59+
60+
Cameron.getExistingChannel("mc-joinlist").sendMessageEmbeds(
61+
new EmbedBuilder()
62+
.setColor(Color.YELLOW)
63+
.setAuthor("Request Pending...")
64+
.setDescription(event.getUser().getAsMention() + " is requesting to join the Minecraft server.\n" +
65+
"If you wish to accept the request, add them to the joinlist and click **Accept**. Otherwise, click **Deny**.")
66+
.addField(new MessageEmbed.Field("> **Name:**", event.getUser().getAsMention(), false))
67+
.addField(new MessageEmbed.Field("> **Username:**", json.get("name"), false))
68+
.addField(new MessageEmbed.Field("> **UUID:**", formatUUID(json.get("id")), false))
69+
.build()
70+
).setActionRow(acceptButton, denyButton).queue();
71+
72+
event.reply("Request sent! A council member will review it soon.").setEphemeral(true).queue();
73+
}
74+
75+
private String formatUUID(String uuid) {
76+
return new StringBuilder(uuid).insert(8, '-').insert(13, '-').insert(18, '-').insert(23, '-').toString();
77+
}
78+
79+
@Override
80+
public void onButtonInteraction(@NotNull ButtonInteractionEvent event) {
81+
if(event.getComponentId().equals("jl_accept")) {
82+
List<MessageEmbed.Field> fields = new ArrayList<>();
83+
MessageEmbed embed = event.getMessage().getEmbeds().get(0);
84+
if(!embed.getFields().isEmpty())
85+
fields = embed.getFields();
86+
87+
event.editMessageEmbeds(
88+
new EmbedBuilder()
89+
.setColor(Color.GREEN)
90+
.setAuthor("Accepted.")
91+
.setDescription("Request accepted.\n")
92+
.addField(fields.get(0))
93+
.addField(fields.get(1))
94+
.addField(fields.get(2))
95+
.setTimestamp(Instant.now())
96+
.build()).setActionRows().queue();
97+
return;
98+
}
99+
if(event.getComponentId().equals("jl_deny")) {
100+
event.editMessageEmbeds(new EmbedBuilder()
101+
.setAuthor("Denied.")
102+
.setColor(Color.RED)
103+
.setDescription("Request Denied.")
104+
.build()).setActionRows().queue(m -> m.deleteOriginal().queueAfter(120, TimeUnit.SECONDS));
105+
}
106+
}
107+
108+
private String sendRequest(String username) {
109+
Pattern pattern = Pattern.compile("[a-zA-Z0-9\\-_]+");
110+
Matcher matcher = pattern.matcher(username);
111+
if(!matcher.matches()) return "#ERR INVALID_CHARS:" + matcher.replaceAll("");
112+
String url = "https://api.mojang.com/users/profiles/minecraft/" + username;
113+
Request request = new Request.Builder()
114+
.url(url)
115+
.header("User-Agent", "application/json")
116+
.build();
117+
try {
118+
Response response = client.newCall(request).execute();
119+
//System.out.println(Objects.requireNonNull(response.body()).string());
120+
return Objects.requireNonNull(response.body()).string();
121+
} catch (IOException e) {
122+
System.out.println("IOException occured via /joinlist");
123+
return "#ERR IOEXCEPTION";
124+
}
125+
}
126+
127+
private Map<String, String> parseJson(String json) {
128+
json = json.replace("\s*", "");
129+
Map<String, String> map = new LinkedHashMap<>();
130+
String[] pairs = json.substring(1, json.length() - 1).split(",");
131+
for(String pair : pairs) {
132+
String[] parts = pair.split(":");
133+
if(parts.length != 2) continue;
134+
map.put(parts[0].substring(1, parts[0].length() - 1), parts[1].substring(1, parts[1].length() - 1));
135+
}
136+
return map;
137+
}
138+
}

src/main/java/rocks/learnercouncil/cameron/commands/PronounsCommand.java

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,11 @@ public static void initializeRoles(Guild guild) {
2727
Cameron.logger.info("Initializing roles");
2828
pronounRoles.clear();
2929
if(guild == null) return;
30-
Cameron.logger.info("Guild isn't null");
3130
Cameron.getExistingChannel("pronouns").getIterableHistory().forEach(m -> {
32-
Cameron.logger.info("Message: " + m.getContentStripped());
3331
if(guild.getRolesByName(PREFIX + m.getContentStripped(), true).isEmpty())
3432
addPronounRole(guild, PREFIX + m.getContentStripped());
3533
});
3634
guild.getRoles().stream().filter(r -> r.getName().startsWith(PREFIX)).forEach(pronounRoles::add);
37-
Cameron.logger.info(pronounRoles.toString());
3835
}
3936

4037
private static boolean matchesAnyInChannel(Role r, MessageChannel channel) {
@@ -51,7 +48,7 @@ public static void addPronounRole(Guild guild, String name) {
5148
guild.createRole().setName(PREFIX + name).queue(pronounRoles::add);
5249
}
5350
public static void removePronounRole(String name, Guild guild) {
54-
Cameron.logger.info("Deleting: " + name);
51+
Cameron.logger.info("Deleting Pronoun Role: " + name);
5552
pronounRoles.remove(Cameron.getExistingRole(PREFIX + name));
5653
Cameron.getExistingRole(PREFIX + name).delete().queue();
5754
}
@@ -60,17 +57,14 @@ public static void removePronounRole(String name, Guild guild) {
6057
@Override
6158
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
6259
if(!event.getName().equals("pronouns")) return;
63-
Cameron.logger.info("Command Executed");
6460
if(!event.isFromGuild()) {
6561
event.reply("This command must be run from inside a server").queue();
6662
return;
6763
}
68-
Cameron.logger.info("Command is from guild");
6964
event.deferReply().setEphemeral(true).queue();
7065
if(pronounRoles.isEmpty()) {
7166
initializeRoles(event.getGuild());
7267
}
73-
Cameron.logger.info("Pronouns: " + pronounRoles);
7468
MessageEmbed embed = new EmbedBuilder()
7569
.setColor(Color.GREEN)
7670
.setAuthor("Set your pronouns! (Select all that apply.)")

src/main/java/rocks/learnercouncil/cameron/commands/WhoisCommand.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,5 @@ public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent even
5050
}, false)
5151
.build()
5252
).queue();
53-
Cameron.logger.info(member.getOnlineStatus().toString());
5453
}
5554
}

0 commit comments

Comments
 (0)