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 NAME = "Movies Quote Bot";
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 MAINTENANCE_MODE_FILE = "maintenance_mode_locked";
private static final Logger logger = LoggerFactory.getLogger(MoviesQuoteBot.class.getCanonicalName());

View File

@ -1,6 +1,7 @@
package xyz.vallat.louis.commands;
import com.github.wtekiela.opensub4j.response.SubtitleInfo;
import discord4j.common.util.Snowflake;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.reaction.ReactionEmoji;
import discord4j.core.spec.EmbedCreateSpec;
@ -30,16 +31,12 @@ public abstract class Command {
protected final String name;
protected final String description;
protected final String usage;
protected final int minArgs;
protected final int maxArgs;
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.description = description;
this.usage = usage;
this.minArgs = minArgs;
this.maxArgs = maxArgs;
this.options = new Options();
}
@ -62,6 +59,14 @@ public abstract class Command {
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) {
return event.getMessage().getChannel()
.flatMap(channel ->

View File

@ -20,12 +20,11 @@ public class Config extends Command {
private static final String LANG_FIELD_NAME = "Language";
public Config(String name) {
super(name, "Configure your own experience.", name + " [-g|--global] [-l/--lang 'default language'|-rl/--reset-lang]", 0, 0);
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());
super(name, "Configure your own experience.", name + " [-g|--global] [-l/--lang 'default language'|-rl/--reset-lang]");
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
@ -33,35 +32,23 @@ public class Config extends Command {
try {
CommandLine cmd = new DefaultParser().parse(options,
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;
if (language == null && cmd.hasOption("l")) return unknownLanguage(event, cmd.getOptionValue("l"));
return event.getMessage().getChannel().flatMap(messageChannel -> messageChannel.createEmbed(embed -> {
Snowflake user = event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null;
Snowflake guild = event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null;
if (cmd.hasOption("g")) guild = null;
embed.setTitle("Configuration").setColor(Color.RED);
if (user == null) embed.setDescription("What? Are you a non-existent user? A bug in the matrix?");
embed.setTitle("Configuration").setColor(Color.RED).setTimestamp(Instant.now());
if (user == null)
embed.setDescription("I cannot set a null user's preference. Sorry.").setColor(Color.ORANGE);
else {
embed.setDescription("A configuration change has been noticed.");
if (cmd.hasOption("l")) {
if (language == null)
embed.setColor(Color.ORANGE)
.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);
if (cmd.hasOption("l")) UserConfigManager.setDefaultLanguage(user, guild, language);
else if (cmd.hasOption("rl")) UserConfigManager.setDefaultLanguage(user, guild, null);
else embed.setDescription("<@" + user.asString() + ">'s configuration.");
Lang l = UserConfigManager.getDefaultLanguage(user, guild);
embed.addField(LANG_FIELD_NAME, l == null ? NO_LANGUAGE : l.getEnglish(), false);
} else {
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.addField(LANG_FIELD_NAME, l == null ? NO_LANGUAGE : l.getEnglish(), true)
.setColor(Color.MEDIUM_SEA_GREEN);
}
embed.setColor(Color.MEDIUM_SEA_GREEN);
}
embed.setTimestamp(Instant.now());
})).then().onErrorResume(throwable -> fatalError(event, throwable));
} catch (
ParseException e) {

View File

@ -35,7 +35,7 @@ public class Download extends Command {
private static final Logger logger = LoggerFactory.getLogger(Download.class.getCanonicalName());
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()
.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());
@ -48,8 +48,8 @@ public class Download extends Command {
public Mono<Void> execute(MessageCreateEvent event) {
try {
CommandLine cmd = new DefaultParser().parse(options, getArgArray(event));
Snowflake user = event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null;
Snowflake guild = event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null;
Snowflake user = getUser(event);
Snowflake guild = getGuild(event);
if (user == null) return Mono.empty();
Lang l;
if (!cmd.hasOption("l")) {

View File

@ -10,7 +10,7 @@ import java.time.Instant;
public class Help extends Command {
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

View File

@ -7,7 +7,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import xyz.vallat.louis.subtitles.OpenSubtitles;
import xyz.vallat.louis.subtitles.exceptions.UnauthorizedException;
import java.time.Instant;
@ -17,7 +16,7 @@ public class ListLang extends Command {
public ListLang(String name) {
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()
.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());
@ -35,12 +34,10 @@ public class ListLang extends Command {
.flatMap(channel -> event.getMessage().addReaction(WAITING).then(event.getMessage().getChannel()
.flatMap(messageChannel -> messageChannel.createEmbed(embed -> {
embed.setTitle("Subtitle languages").setColor(Color.RED);
try {
if (OpenSubtitles.isLoggedIn())
createEmbedListLang(imdbOrTitle, embed, cmd.hasOption("i"));
else throw new UnauthorizedException("isLoggedIn returned false.");
} catch (UnauthorizedException e) {
logger.error("Not logged in on OpenSubtitles! {}", e.getMessage());
else {
logger.error("Not logged in on OpenSubtitles! isLoggedIn returned false!");
logger.warn("It may be due to a website being down. If it's not " +
"the case, please fix this issue quickly.");
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 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
public Mono<Void> execute(MessageCreateEvent event) {
return event.getMessage().getChannel()
.flatMap(channel -> channel.createMessage("Pong!"))
.then().onErrorResume(throwable -> fatalError(event, throwable));
return event.getMessage().getChannel().flatMap(c -> c.createMessage("Pong!")).then().onErrorResume(t -> fatalError(event, t));
}
}

View File

@ -23,7 +23,7 @@ public class Quote extends Command {
public Quote(String name) {
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()
.addOption(Option.builder("i").longOpt("imdb").desc("specify an IMDB identifier").hasArg().build())
.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,
event.getMessage().getContent().substring(name.length()).split(" "));
Lang language;
Snowflake user = event.getMessage().getAuthor().isPresent() ? event.getMessage().getAuthor().get().getId() : null;
Snowflake guild = event.getMessage().getGuildId().isPresent() ? event.getMessage().getGuildId().get() : null;
if (user == null) return Mono.empty();
Snowflake user = getUser(event);
Snowflake guild = getGuild(event);
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");
String imdb = cmd.hasOption("i") ? cmd.getOptionValue("i") : null;
String title = cmd.hasOption("t") ? String.join(" ", cmd.getOptionValues("t")) : null;

View File

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