Cleaned some code in the command execution sections

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-05-16 00:39:40 +02:00
parent 68b3cc941c
commit 32ee3c4ee1
10 changed files with 63 additions and 86 deletions

View File

@ -23,7 +23,7 @@ public class MoviesQuoteBot {
public static final String PREFIX = "!"; public static final String PREFIX = "!";
public static final String NAME = "Movies Quote Bot"; public static final String NAME = "Movies Quote Bot";
public static final String DESCRIPTION = "I may know quotes from movies."; public static final String DESCRIPTION = "I may know quotes from movies.";
public static final String VERSION = "0.6"; public static final String VERSION = "0.7";
public static final String KILL_SWITCH_FILE = "system_locked"; public static final String KILL_SWITCH_FILE = "system_locked";
public static final String MAINTENANCE_MODE_FILE = "maintenance_mode_locked"; public static final String MAINTENANCE_MODE_FILE = "maintenance_mode_locked";
private static final Logger logger = LoggerFactory.getLogger(MoviesQuoteBot.class.getCanonicalName()); private static final Logger logger = LoggerFactory.getLogger(MoviesQuoteBot.class.getCanonicalName());

View File

@ -1,6 +1,7 @@
package xyz.vallat.louis.commands; package xyz.vallat.louis.commands;
import com.github.wtekiela.opensub4j.response.SubtitleInfo; import com.github.wtekiela.opensub4j.response.SubtitleInfo;
import discord4j.common.util.Snowflake;
import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.reaction.ReactionEmoji; import discord4j.core.object.reaction.ReactionEmoji;
import discord4j.core.spec.EmbedCreateSpec; import discord4j.core.spec.EmbedCreateSpec;
@ -30,16 +31,12 @@ public abstract class Command {
protected final String name; protected final String name;
protected final String description; protected final String description;
protected final String usage; protected final String usage;
protected final int minArgs;
protected final int maxArgs;
protected final Options options; protected final Options options;
protected Command(String name, String description, String usage, int minArgs, int maxArgs) { protected Command(String name, String description, String usage) {
this.name = name; this.name = name;
this.description = description; this.description = description;
this.usage = usage; this.usage = usage;
this.minArgs = minArgs;
this.maxArgs = maxArgs;
this.options = new Options(); this.options = new Options();
} }
@ -62,6 +59,14 @@ public abstract class Command {
return name; return name;
} }
protected Snowflake getUser(MessageCreateEvent event) {
return event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null;
}
protected Snowflake getGuild(MessageCreateEvent event) {
return event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null;
}
protected Mono<Void> unknownLanguage(MessageCreateEvent event, String lang) { protected Mono<Void> unknownLanguage(MessageCreateEvent event, String lang) {
return event.getMessage().getChannel() return event.getMessage().getChannel()
.flatMap(channel -> .flatMap(channel ->

View File

@ -20,12 +20,11 @@ public class Config extends Command {
private static final String LANG_FIELD_NAME = "Language"; private static final String LANG_FIELD_NAME = "Language";
public Config(String name) { public Config(String name) {
super(name, "Configure your own experience.", name + " [-g|--global] [-l/--lang 'default language'|-rl/--reset-lang]", 0, 0); super(name, "Configure your own experience.", name + " [-g|--global] [-l/--lang 'default language'|-rl/--reset-lang]");
OptionGroup langOrResetLang = new OptionGroup()
.addOption(Option.builder("l").longOpt("lang").desc("Specify your default language").hasArg().build())
.addOption(Option.builder("rl").longOpt("reset-lang").desc("Reset your default language").build());
options.addOption(Option.builder("g").longOpt("global").desc("Specify that this configuration should be global.").build()); options.addOption(Option.builder("g").longOpt("global").desc("Specify that this configuration should be global.").build());
options.addOptionGroup(langOrResetLang); options.addOptionGroup(new OptionGroup()
.addOption(Option.builder("l").longOpt("lang").desc("Specify your default language").hasArg().build())
.addOption(Option.builder("rl").longOpt("reset-lang").desc("Reset your default language").build()));
} }
@Override @Override
@ -33,35 +32,23 @@ public class Config extends Command {
try { try {
CommandLine cmd = new DefaultParser().parse(options, CommandLine cmd = new DefaultParser().parse(options,
event.getMessage().getContent().substring(name.length()).split(" ")); event.getMessage().getContent().substring(name.length()).split(" "));
Snowflake user = getUser(event);
Snowflake guild = cmd.hasOption("g") ? null : getGuild(event);
Lang language = cmd.hasOption("l") ? LanguageManager.getLangFromAny(cmd.getOptionValue("l")) : null; Lang language = cmd.hasOption("l") ? LanguageManager.getLangFromAny(cmd.getOptionValue("l")) : null;
if (language == null && cmd.hasOption("l")) return unknownLanguage(event, cmd.getOptionValue("l"));
return event.getMessage().getChannel().flatMap(messageChannel -> messageChannel.createEmbed(embed -> { return event.getMessage().getChannel().flatMap(messageChannel -> messageChannel.createEmbed(embed -> {
Snowflake user = event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null; embed.setTitle("Configuration").setColor(Color.RED).setTimestamp(Instant.now());
Snowflake guild = event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null; if (user == null)
if (cmd.hasOption("g")) guild = null; embed.setDescription("I cannot set a null user's preference. Sorry.").setColor(Color.ORANGE);
embed.setTitle("Configuration").setColor(Color.RED);
if (user == null) embed.setDescription("What? Are you a non-existent user? A bug in the matrix?");
else { else {
embed.setDescription("A configuration change has been noticed."); embed.setDescription("A configuration change has been noticed.");
if (cmd.hasOption("l")) { if (cmd.hasOption("l")) UserConfigManager.setDefaultLanguage(user, guild, language);
if (language == null) else if (cmd.hasOption("rl")) UserConfigManager.setDefaultLanguage(user, guild, null);
embed.setColor(Color.ORANGE) else embed.setDescription("<@" + user.asString() + ">'s configuration.");
.setDescription("The provided language is unknown. Try again with another one. Or don't try at all.");
else {
UserConfigManager.setDefaultLanguage(user, guild, language);
embed.addField(LANG_FIELD_NAME, language.getEnglish(), true);
}
} else if (cmd.hasOption("rl")) {
UserConfigManager.setDefaultLanguage(user, guild, null);
Lang l = UserConfigManager.getDefaultLanguage(user, guild); Lang l = UserConfigManager.getDefaultLanguage(user, guild);
embed.addField(LANG_FIELD_NAME, l == null ? NO_LANGUAGE : l.getEnglish(), false); embed.addField(LANG_FIELD_NAME, l == null ? NO_LANGUAGE : l.getEnglish(), true)
} else { .setColor(Color.MEDIUM_SEA_GREEN);
embed.setDescription("<@" + user.asString() + ">'s configuration.");
Lang l = UserConfigManager.getDefaultLanguage(user, guild);
embed.addField(LANG_FIELD_NAME, l == null ? NO_LANGUAGE : l.getEnglish(), false);
} }
embed.setColor(Color.MEDIUM_SEA_GREEN);
}
embed.setTimestamp(Instant.now());
})).then().onErrorResume(throwable -> fatalError(event, throwable)); })).then().onErrorResume(throwable -> fatalError(event, throwable));
} catch ( } catch (
ParseException e) { ParseException e) {

View File

@ -35,7 +35,7 @@ public class Download extends Command {
private static final Logger logger = LoggerFactory.getLogger(Download.class.getCanonicalName()); private static final Logger logger = LoggerFactory.getLogger(Download.class.getCanonicalName());
public Download(String name) { public Download(String name) {
super(name, "Download a subtitle.", name + " [-l|--lang <lang>] -i|--imdb <imdb> | -t|--title <title>", 3, 3); super(name, "Download a subtitle.", name + " [-l|--lang <lang>] -i|--imdb <imdb> | -t|--title <title>");
OptionGroup iOrT = new OptionGroup() OptionGroup iOrT = new OptionGroup()
.addOption(Option.builder("i").longOpt("imdb").hasArg().desc("imdb identifier for the film").build()) .addOption(Option.builder("i").longOpt("imdb").hasArg().desc("imdb identifier for the film").build())
.addOption(Option.builder("t").longOpt("title").hasArgs().numberOfArgs(Option.UNLIMITED_VALUES).desc("movie title for the film").build()); .addOption(Option.builder("t").longOpt("title").hasArgs().numberOfArgs(Option.UNLIMITED_VALUES).desc("movie title for the film").build());
@ -48,8 +48,8 @@ public class Download extends Command {
public Mono<Void> execute(MessageCreateEvent event) { public Mono<Void> execute(MessageCreateEvent event) {
try { try {
CommandLine cmd = new DefaultParser().parse(options, getArgArray(event)); CommandLine cmd = new DefaultParser().parse(options, getArgArray(event));
Snowflake user = event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null; Snowflake user = getUser(event);
Snowflake guild = event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null; Snowflake guild = getGuild(event);
if (user == null) return Mono.empty(); if (user == null) return Mono.empty();
Lang l; Lang l;
if (!cmd.hasOption("l")) { if (!cmd.hasOption("l")) {

View File

@ -10,7 +10,7 @@ import java.time.Instant;
public class Help extends Command { public class Help extends Command {
public Help(String name) { public Help(String name) {
super(name, "I need help. You need help. We all need help at some point.", name, 0, 0); super(name, "I need help. You need help. We all need help at some point.", name);
} }
@Override @Override

View File

@ -7,7 +7,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import xyz.vallat.louis.subtitles.OpenSubtitles; import xyz.vallat.louis.subtitles.OpenSubtitles;
import xyz.vallat.louis.subtitles.exceptions.UnauthorizedException;
import java.time.Instant; import java.time.Instant;
@ -17,7 +16,7 @@ public class ListLang extends Command {
public ListLang(String name) { public ListLang(String name) {
super(name, "List all languages attached to a movie title or an IMDB Identifier.", super(name, "List all languages attached to a movie title or an IMDB Identifier.",
name + " -i|--imdb <imdb identifier> | -t|--title <title>", 2, 2); name + " -i|--imdb <imdb identifier> | -t|--title <title>");
OptionGroup iOrT = new OptionGroup() OptionGroup iOrT = new OptionGroup()
.addOption(Option.builder("i").longOpt("imdb").desc("specify the imdb identifier").hasArg().build()) .addOption(Option.builder("i").longOpt("imdb").desc("specify the imdb identifier").hasArg().build())
.addOption(Option.builder("t").longOpt("title").desc("specify the movie's title").hasArgs().numberOfArgs(Option.UNLIMITED_VALUES).build()); .addOption(Option.builder("t").longOpt("title").desc("specify the movie's title").hasArgs().numberOfArgs(Option.UNLIMITED_VALUES).build());
@ -35,12 +34,10 @@ public class ListLang extends Command {
.flatMap(channel -> event.getMessage().addReaction(WAITING).then(event.getMessage().getChannel() .flatMap(channel -> event.getMessage().addReaction(WAITING).then(event.getMessage().getChannel()
.flatMap(messageChannel -> messageChannel.createEmbed(embed -> { .flatMap(messageChannel -> messageChannel.createEmbed(embed -> {
embed.setTitle("Subtitle languages").setColor(Color.RED); embed.setTitle("Subtitle languages").setColor(Color.RED);
try {
if (OpenSubtitles.isLoggedIn()) if (OpenSubtitles.isLoggedIn())
createEmbedListLang(imdbOrTitle, embed, cmd.hasOption("i")); createEmbedListLang(imdbOrTitle, embed, cmd.hasOption("i"));
else throw new UnauthorizedException("isLoggedIn returned false."); else {
} catch (UnauthorizedException e) { logger.error("Not logged in on OpenSubtitles! isLoggedIn returned false!");
logger.error("Not logged in on OpenSubtitles! {}", e.getMessage());
logger.warn("It may be due to a website being down. If it's not " + logger.warn("It may be due to a website being down. If it's not " +
"the case, please fix this issue quickly."); "the case, please fix this issue quickly.");
embed.setDescription("I cannot search for subtitle languages right now. Sorry."); embed.setDescription("I cannot search for subtitle languages right now. Sorry.");

View File

@ -6,13 +6,11 @@ import reactor.core.publisher.Mono;
public class Ping extends Command { public class Ping extends Command {
public Ping(String name) { public Ping(String name) {
super(name, "Replies as soon as possible to check the bot's health.", name, 0, 0); super(name, "Replies as soon as possible to check the bot's health.", name);
} }
@Override @Override
public Mono<Void> execute(MessageCreateEvent event) { public Mono<Void> execute(MessageCreateEvent event) {
return event.getMessage().getChannel() return event.getMessage().getChannel().flatMap(c -> c.createMessage("Pong!")).then().onErrorResume(t -> fatalError(event, t));
.flatMap(channel -> channel.createMessage("Pong!"))
.then().onErrorResume(throwable -> fatalError(event, throwable));
} }
} }

View File

@ -23,7 +23,7 @@ public class Quote extends Command {
public Quote(String name) { public Quote(String name) {
super(name, "Get a random quote from any movie.", name + " [-l|--lang <lang>] " + super(name, "Get a random quote from any movie.", name + " [-l|--lang <lang>] " +
"[-s|--search <quote extract>] [-i|--imdb imdb_identifier]|[-t|--title title]", 0, 1); "[-s|--search <quote extract>] [-i|--imdb imdb_identifier]|[-t|--title title]");
OptionGroup iOrT = new OptionGroup() OptionGroup iOrT = new OptionGroup()
.addOption(Option.builder("i").longOpt("imdb").desc("specify an IMDB identifier").hasArg().build()) .addOption(Option.builder("i").longOpt("imdb").desc("specify an IMDB identifier").hasArg().build())
.addOption(Option.builder("t").longOpt("title").desc("specify a title").hasArgs() .addOption(Option.builder("t").longOpt("title").desc("specify a title").hasArgs()
@ -41,11 +41,11 @@ public class Quote extends Command {
CommandLine cmd = new DefaultParser().parse(options, CommandLine cmd = new DefaultParser().parse(options,
event.getMessage().getContent().substring(name.length()).split(" ")); event.getMessage().getContent().substring(name.length()).split(" "));
Lang language; Lang language;
Snowflake user = event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null; Snowflake user = getUser(event);
Snowflake guild = event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null; Snowflake guild = getGuild(event);
if (user == null) return Mono.empty();
if (cmd.hasOption("l")) language = LanguageManager.getLangFromAny(cmd.getOptionValue("l")); if (cmd.hasOption("l")) language = LanguageManager.getLangFromAny(cmd.getOptionValue("l"));
else language = UserConfigManager.getDefaultLanguage(user, guild); else language = user == null ? LanguageManager.getLangFromAny("english") :
UserConfigManager.getDefaultLanguage(user, guild);
if (language == null) language = LanguageManager.getLangFromAny("english"); if (language == null) language = LanguageManager.getLangFromAny("english");
String imdb = cmd.hasOption("i") ? cmd.getOptionValue("i") : null; String imdb = cmd.hasOption("i") ? cmd.getOptionValue("i") : null;
String title = cmd.hasOption("t") ? String.join(" ", cmd.getOptionValues("t")) : null; String title = cmd.hasOption("t") ? String.join(" ", cmd.getOptionValues("t")) : null;

View File

@ -1,7 +1,7 @@
package xyz.vallat.louis.commands; package xyz.vallat.louis.commands;
import discord4j.common.util.Snowflake;
import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Guild;
import discord4j.rest.util.Color; import discord4j.rest.util.Color;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import xyz.vallat.louis.MoviesQuoteBot; import xyz.vallat.louis.MoviesQuoteBot;
@ -14,38 +14,27 @@ import java.time.Instant;
public class Version extends Command { public class Version extends Command {
public Version(String name) { public Version(String name) {
super(name, "Give some information about the bot.", name, 0, 0); super(name, "Give some information about the bot.", name);
} }
@Override @Override
public Mono<Void> execute(MessageCreateEvent event) { public Mono<Void> execute(MessageCreateEvent event) {
return event.getMessage().getChannel() return event.getMessage().getChannel().flatMap(channel -> channel.createEmbed(embed -> {
.flatMap(channel -> channel embed
.createEmbed(embedCreateSpec -> {
embedCreateSpec
.setColor(Color.MEDIUM_SEA_GREEN) .setColor(Color.MEDIUM_SEA_GREEN)
.setTitle(MoviesQuoteBot.NAME) .setTitle(MoviesQuoteBot.NAME)
.setDescription(MoviesQuoteBot.DESCRIPTION) .setDescription(MoviesQuoteBot.DESCRIPTION)
.addField("Guilds", String.valueOf(DiscordManager.getGuilds().block()), true) .addField("Guilds", String.valueOf(DiscordManager.getGuilds().block()), true)
.addField("Subtitles imported", String.valueOf(SubtitleManager.getNumberOfSubtitles()), true) .addField("Subtitles imported", String.valueOf(SubtitleManager.getNumberOfSubtitles()), true)
.addField("Lines imported", String.valueOf(SubtitleLineManager.getNumberOfSubtitleLines()), true); .addField("Lines imported", String.valueOf(SubtitleLineManager.getNumberOfSubtitleLines()), true);
if (event.getGuildId().isPresent()) { Snowflake guild = getGuild(event);
Guild guild = event.getGuild().block();
if (guild != null) if (guild != null)
embedCreateSpec.addField("This guild imported", embed.addField("This guild imported",
SubtitleLineManager SubtitleLineManager.getNumberOfSubtitleLinesByGuild(guild.asLong()) +
.getNumberOfSubtitleLinesByGuild(guild.getId().asLong()) +
" subtitles lines, from " + " subtitles lines, from " +
SubtitleManager SubtitleManager.getNumberOfSubtitlesByGuild(guild.asLong()) + " subtitles.", true);
.getNumberOfSubtitlesByGuild(guild.getId().asLong()) + " subtitles.", embed.addField("Version", MoviesQuoteBot.VERSION, true).setTimestamp(Instant.now());
true); })).then().onErrorResume(throwable -> fatalError(event, throwable));
}
embedCreateSpec.addField("Version", MoviesQuoteBot.VERSION, true)
.setTimestamp(Instant.now());
}
)
)
.then().onErrorResume(throwable -> fatalError(event, throwable));
} }
} }

View File

@ -12,7 +12,8 @@ public enum EnvironmentVariables {
OS_USER_AGENT("OPEN_SUBTITLES_USER_AGENT"), OS_USER_AGENT("OPEN_SUBTITLES_USER_AGENT"),
SOCKET_PORT("SOCKET_PORT"), SOCKET_PORT("SOCKET_PORT"),
SOCKET_HOST("SOCKET_HOST"), SOCKET_HOST("SOCKET_HOST"),
OMDB_API_KEY("OMDB_API_KEY"); OMDB_API_KEY("OMDB_API_KEY"),
DEFAULT_LANGUAGE("DEFAULT_LANG");
private final String value; private final String value;