use of at.xirado.bean.command.SlashCommandContext in project Bean by Xirado.
the class InteractionCommandHandler method handleSlashCommand.
public void handleSlashCommand(@NotNull SlashCommandInteractionEvent event, @Nullable Member member) {
Runnable r = () -> {
try {
if (!event.isFromGuild())
return;
Guild guild = event.getGuild();
SlashCommand command = null;
long guildId = event.getGuild().getIdLong();
if (registeredGuildCommands.containsKey(guildId)) {
List<SlashCommand> guildCommands = registeredGuildCommands.get(guildId).stream().filter(cmd -> cmd instanceof SlashCommand).map(cmd -> (SlashCommand) cmd).toList();
SlashCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (guildCommand != null)
command = guildCommand;
}
if (command == null) {
SlashCommand globalCommand = getRegisteredSlashCommands().stream().filter(cmd -> cmd.getCommandName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
if (globalCommand != null)
command = globalCommand;
}
if (command != null) {
SlashCommandContext ctx = new SlashCommandContext(event);
List<Permission> neededPermissions = command.getRequiredUserPermissions();
List<Permission> neededBotPermissions = command.getRequiredBotPermissions();
if (neededPermissions != null && !member.hasPermission((GuildChannel) event.getChannel(), neededPermissions)) {
event.reply(LocaleLoader.ofGuild(guild).get("general.no_perms", String.class)).queue();
return;
}
if (neededBotPermissions != null && !event.getGuild().getSelfMember().hasPermission((GuildChannel) event.getChannel(), neededBotPermissions)) {
event.reply(LocaleLoader.ofGuild(guild).get("general.no_bot_perms1", String.class)).queue();
return;
}
if (command.getCommandFlags().contains(CommandFlag.DJ_ONLY)) {
if (!ctx.getGuildData().isDJ(member)) {
event.replyEmbeds(EmbedUtil.errorEmbed("You need to be a DJ to do this!")).queue();
return;
}
}
if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_VC)) {
GuildVoiceState guildVoiceState = member.getVoiceState();
if (guildVoiceState == null || !guildVoiceState.inAudioChannel()) {
event.replyEmbeds(EmbedUtil.errorEmbed("You are not connected to a voice-channel!")).queue();
return;
}
}
if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_SAME_VC)) {
GuildVoiceState voiceState = member.getVoiceState();
AudioManager manager = event.getGuild().getAudioManager();
if (manager.isConnected()) {
if (!manager.getConnectedChannel().equals(voiceState.getChannel())) {
event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in " + manager.getConnectedChannel().getAsMention() + "to do this!")).setEphemeral(true).queue();
return;
}
}
}
if (command.getCommandFlags().contains(CommandFlag.REQUIRES_LAVALINK_NODE)) {
if (!ctx.isLavalinkNodeAvailable()) {
event.replyEmbeds(EmbedUtil.errorEmbed("There are currently no voice nodes available!\nIf the issue persists, please leave a message on our support server!")).addActionRow(Util.getSupportButton()).queue();
return;
}
}
command.executeCommand(event, ctx);
Metrics.COMMANDS.labels("success").inc();
}
} catch (Exception e) {
Metrics.COMMANDS.labels("failed").inc();
LinkedDataObject translation = event.getGuild() == null ? LocaleLoader.getForLanguage("en_US") : LocaleLoader.ofGuild(event.getGuild());
if (event.isAcknowledged())
event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
}, ex -> {
});
else
event.replyEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
}, ex -> {
});
LOGGER.error("Could not execute slash-command", e);
StringBuilder path = new StringBuilder("/" + event.getCommandPath().replace("/", " "));
for (OptionMapping option : event.getOptions()) {
path.append(" *").append(option.getName()).append("* : ").append("`").append(option.getAsString()).append("`");
}
EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a slash-command!").addField("Guild", event.getGuild() == null ? "None (Direct message)" : event.getGuild().getIdLong() + " (" + event.getGuild().getName() + ")", true).addField("Channel", event.getGuild() == null ? "None (Direct message)" : event.getChannel().getName(), true).addField("User", event.getUser().getAsMention() + " (" + event.getUser().getAsTag() + ")", true).addField("Command", path.toString(), false).setColor(EmbedUtil.ERROR_COLOR);
event.getJDA().openPrivateChannelById(Bean.OWNER_ID).flatMap(c -> c.sendMessageEmbeds(builder.build()).content("```fix\n" + ExceptionUtils.getStackTrace(e) + "\n```")).queue();
}
};
Bean.getInstance().getCommandExecutor().execute(r);
}
use of at.xirado.bean.command.SlashCommandContext in project Bean by Xirado.
the class ReactionRoleCommand method executeCommand.
@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
Guild guild = event.getGuild();
Member bot = guild.getSelfMember();
String subcommand = event.getSubcommandName();
if (subcommand == null) {
ctx.reply(ctx.getLocalized("commands.invalid_subcommand")).setEphemeral(true).queue();
return;
}
if (subcommand.equalsIgnoreCase("remove")) {
TextChannel channel = (TextChannel) event.getOption("channel").getAsGuildChannel();
if (channel == null) {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.channel_not_exists")).setEphemeral(true).queue();
return;
}
long messageID = 0;
try {
messageID = Long.parseLong(event.getOption("message_id").getAsString());
} catch (Exception e) {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_invalid")).setEphemeral(true).queue();
return;
}
channel.retrieveMessageById(messageID).queue((message) -> {
ctx.getGuildData().removeReactionRoles(message.getIdLong()).update();
message.clearReactions().queue(s -> {
}, e -> {
});
ctx.reply(SlashCommandContext.SUCCESS + " " + ctx.getLocalized("commands.reactionroles.removed_success")).setEphemeral(true).queue();
}, new ErrorHandler().handle(ErrorResponse.UNKNOWN_MESSAGE, (err) -> ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_not_exists")).setEphemeral(true).queue()).handle(EnumSet.allOf(ErrorResponse.class), (err) -> {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("general.unknown_error_occured")).setEphemeral(true).queue();
LOGGER.error("An error occurred while trying to remove reaction roles!", err);
}));
} else if (subcommand.equalsIgnoreCase("create")) {
TextChannel channel = (TextChannel) event.getOption("channel").getAsGuildChannel();
if (channel == null) {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.channel_not_exists")).setEphemeral(true).queue();
return;
}
long messageID = 0;
try {
messageID = Long.parseLong(event.getOption("message_id").getAsString());
} catch (Exception e) {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_invalid")).setEphemeral(true).queue();
return;
}
channel.retrieveMessageById(messageID).queue((message) -> {
Role role = event.getOption("role").getAsRole();
if (!bot.canInteract(role)) {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.cannot_interact_role", role.getAsMention())).setEphemeral(true).queue();
return;
}
String emoticon = event.getOption("emote").getAsString();
String emote = emoticon;
Pattern pattern = Message.MentionType.EMOTE.getPattern();
Matcher matcher = pattern.matcher(emoticon);
if (matcher.matches()) {
emoticon = "emote:" + matcher.group(2);
emote = matcher.group(2);
}
String finalEmote = emote;
message.addReaction(emoticon).queue((success) -> {
ReactionRole reactionRole = new at.xirado.bean.data.ReactionRole(finalEmote, message.getIdLong(), role.getIdLong());
ctx.getGuildData().addReactionRoles(reactionRole).update();
ctx.reply(SlashCommandContext.SUCCESS + " " + ctx.getLocalized("commands.reactionroles.added_success")).setEphemeral(true).queue();
}, new ErrorHandler().handle(ErrorResponse.UNKNOWN_EMOJI, (e) -> ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.emote_invalid")).setEphemeral(true).queue()).handle(EnumSet.allOf(ErrorResponse.class), (e) -> {
ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("general.unknown_error_occured")).setEphemeral(true).queue();
LOGGER.error("An error occurred while adding reaction-role!", e);
}));
}, (error) -> ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_not_exists")).setEphemeral(true).queue());
}
}
use of at.xirado.bean.command.SlashCommandContext in project Bean by Xirado.
the class UrbanDictionaryCommand method executeCommand.
@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
String phrase = event.getOption("phrase").getAsString();
int index = event.getOption("definition") != null ? (int) event.getOption("definition").getAsLong() : 1;
if (index < 1)
index = 1;
event.deferReply().queue();
LinkedDataObject dataObject;
try {
String url = "http://api.urbandictionary.com/v0/define?term=" + phrase.replaceAll("\\s+", "+");
Response response = Bean.getInstance().getOkHttpClient().newCall(new Request.Builder().url(url).build()).execute();
dataObject = LinkedDataObject.parse(response.body().byteStream());
response.close();
} catch (Exception ex) {
LOGGER.error("Could not get data from API!", ex);
event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed("An error occurred, please try again later.")).queue();
return;
}
UrbanDefinition[] results = dataObject.convertValueAt("list", UrbanDefinition[].class);
if (results.length == 0) {
EmbedBuilder builder = new EmbedBuilder().setColor(Color.decode("#1D2439")).setTitle(ctx.getLocalized("commands.urban.not_found")).setTimestamp(Instant.now());
event.getHook().sendMessageEmbeds(builder.build()).queue();
return;
}
if (results.length < index)
index = results.length;
UrbanDefinition result = results[index - 1];
String description = result.getDefinition();
Matcher matcher = PATTERN.matcher(description);
description = matcher.replaceAll(match -> "[" + match.group().replaceAll("\\[|\\]", "") + "]" + "(https://urbandictionary.com/define.php?term=" + match.group().replaceAll("\\s+", "+").replaceAll("\\[|\\]", "") + ")");
if (description.length() > 4096) {
String replaceString = "... [**" + ctx.getLocalized("general.read_more") + "**](" + result.getPermalink() + ")";
String split = description.substring(0, 4096 - replaceString.length());
description = split + replaceString;
}
EmbedBuilder builder = new EmbedBuilder().setColor(Color.decode("#1D2439")).setTitle(result.getWord()).setTitle(result.getWord(), result.getPermalink()).setFooter(Util.ordinal(index) + " definition").setFooter(Util.ordinal(index) + " definition", "https://bean.bz/assets/udlogo.png").setDescription(description);
String example = result.getExample();
if (example != null) {
boolean alreadyRecursive = example.startsWith("*") && example.endsWith("*");
Matcher matcher2 = PATTERN.matcher(example);
example = matcher2.replaceAll(match -> "[" + match.group().replaceAll("\\[|\\]", "") + "]" + "(https://www.urbandictionary.com/define.php?term=" + match.group().replaceAll(" ", "+").replaceAll("\\[|\\]", "") + ")");
if (example.length() <= 1022)
builder.addField(ctx.getLocalized("general.example"), ((alreadyRecursive) ? (example) : ("*" + example + "*")), false);
}
String authorUrl = "https://www.urbandictionary.com/author.php?author=";
authorUrl += result.getAuthor().replaceAll("\\s+", "%20");
builder.setTimestamp(Instant.parse(result.getWrittenOn()));
builder.addField(ctx.getLocalized("general.author"), "[" + result.getAuthor() + "](" + authorUrl + ")\n\uD83D\uDC4D " + result.getUpvotes() + " \uD83D\uDC4E " + result.getDownvotes(), false);
event.getHook().sendMessageEmbeds(builder.build()).queue();
}
use of at.xirado.bean.command.SlashCommandContext in project Bean by Xirado.
the class VoiceGameCommand method executeCommand.
@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
long appId = Long.parseUnsignedLong(event.getOption("application").getAsString());
boolean ephemeral = event.getOption("hide") != null && event.getOption("hide").getAsBoolean();
GuildVoiceState voiceState = event.getMember().getVoiceState();
AudioChannel audioChannel = voiceState.getChannel();
if (audioChannel == null) {
event.replyEmbeds(EmbedUtil.errorEmbed("You must be in a audio-channel to do this!")).setEphemeral(true).queue();
return;
}
event.deferReply(ephemeral).flatMap(hook -> createInvite(3600, 0, audioChannel, appId)).flatMap(url -> event.getHook().sendMessage(url)).queue();
}
use of at.xirado.bean.command.SlashCommandContext in project Bean by Xirado.
the class BanCommand method executeCommand.
@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
Member sender = event.getMember();
Guild guild = event.getGuild();
if (guild == null) {
LOGGER.error("Received /ban command with empty guild!");
return;
}
User targetUser = event.getOption("user").getAsUser();
Member targetMember = event.getOption("user").getAsMember();
String reason = event.getOption("reason") == null ? null : event.getOption("reason").getAsString();
int delDays = event.getOption("del_days") != null ? (int) Math.max(0, Math.min(7, event.getOption("del_days").getAsLong())) : 0;
if (targetMember != null) {
if (sender.getIdLong() == targetMember.getIdLong()) {
ctx.reply(EmbedUtil.errorEmbed(ctx.getLocalized("commands.ban.cannot_ban_self"))).setEphemeral(true).queue();
return;
}
if (!sender.canInteract(targetMember)) {
ctx.reply(EmbedUtil.noEntryEmbed(ctx.getLocalized("commands.ban.you_cannot_ban_this_member"))).setEphemeral(true).queue();
return;
}
if (ctx.getGuildData().isModerator(targetMember)) {
ctx.reply(EmbedUtil.noEntryEmbed(ctx.getLocalized("commands.ban.cannot_ban_moderator"))).setEphemeral(true).queue();
return;
}
if (!guild.getSelfMember().canInteract(targetMember)) {
ctx.reply(EmbedUtil.noEntryEmbed(ctx.getLocalized("commands.ban.i_cannot_ban_this_member"))).setEphemeral(true).queue();
return;
}
}
String reasonString = reason == null ? ctx.getLocalized("commands.noreason") : reason;
EmbedBuilder dmEmbed = new EmbedBuilder().setColor(CaseType.BAN.getEmbedColor()).setAuthor(ctx.getLocalized("commands.ban.you_have_been_banned", guild.getName()), null, guild.getIconUrl()).addField("Moderator", sender.getAsMention() + " (" + sender.getUser().getAsTag() + ")", true);
if (reason != null)
dmEmbed.addField(ctx.getLocalized("commands.reason"), reasonString, true);
event.deferReply(true).flatMap(hook -> targetUser.openPrivateChannel()).flatMap((c) -> c.sendMessageEmbeds(dmEmbed.build())).mapToResult().flatMap((result) -> guild.ban(targetUser, delDays, reason)).queue((x) -> {
ModCase modCase = ModCase.createModCase(CaseType.BAN, guild.getIdLong(), targetUser.getIdLong(), sender.getIdLong(), reason);
MessageEmbed confirmationEmbed = new EmbedBuilder().setColor(EmbedUtil.SUCCESS_COLOR).setAuthor(ctx.getLocalized("commands.ban.has_been_banned", targetUser.getAsTag()), null, targetUser.getEffectiveAvatarUrl()).addField(ctx.getLocalized("commands.reason"), reasonString, true).addField(ctx.getLocalized("commands.duration"), "∞", true).build();
event.getHook().sendMessageEmbeds(confirmationEmbed).queue();
if (ctx.getGuildData().getLogChannel() != null) {
TextChannel logChannel = ctx.getGuildData().getLogChannel();
MessageEmbed logEmbed = new EmbedBuilder().setColor(CaseType.BAN.getEmbedColor()).setAuthor("Ban • " + targetUser.getAsTag(), null, targetUser.getEffectiveAvatarUrl()).addField(ctx.getLocalized("commands.reason"), reasonString, true).addField("Moderator", sender.getAsMention() + " (" + sender.getUser().getAsTag() + ")", true).addField(ctx.getLocalized("commands.duration"), "∞", true).setFooter(ctx.getLocalized("commands.user_id", targetUser.getIdLong())).build();
logChannel.sendMessageEmbeds(logEmbed).queue(s -> {
}, e -> {
});
}
}, e -> event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(ctx.getLocalized("general.unknown_error_occured"))).setEphemeral(true).queue());
}
Aggregations