Private update

This commit is contained in:
BrokenFire 2017-03-20 20:27:53 +01:00
parent afdd27e466
commit c466102448
7 changed files with 655 additions and 0 deletions

View File

@ -0,0 +1,87 @@
package net.borken;
import net.borken.Outils.AntiSpam;
import net.borken.Outils.Moderateur;
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.User;
import net.dv8tion.jda.core.events.DisconnectEvent;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.ReconnectedEvent;
import net.dv8tion.jda.core.events.StatusChangeEvent;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
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;
/**
* Created by seb65 on 19/10/2016.
*/
public class BotListener extends ListenerAdapter {
AntiSpam antispam=new AntiSpam();
Moderateur modo = new Moderateur();
Logger logger = LogManager.getLogger();
@Override
public void onReady(ReadyEvent event) {
logger.info("Connection succees");
}
@Override
public void onMessageReceived(MessageReceivedEvent event) {
// ----------------------Test pour eviter eco de commande-------------------------
try
{
if (event.getMessage().getContent().startsWith("//") && event.getMessage().getAuthor().getId() != event.getJDA().getSelfUser().getId()) {
//On a detecter que c'etait une commande
//System.out.println(event.getMessage().getContent());
MainBot.handleCommand(MainBot.parser.parse(event.getMessage().getContent(), event));
}
else if (event.getMessage().getAuthor().getId() != event.getJDA().getSelfUser().getId() && !event.getTextChannel().getName().equals("le_dongeon"))
{
//N'est pas une commande
Guild serveur=event.getGuild();
GuildManager guildManager = serveur.getManager();
Member user = event.getMember();
if(!event.isFromType(ChannelType.PRIVATE))
{
// appel de la methode d'analyse de message de "Moderateur"
if(!event.getAuthor().getName().equals("Aethex") && event.getMessage().getContent().length()>0) {
if (modo.analyse(user, serveur, guildManager, event) == 1) {
antispam.extermine(user, serveur, guildManager,true, event);
}
}
else if(event.getMessage().getContent().length() == 0)
logger.error("Image detected, ignoring it.");
}
}
}catch (Exception e)
{
if (e.getMessage()==null) {
logger.error("NullPointerException");
} else {
logger.error(e.getMessage());
}
}
}
}

240
src/net/borken/MainBot.java Normal file
View File

