use of fredboat.commandmeta.abs.Command in project FredBoat by Frederikam.
the class CommandContextParser method parse.
/**
* @param event the event to be parsed
* @return The full context for the triggered command, or null if it's not a command that we know.
*/
@Nullable
public CommandContext parse(MessageReceivedEvent event) {
String raw = event.getMessage().getContentRaw();
String input;
boolean isMention = false;
Matcher mentionMatcher = MENTION_PREFIX.matcher(raw);
// either starts with a mention of us
if (mentionMatcher.find() && mentionMatcher.group(2).equals(event.getJDA().getSelfUser().getId())) {
input = mentionMatcher.group(3).trim();
isMention = true;
} else // or starts with a custom/default prefix
{
String prefix = PrefixCommand.giefPrefix(event.getGuild());
String defaultPrefix = appConfig.getPrefix();
if (raw.startsWith(prefix)) {
input = raw.substring(prefix.length());
if (prefix.equals(defaultPrefix)) {
Metrics.prefixParsed.labels("default").inc();
} else {
Metrics.prefixParsed.labels("custom").inc();
}
} else {
// hardcoded check for the help or prefix command that is always displayed as FredBoat status
if (raw.startsWith(defaultPrefix + CommandInitializer.HELP_COMM_NAME) || raw.startsWith(defaultPrefix + CommandInitializer.PREFIX_COMM_NAME)) {
Metrics.prefixParsed.labels("default").inc();
input = raw.substring(defaultPrefix.length());
} else {
// no match neither mention nor custom/default prefix
return null;
}
}
}
// eliminate possible whitespace between the mention/prefix and the rest of the input
input = input.trim();
if (input.isEmpty()) {
if (isMention) {
// just a mention and nothing else? trigger the prefix command
input = "prefix";
} else {
// no command will be detectable from an empty input
return null;
}
}
// the \p{javaSpaceChar} instead of the better known \s is used because it actually includes unicode whitespaces
String[] args = input.split("\\p{javaSpaceChar}+");
if (args.length < 1) {
// while this shouldn't technically be possible due to the preprocessing of the input, better be safe than throw exceptions
return null;
}
String commandTrigger = args[0];
Command command = CommandRegistry.findCommand(commandTrigger.toLowerCase());
if (command == null) {
log.info("Unknown command:\t{}", commandTrigger);
return null;
} else {
return new CommandContext(event.getGuild(), event.getTextChannel(), event.getMember(), event.getMessage(), isMention, commandTrigger, // exclude args[0] that contains the command trigger
Arrays.copyOfRange(args, 1, args.length), input.replaceFirst(commandTrigger, "").trim(), command);
}
}
use of fredboat.commandmeta.abs.Command in project FredBoat by Frederikam.
the class CommandsCommand method onInvoke.
@Override
public void onInvoke(@Nonnull CommandContext context) {
if (!context.hasArguments()) {
Collection<Module> enabledModules = context.getEnabledModules();
if (!PermsUtil.checkPerms(PermissionLevel.BOT_ADMIN, context.invoker)) {
// dont show admin commands/modules for non admins
enabledModules.remove(Module.ADMIN);
}
String prefixAndCommand = "`" + context.getPrefix() + CommandInitializer.COMMANDS_COMM_NAME;
List<String> translatedModuleNames = enabledModules.stream().map(module -> context.i18n(module.translationKey)).collect(Collectors.toList());
context.reply(context.i18nFormat("modulesCommands", prefixAndCommand + " <module>`", prefixAndCommand + " " + ALL + "`") + "\n\n" + context.i18nFormat("musicCommandsPromotion", "`" + context.getPrefix() + CommandInitializer.MUSICHELP_COMM_NAME + "`") + "\n\n" + context.i18n("modulesEnabledInGuild") + " **" + String.join("**, **", translatedModuleNames) + "**" + "\n" + context.i18nFormat("commandsModulesHint", "`" + context.getPrefix() + CommandInitializer.MODULES_COMM_NAME + "`"));
return;
}
List<Module> showHelpFor;
if (context.rawArgs.toLowerCase().contains(ALL.toLowerCase())) {
showHelpFor = new ArrayList<>(Arrays.asList(Module.values()));
if (!PermsUtil.checkPerms(PermissionLevel.BOT_ADMIN, context.invoker)) {
// dont show admin commands/modules for non admins
showHelpFor.remove(Module.ADMIN);
}
} else {
Module module = CommandRegistry.whichModule(context.rawArgs, context);
if (module == null) {
context.reply(context.i18nFormat("moduleCantParse", "`" + context.getPrefix() + context.command.name) + "`");
return;
} else {
showHelpFor = Collections.singletonList(module);
}
}
EmbedBuilder eb = CentralMessaging.getColoredEmbedBuilder();
for (Module module : showHelpFor) {
eb = addModuleCommands(eb, context, CommandRegistry.getCommandModule(module));
}
eb.addField("", context.i18nFormat("commandsMoreHelp", "`" + TextUtils.escapeMarkdown(context.getPrefix()) + CommandInitializer.HELP_COMM_NAME + " <command>`"), false);
context.reply(eb.build());
}
use of fredboat.commandmeta.abs.Command in project FredBoat by Frederikam.
the class CommandsCommand method addModuleCommands.
private EmbedBuilder addModuleCommands(@Nonnull EmbedBuilder embedBuilder, @Nonnull CommandContext context, @Nonnull CommandRegistry module) {
List<Command> commands = module.getDeduplicatedCommands().stream().filter(command -> {
if (command instanceof ICommandRestricted) {
if (((ICommandRestricted) command).getMinimumPerms().getLevel() >= PermissionLevel.BOT_ADMIN.getLevel()) {
return PermsUtil.checkPerms(PermissionLevel.BOT_ADMIN, context.invoker);
}
}
return true;
}).collect(Collectors.toList());
String prefix = context.getPrefix();
if (commands.size() >= 6) {
// split the commands into three even columns
StringBuilder[] sbs = new StringBuilder[3];
sbs[0] = new StringBuilder();
sbs[1] = new StringBuilder();
sbs[2] = new StringBuilder();
int i = 0;
for (Command c : commands) {
if (c instanceof DestroyCommand) {
// dont want to publicly show this one
continue;
}
sbs[i++ % 3].append(prefix).append(c.name).append("\n");
}
return embedBuilder.addField(context.i18n(module.module.translationKey), sbs[0].toString(), true).addField("", sbs[1].toString(), true).addField("", sbs[2].toString(), true);
} else {
StringBuilder sb = new StringBuilder();
for (Command c : commands) {
sb.append(prefix).append(c.name).append("\n");
}
return embedBuilder.addField(context.i18n(module.module.translationKey), sb.toString(), true).addBlankField(true).addBlankField(true);
}
}
use of fredboat.commandmeta.abs.Command in project FredBoat by Frederikam.
the class CommandManager method prefixCalled.
public void prefixCalled(CommandContext context) {
Guild guild = context.guild;
Command invoked = context.command;
TextChannel channel = context.channel;
Member invoker = context.invoker;
totalCommandsExecuted.incrementAndGet();
Metrics.commandsExecuted.labels(invoked.getClass().getSimpleName()).inc();
if (FeatureFlags.PATRON_VALIDATION.isActive()) {
PatronageChecker.Status status = patronageChecker.getStatus(guild);
if (!status.isValid()) {
String msg = "Access denied. This bot can only be used if invited from <https://patron.fredboat.com/> " + "by someone who currently has a valid pledge on Patreon.\n**Denial reason:** " + status.getReason() + "\n\n";
msg += "Do you believe this to be a mistake? If so reach out to Fre_d on Patreon <" + BotConstants.PATREON_CAMPAIGN_URL + ">";
context.reply(msg);
return;
}
}
// Hardcode music commands in FredBoatHangout. Blacklist any channel that isn't #spam_and_music or #staff, but whitelist Admins
if (guild.getIdLong() == BotConstants.FREDBOAT_HANGOUT_ID && DiscordUtil.isOfficialBot(credentials)) {
if (// #spam_and_music
!channel.getId().equals("174821093633294338") && // #staff
!channel.getId().equals("217526705298866177") && !PermsUtil.checkPerms(PermissionLevel.ADMIN, invoker)) {
context.deleteMessage();
context.replyWithName("Please read <#219483023257763842> for server rules and only use commands in <#174821093633294338>!", msg -> CentralMessaging.restService.schedule(() -> CentralMessaging.deleteMessage(msg), 5, TimeUnit.SECONDS));
return;
}
}
if (disabledCommands.contains(invoked)) {
context.replyWithName("Sorry the `" + context.command.name + "` command is currently disabled. Please try again later");
return;
}
if (invoked instanceof ICommandRestricted) {
if (!PermsUtil.checkPermsWithFeedback(((ICommandRestricted) invoked).getMinimumPerms(), context)) {
return;
}
}
if (invoked instanceof IMusicCommand) {
musicTextChannelProvider.setMusicChannel(channel);
}
try {
invoked.onInvoke(context);
} catch (Exception e) {
TextUtils.handleException(e, context);
}
}
Aggregations