Skip to content

Commit

Permalink
Add rename to user context menu
Browse files Browse the repository at this point in the history
  • Loading branch information
rtm516 committed Mar 14, 2024
1 parent 2dedff3 commit 55023b1
Show file tree
Hide file tree
Showing 6 changed files with 150 additions and 22 deletions.
2 changes: 1 addition & 1 deletion .idea/copyright/GeyserDiscordBot.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 26 additions & 4 deletions src/main/java/org/geysermc/discordbot/GeyserBot.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020-2022 GeyserMC. http://geysermc.org
* Copyright (c) 2020-2024 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -27,6 +27,7 @@

import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandClientBuilder;
import com.jagrosh.jdautilities.command.ContextMenu;
import com.jagrosh.jdautilities.command.SlashCommand;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import io.sentry.Sentry;
Expand Down Expand Up @@ -78,6 +79,7 @@ public class GeyserBot {
public static final Logger LOGGER = LoggerFactory.getLogger(GeyserBot.class);
public static final List<Command> COMMANDS;
public static final List<SlashCommand> SLASH_COMMANDS;
public static final List<ContextMenu> CONTEXT_MENUS;

public static AbstractStorageManager storageManager;

Expand All @@ -96,8 +98,9 @@ public class GeyserBot {
Set<Class<? extends Command>> subTypes = reflections.getSubTypesOf(Command.class);
for (Class<? extends Command> theClass : subTypes) {
// Don't load SubCommands
if (theClass.getName().contains("SubCommand"))
if (theClass.getName().contains("SubCommand")) {
continue;
}
try {
commands.add(theClass.getDeclaredConstructor().newInstance());
LoggerFactory.getLogger(theClass).debug("Loaded Command Successfully!");
Expand All @@ -109,8 +112,9 @@ public class GeyserBot {
Set<Class<? extends SlashCommand>> slashSubTypes = reflections.getSubTypesOf(SlashCommand.class);
for (Class<? extends SlashCommand> theClass : slashSubTypes) {
// Don't load SubCommands
if (theClass.getName().contains("SubCommand"))
if (theClass.getName().contains("SubCommand")) {
continue;
}
slashCommands.add(theClass.getDeclaredConstructor().newInstance());
LoggerFactory.getLogger(theClass).debug("Loaded SlashCommand Successfully!");
}
Expand All @@ -119,9 +123,26 @@ public class GeyserBot {
}
COMMANDS = commands;
SLASH_COMMANDS = slashCommands;

// Gathers all context menu items from "context_menu" package.
List<ContextMenu> contextMenus = new ArrayList<>();
try {
Reflections reflections = new Reflections("org.geysermc.discordbot.context_menus");
Set<Class<? extends ContextMenu>> subTypes = reflections.getSubTypesOf(ContextMenu.class);
for (Class<? extends ContextMenu> theClass : subTypes) {
if (!theClass.getPackageName().startsWith("org.geysermc.discordbot.context_menus")) {
continue;
}
contextMenus.add(theClass.getDeclaredConstructor().newInstance());
LoggerFactory.getLogger(theClass).debug("Loaded ContextMenu Successfully!");
}
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
LOGGER.error("Unable to load context menus", e);
}
CONTEXT_MENUS = contextMenus;
}

public static void main(String[] args) throws IOException, LoginException {
public static void main(String[] args) throws IOException {
// Load properties into the PropertiesManager
Properties prop = new Properties();
prop.load(new FileInputStream("bot.properties"));
Expand Down Expand Up @@ -169,6 +190,7 @@ public static void main(String[] args) throws IOException, LoginException {
client.useHelpBuilder(false);
client.addCommands(COMMANDS.toArray(new Command[0]));
client.addSlashCommands(SLASH_COMMANDS.toArray(new SlashCommand[0]));
client.addContextMenus(CONTEXT_MENUS.toArray(new ContextMenu[0]));
client.setListener(new CommandErrorHandler());
client.setCommandPreProcessBiFunction((event, command) -> !SwearHandler.filteredMessages.contains(event.getMessage().getIdLong()));

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020-2022 GeyserMC. http://geysermc.org
* Copyright (c) 2020-2024 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -81,7 +81,7 @@ protected void execute(CommandEvent event) {
event.getMessage().replyEmbeds(handle(member, event.getMember(), event.getGuild())).queue();
}

private MessageEmbed handle(Member member, Member moderator, Guild guild) {
public static MessageEmbed handle(Member member, Member moderator, Guild guild) {
// Check the user exists
if (member == null) {
return new EmbedBuilder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2024-2024 GeyserMC. http://geysermc.org
*
* 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.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/GeyserDiscordBot
*/

package org.geysermc.discordbot.context_menus;

import com.jagrosh.jdautilities.command.UserContextMenu;
import com.jagrosh.jdautilities.command.UserContextMenuEvent;
import net.dv8tion.jda.api.Permission;
import org.geysermc.discordbot.commands.moderation.RenameCommand;

public class RenameUserMenu extends UserContextMenu {
public RenameUserMenu() {
this.name = "Rename";

this.userPermissions = new Permission[] { Permission.NICKNAME_MANAGE };
this.botPermissions = new Permission[] { Permission.NICKNAME_MANAGE };
}

@Override
protected void execute(UserContextMenuEvent event) {
event.replyEmbeds(RenameCommand.handle(event.getTargetMember(), event.getMember(), event.getGuild())).setEphemeral(true).queue();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020-2022 GeyserMC. http://geysermc.org
* Copyright (c) 2020-2024 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -28,6 +28,12 @@
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.command.CommandListener;
import com.jagrosh.jdautilities.command.MessageContextMenu;
import com.jagrosh.jdautilities.command.MessageContextMenuEvent;
import com.jagrosh.jdautilities.command.SlashCommand;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import com.jagrosh.jdautilities.command.UserContextMenu;
import com.jagrosh.jdautilities.command.UserContextMenuEvent;
import net.dv8tion.jda.api.EmbedBuilder;
import org.geysermc.discordbot.util.BotColors;
import pw.chew.chewbotcca.listeners.BotCommandListener;
Expand All @@ -38,28 +44,82 @@

public class CommandErrorHandler extends BotCommandListener implements CommandListener {
@Override
public void onCommandException(CommandEvent event, Command command, Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
String[] errorStack = sw.toString().split("\n");
int limit = Math.min(errorStack.length, 5);
public void onSlashCommandException(SlashCommandEvent event, SlashCommand command, Throwable throwable) {
String errorMessage = getErrorMessage(throwable);

StringBuilder errorMessage = new StringBuilder();
for (int i = 0; i < limit; i++) {
errorMessage.append(errorStack[i]).append("\n");
}
event.replyEmbeds(new EmbedBuilder()
.setTitle("Error handling command")
.setDescription("An error occurred while handling the command")
.addField("Command usage", "/" + command.getName() + (command.getArguments() != null ? " " + command.getArguments() : ""), false)
.addField("Command help", command.getHelp(), false)
.addField("Error", errorMessage, false)
.setTimestamp(Instant.now())
.setColor(BotColors.FAILURE.getColor())
.build()).setEphemeral(true).queue();

super.onSlashCommandException(event, command, throwable);
}

@Override
public void onCommandException(CommandEvent event, Command command, Throwable throwable) {
String errorMessage = getErrorMessage(throwable);

event.getMessage().replyEmbeds(new EmbedBuilder()
.setTitle("Error handling command")
.setDescription("An error occurred while handling the command")
.addField("Command usage", event.getPrefix() + command.getName() + (command.getArguments() != null ? " " + command.getArguments() : ""), false)
.addField("Command help", command.getHelp(), false)
.addField("Error", errorMessage.toString(), false)
.addField("Error", errorMessage, false)
.setTimestamp(Instant.now())
.setColor(BotColors.FAILURE.getColor())
.build()).queue();

super.onCommandException(event, command, throwable);
}

@Override
public void onMessageContextMenuException(MessageContextMenuEvent event, MessageContextMenu menu, Throwable throwable) {
String errorMessage = getErrorMessage(throwable);

event.replyEmbeds(new EmbedBuilder()
.setTitle("Error handling context menu option")
.setDescription("An error occurred while handling the message context menu option")
.addField("Menu option", menu.getName(), false)
.addField("Error", errorMessage, false)
.setTimestamp(Instant.now())
.setColor(BotColors.FAILURE.getColor())
.build()).setEphemeral(true).queue();

super.onMessageContextMenuException(event, menu, throwable);
}

@Override
public void onUserContextMenuException(UserContextMenuEvent event, UserContextMenu menu, Throwable throwable) {
String errorMessage = getErrorMessage(throwable);

event.replyEmbeds(new EmbedBuilder()
.setTitle("Error handling context menu option")
.setDescription("An error occurred while handling the user context menu option")
.addField("Menu option", menu.getName(), false)
.addField("Error", errorMessage, false)
.setTimestamp(Instant.now())
.setColor(BotColors.FAILURE.getColor())
.build()).setEphemeral(true).queue();

super.onUserContextMenuException(event, menu, throwable);
}

private String getErrorMessage(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
String[] errorStack = sw.toString().split("\n");
int limit = Math.min(errorStack.length, 5);

StringBuilder errorMessage = new StringBuilder();
for (int i = 0; i < limit; i++) {
errorMessage.append(errorStack[i]).append("\n");
}
return errorMessage.toString();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2020-2022 GeyserMC. http://geysermc.org
* Copyright (c) 2020-2024 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
Expand Down Expand Up @@ -40,6 +40,7 @@
import javax.annotation.Nullable;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.HashMap;
Expand Down Expand Up @@ -80,7 +81,7 @@ public static void loadFilters() {
if (fileName.endsWith(".wlist")) {
fileCount++;
// Load the lines
String[] lines = new String(BotHelpers.bytesFromResource("filters/" + fileName)).split("\n");
String[] lines = new String(BotHelpers.bytesFromResource("filters/" + fileName), StandardCharsets.UTF_8).split("\n");
for (String line : lines) {
filterPatterns.add(Pattern.compile("(^| )" + line.trim() + "( |$)", Pattern.CASE_INSENSITIVE));
}
Expand All @@ -92,7 +93,7 @@ public static void loadFilters() {

GeyserBot.LOGGER.info("Loaded " + filterPatterns.size() + " filter patterns from " + fileCount + " files");

nicknames = new String(BotHelpers.bytesFromResource("nicknames.wlist")).trim().split("\n");
nicknames = new String(BotHelpers.bytesFromResource("nicknames.wlist"), StandardCharsets.UTF_8).trim().split("\n");

GeyserBot.LOGGER.info("Loaded " + nicknames.length + " nicknames");
}
Expand Down

0 comments on commit 55023b1

Please sign in to comment.