@ -0,0 +1,240 @@
package net.borken;
import net.borken.Outils.CommandParser;
import net.borken.Outils.DayListener;
import net.borken.Outils.Redirection;
import net.borken.commandes.*;
import net.borken.commandes.Over18.*;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.OnlineStatus;
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.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.managers.GuildManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.*;
/**
* Created by seb65 on 19/10/2016.
*/
public class MainBot {
private static JDA jda;
public static final CommandParser parser =new CommandParser();
public static HashMap<String, Commande> commandes = new HashMap<>();
public static boolean okInit=false;
public static HashMap<Member, String[]> historique =new HashMap<>();
public static HashMap<Member, Integer> message_compteur =new HashMap<>();
public static Hashtable<Member,Integer> userMulti = new Hashtable();
public static Hashtable<Member,Boolean> minuteurStatut = new Hashtable<>();
public static ArrayList<Class<?>> privateUsableCommand = new ArrayList<>();
static Logger logger = LogManager.getLogger();
public static void main(String[] args) throws IOException {
logger.trace("trace");
logger.debug("debug");
logger.info("info");
logger.warn("warn");
logger.error("error");
Stop stopTh=new Stop();
stopTh.start();
/****************************
* Initialisation *
****************************/
logger.info("-------------------INITIALISATION-------------------");
//Bot démarrer sans token
if (args.length < 1) {
logger.fatal("Veuilliez indiquer le token du bot en argument...");
okInit=false;
}
else
{
//Token présent
try
{
logger.info("Connection au serveur...");
//connection au bot
jda = new JDABuilder(AccountType.BOT).addListener(new BotListener()).setToken(args[0]).setBulkDeleteSplittingEnabled(false).buildBlocking();
jda.setAutoReconnect(true);
jda.addEventListener();
jda.addEventListener();
okInit=true;
}
catch (LoginException | InterruptedException | RateLimitedException e)
{
logger.catching(e);
okInit=false;
}
}
//Connection reussi
if(okInit)
{
/*************************************
* Definition des commande *
*************************************/
commandes.put("ping", new PingCommande());
commandes.put("help",new Help());
commandes.put("move", new Move());
commandes.put("spam", new Spam());
commandes.put("ass",new Ass());
commandes.put("boobs",new Boobs());
commandes.put("pipe",new Pipe());
commandes.put("sm",new SM());
commandes.put("madame",new Madame());
commandes.put("cat",new Cat());
privateUsableCommand.add(Help.class);
privateUsableCommand.add(PingCommande.class);
//On recupere le l'id serveur
Guild serveur = jda.getGuilds().get(0);
//On recupere le serveur manageur
GuildManager guildManager = serveur.getManager();
//on recupere les utilisateur conecter
List<Member> utilisateurCo = serveur.getMembers();
logger.info("Utilisatieur connecté: ");
for (Member anUtilisateurCo : utilisateurCo) //= for(int i=0; i<utilisateurCo.size(); i++)
{
if(anUtilisateurCo.getOnlineStatus().equals(OnlineStatus.ONLINE))
logger.info("\t*" + anUtilisateurCo.getEffectiveName()); //anUtilisateurCo = utilisateurCo.get(i)
}
logger.info("Utilisatieur absent: ");
for (Member anUtilisateurCo : utilisateurCo) //= for(int i=0; i<utilisateurCo.size(); i++)
{
if(anUtilisateurCo.getOnlineStatus().equals(OnlineStatus.DO_NOT_DISTURB))
logger.info("\t*" + anUtilisateurCo.getEffectiveName()); //anUtilisateurCo = utilisateurCo.get(i)
}
logger.info("Utilisatieur hors ligne: ");
for (Member anUtilisateurCo : utilisateurCo) //= for(int i=0; i<utilisateurCo.size(); i++)
{
if(anUtilisateurCo.getOnlineStatus().equals(OnlineStatus.OFFLINE))
logger.info("\t*" + anUtilisateurCo.getEffectiveName()); //anUtilisateurCo = utilisateurCo.get(i)
}
ModoTimer modotimer = new ModoTimer();
modotimer.start();
DayListener dayListener =new DayListener();
dayListener.start();
logger.info("-----------------FIN INITIALISATION-----------------");
/*List<User> userAction = serveur.getUsersByName("Broken_Fire");
new Move().exc(userAction.get(0),"Big Daddy",true,serveur,serveur.getManager());*/
Redirection urlRedirect=new Redirection();
}
}
/***************************************
* Traitement de la commande *
***************************************/
public static void handleCommand(CommandParser.CommandContainer cmd)
{
//On verifie que la commande existe
if (commandes.containsKey(cmd.commande))
{
if(cmd.event.isFromType(ChannelType.PRIVATE) && privateUsableCommand.contains(commandes.get(cmd.commande).getClass()))
{
commandes.get(cmd.commande).action(cmd.args, cmd.event);
commandes.get(cmd.commande).executed(true, cmd.event);
}
else if (!cmd.event.isFromType(ChannelType.PRIVATE))
{
commandes.get(cmd.commande).action(cmd.args, cmd.event);
commandes.get(cmd.commande).executed(true, cmd.event);
}
else
cmd.event.getPrivateChannel().sendMessage("\n:warning: **__Commande non disponible en priver!__** :warning:").queue();
}
else
{
MessageReceivedEvent event = cmd.event;
if(event.isFromType(ChannelType.PRIVATE))
event.getPrivateChannel().sendMessage("\n:warning: **__Commande inconnue!__** :warning:\n:arrow_right: Utilisez `//help` pour voirs les commandes disponible. ").queue();
else
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:warning: **__Commande inconnue!__** :warning:\n:arrow_right: Utilisez `//help` pour voirs les commandes disponible. ").queue();
logger.info("Commande inconnue");
}
}
/*******************************
* RAZ Compteur Spam *
*******************************/
public static class ModoTimer extends Thread{
public ModoTimer()
{
}
@Override
public void run()
{
while (true)
{
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("\n5sec Ecoulées !");
for (Member unUser: message_compteur.keySet() ) //=for(int i=0; i<saveRoleUser.size(); i++)
{
MainBot.message_compteur.put(unUser, 0);
}
}
}
}
public static class Stop extends Thread
{
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
String txtEntré = "";
while(!txtEntré.equals("o")&&!txtEntré.equals("O"))
{
while (!txtEntré.equals("stop"))
{
txtEntré = scanner.nextLine();
}
logger.warn("Etes-vous sur de vouloir arréter le Bot? (o/n)");
txtEntré = scanner.nextLine();
if(txtEntré.equals("n")||txtEntré.equals("N"))
{
logger.info("Arret du Bot annulé.");
}
}
Runtime.getRuntime().exit(0);
}
}
}

