Migrate madame command to slash

This commit is contained in:
SebClem 2022-05-16 18:25:00 +02:00
parent 02b19c98d2
commit a41b4c76f1
Signed by: sebclem
GPG Key ID: 5A4308F6A359EA50
12 changed files with 215 additions and 204 deletions

View File

@ -8,10 +8,7 @@ import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.Broken.audio.AudioM; import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
@ -29,7 +26,6 @@ import org.jetbrains.annotations.NotNull;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import java.awt.*; import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -71,7 +67,7 @@ public class BotListener extends ListenerAdapter {
String message = guildPref.getWelcomeMessage().replaceAll("@name", event.getMember().getAsMention()); String message = guildPref.getWelcomeMessage().replaceAll("@name", event.getMember().getAsMention());
logger.debug(message); logger.debug(message);
chanel.sendMessage(message).queue(); chanel.sendMessage(message).queue();
}else { } else {
logger.fatal("[" + event.getGuild().getName() + "] : Welcome chanel is null !"); logger.fatal("[" + event.getGuild().getName() + "] : Welcome chanel is null !");
} }
} }
@ -123,8 +119,7 @@ public class BotListener extends ListenerAdapter {
logger.debug("I'm alone, close audio connection."); logger.debug("I'm alone, close audio connection.");
AudioM.getInstance(event.getGuild()).stop(); AudioM.getInstance(event.getGuild()).stop();
} }
} } else if (event.getMember().getUser() == MainBot.jda.getSelfUser()) {
else if (event.getMember().getUser() == MainBot.jda.getSelfUser()){
AudioM.getInstance(event.getGuild()).clearLastButton(); AudioM.getInstance(event.getGuild()).clearLastButton();
} }
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild()); AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
@ -165,7 +160,29 @@ public class BotListener extends ListenerAdapter {
HashMap<String, SlashCommand> commands = MainBot.slashCommands; HashMap<String, SlashCommand> commands = MainBot.slashCommands;
super.onSlashCommand(event); super.onSlashCommand(event);
if (commands.containsKey(event.getName())) { if (commands.containsKey(event.getName())) {
commands.get(event.getName()).action(event); SlashCommand commandRunner = commands.get(event.getName());
// It's form private message
if (!event.isFromGuild()) {
if (commandRunner.isPrivateUsable()) {
commandRunner.action(event);
} else {
MessageEmbed message = EmbedMessageUtils.buildStandar(new EmbedBuilder()
.setTitle(":no_entry_sign: This command is not usable in private message")
.setColor(Color.red)
);
event.replyEmbeds(message).setEphemeral(true).queue();
}
} else {
if (!commandRunner.isNSFW() || event.getTextChannel().isNSFW()) {
commandRunner.action(event);
} else {
MessageEmbed message = EmbedMessageUtils.buildStandar(new EmbedBuilder()
.setTitle(":underage: This command is only usable in NSFW channels")
.setColor(Color.red)
);
event.replyEmbeds(message).setEphemeral(true).queue();
}
}
} }
} }
@ -206,5 +223,4 @@ public class BotListener extends ListenerAdapter {
} }
} }

View File

@ -65,4 +65,6 @@ public class ReportUsers implements Commande {
public boolean isNSFW() { public boolean isNSFW() {
return false; return false;
} }
} }

View File

@ -38,5 +38,9 @@ public interface SlashCommand {
*/ */
boolean isNSFW(); boolean isNSFW();
boolean isPrivateUsable();
boolean isDisableByDefault();
} }

View File

@ -81,4 +81,14 @@ public class Cat implements SlashCommand {
public boolean isNSFW() { public boolean isNSFW() {
return false; return false;
} }
@Override
public boolean isPrivateUsable() {
return true;
}
@Override
public boolean isDisableByDefault() {
return false;
}
} }

View File

@ -55,4 +55,14 @@ public class Clear implements SlashCommand {
public boolean isNSFW() { public boolean isNSFW() {
return false; return false;
} }
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isDisableByDefault() {
return true;
}
} }

View File

@ -130,4 +130,14 @@ public class Music implements SlashCommand {
public boolean isNSFW() { public boolean isNSFW() {
return false; return false;
} }
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isDisableByDefault() {
return false;
}
} }

View File

