Skip to content

Add config system and customize command handling #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/main/java/io/codemc/bot/CodeMCBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import io.codemc.bot.commands.CmdMsg;
import io.codemc.bot.commands.CmdSubmit;
import io.codemc.bot.listeners.ModalListener;
import io.codemc.bot.menu.ApplicationMenu;
import io.codemc.bot.utils.Constants;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
Expand Down Expand Up @@ -62,7 +63,12 @@ private void start(String token) throws LoginException{
new CmdDisable(),
new CmdMsg(),
new CmdSubmit()
).forceGuildOnly(Constants.SERVER)
)
.addContextMenus(
new ApplicationMenu.Accept(),
new ApplicationMenu.Deny()
)
.forceGuildOnly(Constants.SERVER)
.build();

JDABuilder.createDefault(token)
Expand Down
100 changes: 100 additions & 0 deletions src/main/java/io/codemc/bot/commands/BotCommand.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Copyright 2024 CodeMC.io
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package io.codemc.bot.commands;

import com.jagrosh.jdautilities.command.SlashCommand;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import io.codemc.bot.utils.CommandUtil;
import io.codemc.bot.utils.Constants;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.interactions.InteractionHook;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public abstract class BotCommand extends SlashCommand{

protected List<Long> allowedRoles = new ArrayList<>();
protected boolean hasModalReply = false;

@Override
public void execute(SlashCommandEvent event){
System.out.println("Custom BotCommand called!");
Guild guild = event.getGuild();
if(guild == null){
CommandUtil.EmbedReply.fromCommandEvent(event)
.withError("Command can only be executed in a Server!")
.send();
return;
}

if(!guild.getId().equals(Constants.SERVER)){
CommandUtil.EmbedReply.fromCommandEvent(event)
.withError("Unable to find CodeMC Server!")
.send();
return;
}

Member member = event.getMember();
if(member == null){
CommandUtil.EmbedReply.fromCommandEvent(event)
.withError("Unable to retrieve Member from Event!")
.send();
return;
}

if(!allowedRoles.isEmpty()){
boolean hasRole = false;
for(Role role : member.getRoles()){
if(allowedRoles.contains(role.getIdLong())){
hasRole = true;
break;
}
}

if(!hasRole){
List<String> names = guild.getRoles().stream()
.filter(role -> allowedRoles.contains(role.getIdLong()))
.map(Role::getName)
.collect(Collectors.toList());

CommandUtil.EmbedReply.fromCommandEvent(event)
.withError(
"You don't have any of the allowed roles to execute this command.",
"Allowed Roles: " + String.join(", ", names)
)
.send();
return;
}
}

if(hasModalReply){
withModalReply(event);
}else{
event.deferReply(true).queue(hook -> withHookReply(hook, event, guild, member));
}
}

public abstract void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member);

public abstract void withModalReply(SlashCommandEvent event);
}
62 changes: 33 additions & 29 deletions src/main/java/io/codemc/bot/commands/CmdApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import io.codemc.bot.utils.CommandUtil;
import io.codemc.bot.utils.Constants;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed;
Expand All @@ -43,15 +42,16 @@
import java.util.List;
import java.util.regex.Pattern;