View File

@ -0,0 +1,74 @@
package net.borken.commandes;
import net.borken.Commande;
import net.borken.Outils.Redirection;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by Seb on 06/02/2017.
*/
public class Cat implements Commande{
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
@Override
public void action(String[] args, MessageReceivedEvent event) {
Redirection redirect= new Redirection();
if(!event.isFromType(ChannelType.PRIVATE))
{
try {
String catLine=null;
redirect.get("http://random.cat");
URL cat = new URL(redirect.get("http://random.cat"));
URLConnection cc = cat.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(cc.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if(inputLine.contains("id=\"cat\""))
catLine = inputLine;
}
in.close();
String[] splited = catLine.split(" ");
String finalLineCat=null;
for(String aString:splited)
{
if(aString.startsWith("src"))
{
finalLineCat=aString;
}
}
System.out.println(finalLineCat);
finalLineCat=finalLineCat.replaceAll("src=\"","");
finalLineCat=finalLineCat.replaceAll("\"","");
event.getTextChannel().sendMessage("http://random.cat/"+finalLineCat).queue();
} catch (IOException e) {
e.printStackTrace();
}
}
else
event.getPrivateChannel().sendMessage("\n:warning: **__Commande non disponible en priver!__** :warning:");
}
@Override
public String help(String[] args) {
return "";
}
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
}

View File

@ -0,0 +1,171 @@
package net.borken.commandes;
import net.borken.Commande;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.managers.GuildController;
import net.dv8tion.jda.core.managers.GuildManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Created by seb65 on 20/10/2016.
*/
/**
*
*/
public class Move implements Commande {
Logger logger = LogManager.getLogger();
private String HELP="`//move <@utilisateur> <@rôleCible>`\n:arrow_right:\t*Deplacement d'un utilisateur vers un rôle cible, attention à bien faire des montions.*";
public List<Role> saveRoleUser;
public Member user;
public Guild serveur;
public GuildManager serveurManager;
public GuildController guildController;
/**
*
* @param user
* @param cible
* @param reset
* @param serveur
* @param serveurManager
* @return
*/
public boolean exc(Member user, Role cible , boolean reset, Guild serveur, GuildManager serveurManager)
{
guildController = new GuildController(serveur);
boolean erreur = false;
List<Role> allRoll = serveur.getRoles();
//On recupere les roles de l'utilisateur
List<Role> roleUserList = user.getRoles();
logger.info("Roles de " + user.getEffectiveName() + ":");
//On les save
saveRoleUser = roleUserList;
//Ajout du role cible
//On transforme la le role a ajouter en une liste pour pouvoir l'utiliser dans modifyMemberRoles
Collection<Role> temp = new ArrayList<>();
temp.add(cible);
//on fait ensuite les modif
guildController.modifyMemberRoles(user,temp,saveRoleUser).queue();
logger.info("Role " + cible + " attribuer a " + user.getEffectiveName());
this.user=user;
this.serveur=serveur;
this.serveurManager=serveurManager;
return erreur;
}
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return false;
}
/**
*
* @param args
* @param event
*/
public void action(String[] args, MessageReceivedEvent event)
{
if(!event.isFromType(ChannelType.PRIVATE))
{
if(args.length>=2)
{
serveur=event.getGuild();
List<User> userL = event.getMessage().getMentionedUsers();
List<Role> roleL = event.getMessage().getMentionedRoles();
if(userL.size()<1 ||roleL.size()<1)
{
logger.info("Mentionnement Incorect.");
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:warning: **__Erreur de déplacement__** :warning:\n:arrow_right: Erreur, Utilisateur ou Role mal mentioner. `//help move` pour plus d'info ").queue();
}
else
{
user = serveur.getMember(userL.get(0));
Role roleCible = roleL.get(0);
serveur=event.getGuild();
logger.info("Tentative de déplacement de "+user.getEffectiveName()+" vers "+roleCible.getName()+" par l'utilisateur "+event.getAuthor().getName());
if(event.getMember().getRoles().contains(serveur.getRolesByName("Big_Daddy",false).get(0)))
{
logger.info("Autorisation suffisante, deplacement autorisé");
logger.info("Utilisateur trouvée");
boolean erreur=this.exc(user,roleCible,true,serveur,serveur.getManager());
if(erreur)
{
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:warning: **__Erreur de déplacement.__** :warning:\n:arrow_right: Verifier le rôle cible. ").queue();
}
else
{
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:ok: **Déplacement de "+user.getEffectiveName()+" vers "+roleCible.getName()+" reussi.** :ok:").queue();
}
}
else
{
logger.info("Autorisation insuffisante, deplacement refusé");
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:warning: **__Vous n'avez pas l'autorisation de faire ca!__**:warning: ").queue();
}
}
}
else
{
logger.warn("Arguments maquant.");
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:warning: **__Erreur de déplacement__** :warning:\n:arrow_right: Arguments manquant. `//help move` pour plus d'info ").queue();
}
}
else
event.getPrivateChannel().sendMessage("\n:warning: **__Commande non disponible en priver!__** :warning:");
}
/**
*
* @param args
* @return
*/
@Override
public String help(String[] args) {
return HELP;
}
/**
*
* @param success
* @param event
*/
@Override
public void executed(boolean success, MessageReceivedEvent event) {
}
}

