Add preference

This commit is contained in:
Sebastien 2018-04-28 22:57:48 +02:00
parent 59813fe37b
commit ad31172485
10 changed files with 498 additions and 69 deletions

View File

@ -2,16 +2,16 @@ package net.Broken;
import net.Broken.Commands.Move;
import net.Broken.Commands.Music;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.DB.Repository.PlaylistRepository;
import net.Broken.Tools.AntiSpam;
import net.Broken.Tools.Command.CommandParser;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.Moderateur;
import net.Broken.Tools.PrivateMessage;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.ExceptionEvent;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent;
@ -22,6 +22,10 @@ import net.dv8tion.jda.core.hooks.ListenerAdapter;
import net.dv8tion.jda.core.managers.GuildManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import java.util.ArrayList;
import java.util.List;
/**
@ -30,8 +34,17 @@ import org.apache.logging.log4j.Logger;
public class BotListener extends ListenerAdapter {
private AntiSpam antispam=new AntiSpam();
private Moderateur modo = new Moderateur();
private GuildPreferenceRepository guildPreferenceRepository;
private Logger logger = LogManager.getLogger();
public BotListener() {
ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
}
@Override
public void onReady(ReadyEvent event) {
@ -41,30 +54,66 @@ public class BotListener extends ListenerAdapter {
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
logger.info(event.getUser().getName()+ "join the guild, move it!");
new Move().exc(event.getMember(),event.getJDA().getRolesByName("Newbies",true),false,event.getGuild(),event.getGuild().getManager());
TextChannel chanel = event.getGuild().getTextChannelsByName("accueil", true).get(0);
if(chanel != null)
chanel.sendMessage("Salut "+event.getUser().getAsMention()+"! Ecris ton nom, prénom, ta promotion et ton groupe ici! Un admin te donnera accées a ton groupe!").complete();
MainBot.roleFlag = false;
GuildPreferenceEntity guildPref = getPreference(event.getGuild());
if(guildPref.isDefaultRole()){
logger.info(event.getUser().getName()+ "join the guild, move it!");
List<Role> roles = new ArrayList<>();
roles.add(event.getGuild().getRoleById(guildPref.getDefaultRoleId()));
new Move().exc(event.getMember(), roles,false,event.getGuild(),event.getGuild().getManager());
}
if(guildPref.isWelcome()){
TextChannel chanel = event.getGuild().getTextChannelById(guildPref.getWelcomeChanelID());
if(chanel != null){
String message = guildPref.getWelcomeMessage();
message = message.replaceAll("@name", event.getMember().getAsMention());
logger.debug(message);
// "Salut "+event.getUser().getAsMention()+"! Ecris ton nom, prénom, ta promotion et ton groupe ici! Un admin te donnera accées a ton groupe!"
chanel.sendMessage(message).complete();
}
MainBot.roleFlag = false;
}
}
@Override
public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) {
logger.debug(event.getUser().getName()+" leave a role");
if(!MainBot.roleFlag){
if(event.getMember().getRoles().size() == 0){
logger.info(event.getUser().getName()+ "have no roles, move it!");
new Move().exc(event.getMember(),event.getGuild().getRolesByName("Populace",true),false,event.getGuild(),event.getGuild().getManager());
GuildPreferenceEntity guildPref = getPreference(event.getGuild());
if(guildPref.isDefaultRole()){
if(!MainBot.roleFlag){
if(event.getMember().getRoles().size() == 0){
logger.info(event.getUser().getName()+ "have no roles, move it!");
List<Role> roles = new ArrayList<>();
roles.add(event.getGuild().getRoleById(guildPref.getDefaultRoleId()));
new Move().exc(event.getMember(), roles,false,event.getGuild(),event.getGuild().getManager());
MainBot.roleFlag = false;
}
}
else
{
logger.debug("ignore it");
MainBot.roleFlag = false;
}
}
else
{
logger.debug("ignore it");
MainBot.roleFlag = false;
}
}
@ -87,7 +136,7 @@ public class BotListener extends ListenerAdapter {
@Override
public void onMessageReceived(MessageReceivedEvent event) {
// ----------------------Test pour eviter eco de commande-------------------------
// ----------------------Preference pour eviter eco de commande-------------------------
try{
@ -101,21 +150,29 @@ public class BotListener extends ListenerAdapter {
{
if(!event.isFromType(ChannelType.PRIVATE)) {
if (!event.getTextChannel().getName().equals("le_dongeon")) {
Guild serveur = event.getGuild();
GuildManager guildManager = serveur.getManager();
Member user = event.getMember();
// appel de la methode d'analyse de message de "Moderateur"
if (!event.getAuthor().getName().equals("Aethex") && event.getMessage().getContentRaw().length() > 0) {
if (modo.analyse(user, serveur, guildManager, event) == 1) {
antispam.extermine(user, serveur, guildManager, true, event);
}
} else if (event.getMessage().getContentRaw().length() == 0)
logger.error("Image detected, ignoring it.");
}
Guild serveur = event.getGuild();
GuildPreferenceEntity guildPref = getPreference(serveur);
if(!guildPref.isAntiSpam())
return;
GuildManager guildManager = serveur.getManager();
Member user = event.getMember();
// appel de la methode d'analyse de message de "Moderateur"
if (event.getMessage().getContentRaw().length() > 0) {
if (modo.analyse(user, serveur, guildManager, event) == 1) {
antispam.extermine(user, serveur, guildManager, true, event);
}
} else if (event.getMessage().getContentRaw().length() == 0)
logger.error("Image detected, ignoring it.");
}
@ -133,4 +190,19 @@ public class BotListener extends ListenerAdapter {
}
private GuildPreferenceEntity getPreference(Guild guild){
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if(guildPrefList.isEmpty()){
logger.info("Generate default pref");
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
}
else
guildPref = guildPrefList.get(0);
return guildPref;
}
}

View File

@ -0,0 +1,38 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.awt.*;
import java.util.List;
public class ListRoles implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
List<Role> roles = event.getGuild().getRoles();
EmbedBuilder messageB = new EmbedBuilder();
for (Role role : roles){
messageB.addField(role.getName(),"```id: " + role.getId() + "```",false);
}
messageB.setColor(Color.green);
event.getTextChannel().sendMessage(messageB.build()).complete();
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -0,0 +1,212 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.DB.Repository.GuildPreferenceRepository;
import net.Broken.MainBot;
import net.Broken.SpringContext;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.Tools.MessageTimeOut;
import net.Broken.audio.AudioM;
import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import java.awt.*;
import java.io.IOException;
import java.util.List;
public class Preference implements Commande {
private Logger logger = LogManager.getLogger();
private GuildPreferenceRepository guildPreferenceRepository;
public Preference() {
ApplicationContext context = SpringContext.getAppContext();
guildPreferenceRepository = (GuildPreferenceRepository) context.getBean("guildPreferenceRepository");
}
@Override
public void action(String[] args, MessageReceivedEvent event) {
if(args.length == 0){
GuildPreferenceEntity guildPref = getPreference(event.getGuild());
MessageEmbed message = EmbedMessageUtils.getPref(guildPref);
event.getTextChannel().sendMessage(message).complete();
}
else{
switch (args[0]){
case "set":
if(args.length >= 3){
StringBuilder val = new StringBuilder();
for(int i = 2; i < args.length; i++){
val.append(args[i]).append(" ");
}
set(event, args[1], val.toString());
}
else{
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("Missing argument.\n:arrow_right: Please use `//help preference`"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
break;
default:
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nUnknown argument`\n\nMore info with `//help preference`"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
break;
}
}
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return true;
}
@Override
public boolean isNSFW() {
return false;
}
private GuildPreferenceEntity getPreference(Guild guild){
List<GuildPreferenceEntity> guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId());
GuildPreferenceEntity guildPref;
if(guildPrefList.isEmpty()){
logger.info("Generate default pref for " + guild.getName());
guildPref = GuildPreferenceEntity.getDefault(guild);
guildPreferenceRepository.save(guildPref);
}
else
guildPref = guildPrefList.get(0);
return guildPref;
}
private void set(MessageReceivedEvent event, String key, String value){
GuildPreferenceEntity pref = getPreference(event.getGuild());
switch (key){
case "anti_spam":
if(value.toLowerCase().equals("true") || value.toLowerCase().equals("false")){
boolean result = Boolean.parseBoolean(value);
pref.setAntiSpam(result);
pref = guildPreferenceRepository.save(pref);
EmbedBuilder eb = new EmbedBuilder().addField(":ok: Ok :ok:","",false).addField("> Anti Spam", "```java\n" + String.valueOf(pref.isAntiSpam()) + "```", false).setColor(Color.green);
Message sended = event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(eb)).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}else{
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nWrong value, expect `true` or `false`\n\nMore info with `//help preference`"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
break;
case "default_role":
if(value.toLowerCase().equals("true") || value.toLowerCase().equals("false")){
boolean result = Boolean.parseBoolean(value);
pref.setDefaultRole(result);
pref = guildPreferenceRepository.save(pref);
EmbedBuilder eb = new EmbedBuilder().addField(":ok: Ok :ok:","",false).addField("> Default Role", "```java\n" + String.valueOf(pref.isDefaultRole()) + "```", false).setColor(Color.green);
Message sended = event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(eb)).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}else{
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nWrong value, expect `true` or `false`\n\nMore info with `//help preference`"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
break;
case "default_role_id":
try{
Role role = event.getGuild().getRoleById(value);
if(role != null){
pref.setDefaultRoleId(role.getId());
pref = guildPreferenceRepository.save(pref);
EmbedBuilder eb = new EmbedBuilder().addField(":ok: Ok :ok:","",false).addField("> Default Role ID", "```java\n" + pref.getDefaultRoleId()+ "```", false).setColor(Color.green);
Message sended = event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(eb)).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
else
{
throw new NumberFormatException();
}
}catch (NumberFormatException e){
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nRole not found!\n\nUse `//listroles` to get roles id"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
break;
case "welcome":
if(value.toLowerCase().equals("true") || value.toLowerCase().equals("false")){
boolean result = Boolean.parseBoolean(value);
pref.setWelcome(result);
pref = guildPreferenceRepository.save(pref);
EmbedBuilder eb = new EmbedBuilder().addField(":ok: Ok :ok:","",false).addField("> Welcome", "```java\n" + String.valueOf(pref.isWelcome()) + "```", false).setColor(Color.green);
Message sended = event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(eb)).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}else{
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nWrong value, expect `true` or `false`\n\nMore info with `//help preference`"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
break;
case "welcome_chanel_id":
try{
TextChannel chanel = event.getGuild().getTextChannelById(value);
if(chanel != null){
pref.setWelcomeChanelID(chanel.getId());
pref = guildPreferenceRepository.save(pref);
EmbedBuilder eb = new EmbedBuilder().addField(":ok: Ok :ok:","",false).addField("> Welcome chanel ID", "```java\n" + pref.getWelcomeChanelID() + "```", false).setColor(Color.green);
Message sended = event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(eb)).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
else
{
throw new NumberFormatException();
}
}catch (NumberFormatException e){
MessageEmbed msg = EmbedMessageUtils.buildStandar(EmbedMessageUtils.getError("\nRole not found!\n\nUse `//listroles` to get roles id"));
Message sended = event.getTextChannel().sendMessage(msg).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
}
break;
case "welcome_message":
pref.setWelcomeMessage(value);
pref = guildPreferenceRepository.save(pref);
EmbedBuilder eb = new EmbedBuilder().addField(":ok: Ok :ok:","",false).addField("> Welcome message", "```java\n" + pref.getWelcomeMessage() + "```", false).setColor(Color.green);
Message sended = event.getTextChannel().sendMessage(EmbedMessageUtils.buildStandar(eb)).complete();
new MessageTimeOut(MainBot.messageTimeOut, sended, event.getMessage()).start();
break;
}
}
}

View File

@ -1,33 +0,0 @@
package net.Broken.Commands;
import net.Broken.Commande;
import net.Broken.audio.AudioM;
import net.Broken.audio.NotConnectedException;
import net.Broken.audio.NullMusicManager;
import net.Broken.audio.Youtube.YoutubeTools;
import net.dv8tion.jda.core.entities.RichPresence;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.io.IOException;
public class Test implements Commande {
@Override
public void action(String[] args, MessageReceivedEvent event) {
event.getJDA().getPresence().setPresence(RichPresence.playing("test").asRichPresence(),false);
}
@Override
public boolean isPrivateUsable() {
return false;
}
@Override
public boolean isAdminCmd() {
return false;
}
@Override
public boolean isNSFW() {
return false;
}
}

View File

@ -0,0 +1,111 @@
package net.Broken.DB.Entity;
import net.dv8tion.jda.core.entities.Guild;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class GuildPreferenceEntity {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Integer id;
private String guildId;
private boolean antiSpam;
private boolean welcome;
private String welcomeMessage;
private String welcomeChanelID;
private boolean defaultRole;
private String defaultRoleId;
public GuildPreferenceEntity(String guildId, boolean antiSpam, boolean welcome, String welcomeMessage, String welcomeChanelID, boolean defaultRole, String defaultRoleId) {
this.guildId = guildId;
this.antiSpam = antiSpam;
this.welcome = welcome;
this.welcomeMessage = welcomeMessage;
this.welcomeChanelID = welcomeChanelID;
this.defaultRole = defaultRole;
this.defaultRoleId = defaultRoleId;
}
public GuildPreferenceEntity(){}
public static GuildPreferenceEntity getDefault(Guild guild){
return new GuildPreferenceEntity(guild.getId(), false, false, "Welcome to this awesome server @name! ", " ", false, " ");
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGuildId() {
return guildId;
}
public void setGuildId(String guildId) {
this.guildId = guildId;
}
public boolean isAntiSpam() {
return antiSpam;
}
public void setAntiSpam(boolean antiSpam) {
this.antiSpam = antiSpam;
}
public boolean isWelcome() {
return welcome;
}
public void setWelcome(boolean welcome) {
this.welcome = welcome;
}
public String getWelcomeMessage() {
return welcomeMessage;
}
public void setWelcomeMessage(String welcomeMessage) {
this.welcomeMessage = welcomeMessage;
}
public String getWelcomeChanelID() {
return welcomeChanelID;
}
public void setWelcomeChanelID(String welcomeChanelID) {
this.welcomeChanelID = welcomeChanelID;
}
public String getDefaultRoleId() {
return defaultRoleId;
}
public void setDefaultRoleId(String defaultRoleId) {
this.defaultRoleId = defaultRoleId;
}
public boolean isDefaultRole() {
return defaultRole;
}
public void setDefaultRole(boolean defaultRole) {
this.defaultRole = defaultRole;
}
}

View File

@ -33,6 +33,8 @@ public class PendingUserEntity {
this.password = password;
}
public String getPassword() {
return password;
}

View File

@ -0,0 +1,10 @@
package net.Broken.DB.Repository;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface GuildPreferenceRepository extends CrudRepository<GuildPreferenceEntity, Integer> {
List<GuildPreferenceEntity> findByGuildId(String id);
}

View File

@ -50,10 +50,9 @@ public class Init {
logger.info("Connecting to Discord api...");
//connection au bot
jda = new JDABuilder(AccountType.BOT).addEventListener(new BotListener()).setToken(token).setBulkDeleteSplittingEnabled(false).buildBlocking();
jda = new JDABuilder(AccountType.BOT).setToken(token).setBulkDeleteSplittingEnabled(false).buildBlocking();
MainBot.jda = jda;
jda.setAutoReconnect(true);
jda.addEventListener();
/*************************************
* Definition des commande *
@ -116,6 +115,7 @@ public class Init {
static void polish(JDA jda){
CommandLoader.load();
ApiCommandLoader.load();
jda.addEventListener(new BotListener());
jda.getPresence().setPresence(OnlineStatus.ONLINE, Game.playing("bot.seb6596.ovh"));

View File

@ -1,5 +1,6 @@
package net.Broken.Tools;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.MainBot;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.Member;
@ -105,6 +106,22 @@ public class EmbedMessageUtils {
return new EmbedBuilder().setTitle("Command du bot ("+role+")").setDescription(message).setFooter("Utilise '//help <commande>' pour plus de détails.",MainBot.jda.getSelfUser().getAvatarUrl()).setTimestamp(Instant.now()).setColor(Color.green).setThumbnail(MainBot.jda.getSelfUser().getAvatarUrl()).build();
}
public static MessageEmbed getPref(GuildPreferenceEntity guildPref){
EmbedBuilder messageB = new EmbedBuilder()
.setColor(Color.green)
.setTitle("**Guild config**")
.setDescription("_This is the current config of bot for this Guild_")
.addField("> Guild ID", "This is the curent guild ID\n```java\n" + guildPref.getGuildId() + "```Edit: :lock:", false)
.addField("> Anti Spam", "Activate Spam hunter\n```java\n" + String.valueOf(guildPref.isAntiSpam()) + "```Edit: :unlock:\nKey: anti_spam", false)
.addField("> Default Role", "Activate auto move to default role\n```java\n" + String.valueOf(guildPref.isDefaultRole()) + "```Edit: :unlock:\nKey: default_role", false)
.addField("> Default Role ID", "Role id for auto move\n```java\n" + guildPref.getDefaultRoleId() + "```Edit: :unlock:\nKey: default_role_id", false)
.addField("> Welcome", "Activate welcome message\n```java\n" + String.valueOf(guildPref.isWelcome()) + "```Edit: :unlock:\nKey: welcome", false)
.addField("> Welcome chanel ID", "Chane id for welcome message\n```" + guildPref.getWelcomeChanelID() + "```Edit: :unlock:\nKey: welcome_chanel_id", false)
.addField("> Welcome message", "Welcome message (@name for mention)\n```markdown\n" + guildPref.getWelcomeMessage() + "```Edit: :unlock:\nKey: welcome_message", false);
return buildStandar(messageB);
}
}

View File

@ -66,7 +66,7 @@ public class UserUtils {
PendingUserEntity pendingUserEntity = null;
String token = "";
//Test if exist on register user
//Preference if exist on register user
if(userRepository.findByJdaId(user.getId()).size() > 0){
logger.warn("User already registered!");
throw new UserAlreadyRegistered();