@ -1,55 +1,18 @@
package net.Broken.Commands.Over18; package net.Broken.SlashCommands.Over18;
import net.Broken.Tools.Command.NoDev; import net.Broken.Tools.Command.NumberedSlashCommand;
import net.Broken.Tools.Command.NumberedCommande;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.io.IOException; import java.io.IOException;
public class Madame extends NumberedSlashCommand {
/**
* Madame command that return random picture from dites.bonjourmadame.fr
*/
@NoDev
public class Madame extends NumberedCommande {
public String HELP = "Yo really? Just type Madame to see some :cat:";
Logger logger = LogManager.getLogger(); Logger logger = LogManager.getLogger();
MessageReceivedEvent event;
public Madame() { public Madame() {
super(LogManager.getLogger(), "https://www.bonjourmadame.fr/page/", "/"); super(LogManager.getLogger(), "https://www.bonjourmadame.fr/page/", "/");
} }
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
/**
* Determines if the command is usable only by bot level admin user
*
* @return boolean
*/
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return true;
}
/** /**
* Detect if picture link go to Tepeee * Detect if picture link go to Tepeee
* *
@ -107,4 +70,29 @@ public class Madame extends NumberedCommande {
imgUrl = removeParams(imgUrl); imgUrl = removeParams(imgUrl);
return imgUrl; return imgUrl;
} }
@Override
public String getDescription() {
return "Return random image from bonjourmadame.fr";
}
@Override
public boolean isBotAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return true;
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isDisableByDefault() {
return true;
}
} }

View File

@ -46,4 +46,14 @@ public class Rank implements SlashCommand {
public boolean isNSFW() { public boolean isNSFW() {
return false; return false;
} }
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isDisableByDefault() {
return false;
}
} }

View File

@ -1,152 +0,0 @@
package net.Broken.Tools.Command;
import net.Broken.Commande;
import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.LimitChecker;
import net.Broken.Tools.TrueRandom;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Abstact class used for all command that need to find the max number of page on a web site.
*/
@Ignore
public abstract class NumberedCommande implements Commande {
protected int minNumber = 1;
protected int maxNumber = -1;
protected String baseURL;
protected String divClass;
protected String htmlType;
protected String urlSuffix;
protected LinkedBlockingQueue<Integer> randomQueue = new LinkedBlockingQueue<>();
private Logger logger = LogManager.getLogger();
/**
* Default constructor
*
* @param logger Logger used for logs
* @param baseURL WebSite base url
* @param divClass DivClass to search to extract image
* @param htmlType HTML tag to extract image (img)
*/
public NumberedCommande(Logger logger, String baseURL, String urlSuffix, String divClass, String htmlType) {
this.logger = logger;
this.baseURL = baseURL;
this.divClass = divClass;
this.htmlType = htmlType;
this.urlSuffix = urlSuffix;
try {
logger.debug("Checking max...");
maxNumber = LimitChecker.doYourJob(baseURL, 2, urlSuffix);
logger.info("Limit is " + maxNumber);
} catch (IOException e) {
logger.catching(e);
}
}
public NumberedCommande(Logger logger, String baseURL, String urlSuffix) {
this(logger, baseURL, urlSuffix, null, null);
}
@Override
public void action(String[] args, MessageReceivedEvent event) {
try {
if (args.length == 0) {
String result = poll();
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n" + result).queue();
} else {
switch (args[0].toLowerCase()) {
case "update":
logger.info("update commande from " + event.getMessage().getAuthor().getName());
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:arrow_right: Updating...").queue();
int newNumber = maxNumber;
try {
newNumber = LimitChecker.doYourJob(baseURL, maxNumber, urlSuffix);
} catch (IOException e) {
e.printStackTrace();
}
if (newNumber == maxNumber) {
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:arrow_right: 0 new picture found :cry:").queue();
} else if (newNumber - maxNumber == 1)
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:arrow_right: " + (newNumber - maxNumber) + " picture has been found :kissing_heart:").queue();
else
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:arrow_right: " + (newNumber - maxNumber) + " pictures has been found :kissing_heart:").queue();
logger.info((newNumber - maxNumber) + " new image(s) found.");
maxNumber = newNumber;
break;
case "get":
if (args.length >= 2) {
int number = -1;
try {
number = Integer.parseInt(args[1]);
URL url = new URL(baseURL + number + "-2/");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("GET");
huc.connect();
int result = huc.getResponseCode();
if (result == 200) {
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n" + baseURL + number + urlSuffix).queue();
} else {
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:warning: **__Error__** :warning:\n:arrow_right: Page not found (404)").queue();
}
} catch (NumberFormatException e) {
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:warning: **__Error__** :warning:\n:arrow_right: Bad argument. `//help " + this.toString().toLowerCase() + "` for more info ").queue();
} catch (IOException e) {
logger.catching(e);
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:warning: **__Error__** :warning:\n:arrow_right: Internal error...").queue();
}
} else {
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:warning: **__Error__** :warning:\n:arrow_right: Bad argument. `//help " + this.toString().toLowerCase() + "` for more info ").queue();
logger.warn("Bad Argument: " + event.getMessage().getContentRaw() + " From " + event.getAuthor().getName());
}
break;
default:
event.getTextChannel().sendMessage(event.getAuthor().getAsMention() + "\n:warning: **__Error__** :warning:\n:arrow_right: Bad argument. `//help " + this.toString().toLowerCase() + "` for more info ").queue();
logger.warn("Bad Argument: " + event.getMessage().getContentRaw() + " From " + event.getAuthor().getName());
break;
}
}
} catch (IOException e) {
logger.catching(e);
}
}
private void completeRandom() throws IOException {
TrueRandom trueRandom = TrueRandom.getINSTANCE();
ArrayList<Integer> numbers = trueRandom.getNumbers(minNumber, maxNumber);
randomQueue.addAll(numbers);
}
protected void checkRandom() throws IOException {
logger.trace("Queue size: " + randomQueue.size());
if (randomQueue.isEmpty()) {
logger.debug("Queue empty, update it.");
completeRandom();
}
}
public String poll() throws IOException {
checkRandom();
int randomResult = randomQueue.poll();
return FindContentOnWebPage.doYourJob(baseURL + randomResult + urlSuffix, divClass, htmlType);
}
}

View File

@ -0,0 +1,112 @@
package net.Broken.Tools.Command;
import net.Broken.Commande;
import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.FindContentOnWebPage;
import net.Broken.Tools.LimitChecker;
import net.Broken.Tools.TrueRandom;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Abstact class used for all command that need to find the max number of page on a web site.
*/
@Ignore
public abstract class NumberedSlashCommand implements SlashCommand {
protected int minNumber = 1;
protected int maxNumber = -1;
protected String baseURL;
protected String divClass;
protected String htmlType;
protected String urlSuffix;
protected LinkedBlockingQueue<Integer> randomQueue = new LinkedBlockingQueue<>();
private Logger logger = LogManager.getLogger();
/**
* Default constructor
*
* @param logger Logger used for logs
* @param baseURL WebSite base url
* @param divClass DivClass to search to extract image
* @param htmlType HTML tag to extract image (img)
*/
public NumberedSlashCommand(Logger logger, String baseURL, String urlSuffix, String divClass, String htmlType) {
this.logger = logger;
this.baseURL = baseURL;
this.divClass = divClass;
this.htmlType = htmlType;
this.urlSuffix = urlSuffix;
try {
logger.debug("Checking max...");
maxNumber = LimitChecker.doYourJob(baseURL, 2, urlSuffix);
logger.info("Limit is " + maxNumber);
} catch (IOException e) {
logger.catching(e);
}
}
public NumberedSlashCommand(Logger logger, String baseURL, String urlSuffix) {
this(logger, baseURL, urlSuffix, null, null);
}
@Override
public void action(SlashCommandEvent event) {
event.deferReply().queue();
try {
String result = poll();
event.getHook().sendMessage(event.getMember().getAsMention() + "\n" + result).queue();
} catch (IOException e) {
logger.catching(e);
MessageEmbed message = EmbedMessageUtils.getInternalError();
event.getHook().setEphemeral(true).sendMessageEmbeds(message).queue();
}
}
private void fillRandomQueue() throws IOException {
TrueRandom trueRandom = TrueRandom.getINSTANCE();
ArrayList<Integer> numbers = trueRandom.getNumbers(minNumber, maxNumber);
randomQueue.addAll(numbers);
}
protected void checkRandom() throws IOException {
logger.trace("Queue size: " + randomQueue.size());
if (randomQueue.isEmpty()) {
logger.debug("Queue empty, update it.");
fillRandomQueue();
}
}
public String poll() throws IOException {
checkRandom();
int randomResult = randomQueue.poll();
return FindContentOnWebPage.doYourJob(baseURL + randomResult + urlSuffix, divClass, htmlType);
}
@Override
public List<OptionData> getOptions() {
return null;
}
@Override
public List<SubcommandData> getSubcommands() {
return null;
}
}

View File

@ -65,6 +65,7 @@ public class SlashCommandLoader {
if (v.getSubcommands() != null) { if (v.getSubcommands() != null) {
command.addSubcommands(v.getSubcommands()); command.addSubcommands(v.getSubcommands());
} }
command.setDefaultEnabled(!v.isDisableByDefault());
commandListUpdateAction.addCommands(command); commandListUpdateAction.addCommands(command);
}); });
commandListUpdateAction.queue(); commandListUpdateAction.queue();

View File

@ -1,9 +1,9 @@
package net.Broken.Tools.DayListener.Listeners; package net.Broken.Tools.DayListener.Listeners;
import net.Broken.Commands.Over18.Madame;
import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.MainBot; import net.Broken.MainBot;
import net.Broken.SlashCommands.Over18.Madame;
import net.Broken.SpringContext; import net.Broken.SpringContext;
import net.Broken.Tools.DayListener.NewDayListener; import net.Broken.Tools.DayListener.NewDayListener;
import net.Broken.Tools.FindContentOnWebPage; import net.Broken.Tools.FindContentOnWebPage;
@ -50,7 +50,7 @@ public class DailyMadame implements NewDayListener {
} else { } else {
Madame command = (Madame) MainBot.commandes.get("madame"); Madame command = (Madame) MainBot.slashCommands.get("madame");
imgUrl = command.poll(); imgUrl = command.poll();
} }