View File

@ -0,0 +1,46 @@
package net.borken.commandes;
import net.borken.Commande;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import org.apache.logging.log4j.LogManager;
import java.sql.Timestamp;
import java.time.*;
/**
* Created by seb65 on 19/10/2016.
*/
public class PingCommande implements Commande {
private String HELP = "`//ping` \n :arrow_right:\t*Le bot vous répondra Pong!*";
@Override
public boolean called(String[] args, MessageReceivedEvent event) {
return true;
}
@Override
public void action(String[] args, MessageReceivedEvent event) {
long receivedTime = Timestamp.valueOf(LocalDateTime.ofInstant(event.getMessage().getCreationTime().toInstant(), ZoneId.systemDefault())).getTime();
if(event.isFromType(ChannelType.PRIVATE))
event.getPrivateChannel().sendMessage(":arrow_right: Pong! `"+((Timestamp.from(Instant.now()).getTime()-receivedTime))+"ms`").queue();
else
event.getTextChannel().sendMessage(event.getAuthor().getAsMention()+"\n:arrow_right: Pong! `"+((Timestamp.from(Instant.now()).getTime()-receivedTime))+"ms`").queue();
LogManager.getLogger().info("pong");
}
@Override
public String help(String[] args) {
return HELP;
}
@Override
public void executed(boolean success, MessageReceivedEvent event)
{
return;
}
}

View File

@ -0,0 +1,8 @@
package net.borken.commandes;
/**
* Created by sebastien on 13/03/17.
*/
public class SpamInfo {
}

29
src/net/borken/log4j2.xml Normal file
View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="error">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%highlight{[%d{HH:mm:ss.SSS}][%-5level]%logger{36}: %msg%n}{FATAL=red blink, ERROR=red, WARN=bright yellow , INFO=blue, DEBUG=bright black, TRACE=cyan}" />
<!--{FATAL=red blink, ERROR=red, WARN=orange, INFO=yellow, DEBUG=green bold, TRACE=blue}-->
</Console>
<!--
<RollingFile name="RollingFile" fileName="/home/pi/Interface/logs/domo.log"
filePattern="/home/pi/Interface/logs/$${date:yyyy-MM}/domo-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout>
<Pattern>[%d{yyy-MM-dd ~ HH:mm:ss.SSS}][%-5level]%logger{36}: %msg%n</Pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy minSize="1B"/>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
-->
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" level="trace"/>
<!-- <AppenderRef ref="RollingFile" level="info"/>-->
</Root>
</Loggers>
</Configuration>