public class CmdApplication extends SlashCommand{
public class CmdApplication extends BotCommand{

public CmdApplication(){
this.name = "application";
this.help = "Accept or deny applications.";

this.userPermissions = new Permission[]{
Permission.MANAGE_SERVER
};
this.allowedRoles = Arrays.asList(
Constants.ROLE_ADMINISTRATOR,
Constants.ROLE_MODERATOR
);

this.children = new SlashCommand[]{
new Accept(),
Expand All @@ -60,14 +60,12 @@ public CmdApplication(){
}

@Override
protected void execute(SlashCommandEvent event){}
public void withModalReply(SlashCommandEvent event){}

private static void handle(InteractionHook hook, Guild guild, long messageId, String str, boolean accepted){
if(guild == null || !guild.getId().equals(Constants.SERVER)){
CommandUtil.EmbedReply.fromHook(hook).withError("Unable to retrieve Server!").send();
return;
}

@Override
public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member){}

public static void handle(InteractionHook hook, Guild guild, long messageId, String str, boolean accepted){
TextChannel requestChannel = guild.getTextChannelById(Constants.REQUEST_ACCESS);
if(requestChannel == null){
CommandUtil.EmbedReply.fromHook(hook).withError("Unable to retrieve `request-access` channel.").send();
Expand Down Expand Up @@ -95,8 +93,6 @@ private static void handle(InteractionHook hook, Guild guild, long messageId, St
return;
}

System.out.println("Embed Footer text: " + userId);

String userLink = null;
String repoLink = null;
for(MessageEmbed.Field field : embed.getFields()){
Expand Down Expand Up @@ -193,17 +189,18 @@ private static MessageCreateData getMessage(String userId, String userLink, Stri
.build();
}

private static class Accept extends SlashCommand{
private static class Accept extends BotCommand{

private final Pattern projectUrlPattern = Pattern.compile("^https://ci\\.codemc\\.io/job/[a-zA-Z0-9-]+/job/[a-zA-Z0-9-_.]+/?$");

public Accept(){
this.name = "accept";
this.help = "Accept an application";

this.userPermissions = new Permission[]{
Permission.MANAGE_SERVER
};
this.allowedRoles = Arrays.asList(
Constants.ROLE_ADMINISTRATOR,
Constants.ROLE_MODERATOR
);

this.options = Arrays.asList(
new OptionData(OptionType.STRING, "id", "The message id of the application.").setRequired(true),
Expand All @@ -212,7 +209,10 @@ public Accept(){
}

@Override
protected void execute(SlashCommandEvent event){
public void withModalReply(SlashCommandEvent event){}

@Override
public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member){
long messageId = event.getOption("id", -1L, option -> {
try{
return Long.parseLong(option.getAsString());
Expand All @@ -223,32 +223,33 @@ protected void execute(SlashCommandEvent event){
String projectUrl = event.getOption("project-url", null, OptionMapping::getAsString);

if(messageId == -1L || projectUrl == null){
CommandUtil.EmbedReply.fromCommandEvent(event).withError(
CommandUtil.EmbedReply.fromHook(hook).withError(
"Message ID or Project URL were not present!"
).send();
return;
}

if(!projectUrlPattern.matcher(projectUrl).matches()){
CommandUtil.EmbedReply.fromCommandEvent(event).withError(
CommandUtil.EmbedReply.fromHook(hook).withError(
"The provided Project URL did not match the pattern `https://ci.codemc.io/job/<user>/job/<project>`!"
).send();
return;
}

event.deferReply(true).queue(hook -> handle(hook, event.getGuild(), messageId, projectUrl, true));
handle(hook, guild, messageId, projectUrl, true);
}
}

private static class Deny extends SlashCommand{
private static class Deny extends BotCommand{

public Deny(){
this.name = "deny";
this.help = "Deny an application";

this.userPermissions = new Permission[]{
Permission.MANAGE_SERVER
};
this.allowedRoles = Arrays.asList(
Constants.ROLE_ADMINISTRATOR,
Constants.ROLE_MODERATOR
);

this.options = Arrays.asList(
new OptionData(OptionType.STRING, "id", "The message id of the application.").setRequired(true),
Expand All @@ -257,7 +258,10 @@ public Deny(){
}

@Override
protected void execute(SlashCommandEvent event){
public void withModalReply(SlashCommandEvent event){}

@Override
public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member){
long messageId = event.getOption("id", -1L, option -> {
try{
return Long.parseLong(option.getAsString());
Expand All @@ -268,13 +272,13 @@ protected void execute(SlashCommandEvent event){
String reason = event.getOption("reason", null, OptionMapping::getAsString);

if(messageId == -1L || reason == null){
CommandUtil.EmbedReply.fromCommandEvent(event).withError(
CommandUtil.EmbedReply.fromHook(hook).withError(
"Message ID or Reason were not present!"
).send();
return;
}

event.deferReply(true).queue(hook -> handle(hook, event.getGuild(), messageId, reason, false));
handle(hook, guild, messageId, reason, false);
}
}
}
29 changes: 18 additions & 11 deletions src/main/java/io/codemc/bot/commands/CmdDisable.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,31 +18,38 @@

package io.codemc.bot.commands;

import com.jagrosh.jdautilities.command.SlashCommand;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.Permission;
import io.codemc.bot.utils.CommandUtil;
import io.codemc.bot.utils.Constants;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.interactions.InteractionHook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CmdDisable extends SlashCommand{
import java.util.Collections;

public class CmdDisable extends BotCommand{

private final Logger logger = LoggerFactory.getLogger("Shutdown");

public CmdDisable(){
this.name = "disable";
this.help = "Disables the bot.";

this.userPermissions = new Permission[]{
Permission.MANAGE_SERVER
};
this.allowedRoles = Collections.singletonList(
Constants.ROLE_ADMINISTRATOR
);
}

@Override
protected void execute(SlashCommandEvent event){
event.reply("Disabling bot...").setEphemeral(true).queue(m -> {
logger.info("Received disable command by {}.", event.getUser().getEffectiveName());
logger.info("Disabling bot...");
public void withHookReply(InteractionHook hook, SlashCommandEvent event, Guild guild, Member member){
hook.editOriginalEmbeds(CommandUtil.getEmbed().setColor(0x00FF00).setDescription("Bot disabled!").build()).queue(h -> {
logger.info("Bot disabled by {}", event.getUser().getEffectiveName());
System.exit(0);
});
}

@Override
public void withModalReply(SlashCommandEvent event){}
}
Loading