Merge branch 'altBrch'

This commit is contained in:
Mysaa 2021-05-23 02:44:20 +02:00
commit ff94a614c3
11 changed files with 698 additions and 0 deletions

View File

@ -0,0 +1,59 @@
package com.bernard.juliabot;
import java.lang.reflect.Method;
import com.bernard.juliabot.api.CCommande;
public class CommandCalled {
Method called;
CCommande argument;
String name;
String cname;
Object caller;
Thread commandThread;
Throwable exitValue = null;
volatile boolean running;
volatile boolean started;
public CommandCalled(Method called, CCommande argument, String name, String cname, Object caller) {
this.called = called;
this.argument = argument;
this.name = name;
this.cname = cname;
this.caller = caller;
this.running = true;
}
public void setThread(Thread commandThread) {
this.commandThread = commandThread;
}
public void setExitValue(Throwable t) {
this.exitValue = t;
}
public void ended() {
running = false;
}
public boolean isRunning() {
return running;
}
public void waitForExecution() {
while(running) {
try {
Thread.sleep(42);
} catch (InterruptedException e) {
System.err.println("Icapacité de pauser le thread : ");
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,87 @@
package com.bernard.juliabot;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.bernard.juliabot.api.CCommande;
import com.bernard.juliabot.api.Command;
public class CommandeSurchargee {
String name;
Command command;
Map<Set<Class<?>>,Method> versions = new HashMap<>();
public CommandeSurchargee(Command c) {
this.name = c.name();
this.command = c;
}
public Method getExecutor(CCommande commande) {
Set<Class<?>> critargs = checkFiliature(Stream.of(commande.getClass()).collect(Collectors.toSet()));
System.out.println("////////"+critargs);
return versions.get(versions.keySet().stream().filter(cr -> critargs.containsAll(cr)).findAny().orElse(null));
}
public void surcharger(Set<Class<?>> discriminant, Method m) {
Set<Class<?>> critargs = checkFiliature(discriminant);
versions.put(critargs, m);
}
public static Set<Class<?>> checkFiliature(Set<Class<?>> unorderedDiscriminant){
return unorderedDiscriminant.stream()
.map(CommandeSurchargee::getAllMamans)
.flatMap(Set::stream)
.filter(CCommande.class::isAssignableFrom)
.filter(c->c.isInterface())
.collect(Collectors.toSet());
}
public static Set<Class<?>> getAllMamans(Class<?> clazz) {
Set<Class<?>> res = new HashSet<>();
res.add(clazz);
if(clazz == Object.class)return res;
// First, add all the interfaces implemented by this class
Class<?>[] interfaces = clazz.getInterfaces();
res.addAll(Arrays.asList(interfaces));
for (Class<?> interfaze : interfaces) {
res.addAll(getAllMamans(interfaze));
}
// Add the super class
Class<?> superClass = clazz.getSuperclass();
// Interfaces does not have java,lang.Object as superclass, they have null, so break the cycle and return
if (superClass == null) {
return res;
}
// Now inspect the superclass
res.addAll(getAllMamans(superClass));
return res;
}
@Override
public String toString() {
return "CommandeSurchargee [name=" + name + ", versions=" + versions + "]";
}
public String getDesc() {
return command.description();
}
}

View File

@ -0,0 +1,60 @@
package com.bernard.juliabot;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.dv8tion.jda.core.MessageBuilder;
import net.dv8tion.jda.core.entities.MessageChannel;
public class JuliaErrPrintStream extends OutputStream {
StringBuilder tas = new StringBuilder(2000);// Les 2000 caractères de Discord
Lock cadenas;
MessageChannel logChannel;
public static final int maxlength = 1900;
public JuliaErrPrintStream(MessageChannel logChan) {
this.cadenas = new ReentrantLock();
this.logChannel = logChan;
}
@Override
public void write(int i) throws IOException {
tas.append((char)(i));
}
@Override
public void flush() {
}
public void flushMessage() {
if(tas.length()==0)return;
this.cadenas.lock();
String str = tas.toString();
for(int i = 0; i*maxlength < tas.length();i++) {
MessageBuilder builder = new MessageBuilder();
builder.appendCodeBlock(str.substring(i*maxlength, Math.min((i+1)*maxlength,tas.length())), "");
logChannel.sendMessage(builder.build()).queue();
}
tas = new StringBuilder();
this.cadenas.unlock();
}
PrintStream ps = null;
public PrintStream printStream() {
if(ps == null)
ps = new PrintStream(this);
return ps;
}
}

View File

@ -0,0 +1,9 @@
package com.bernard.juliabot.api;
import com.bernard.juliabot.Julia.Laboratory;
public interface CCommande {
public Laboratory getLabo();
}

View File

@ -0,0 +1,45 @@
package com.bernard.juliabot.api;
import java.util.*;
public class CommandArguments {
List<String> nommes;
Map<String,String> arguments;
Set<String> flags;
public CommandArguments(List<String> nommes, Map<String, String> arguments, Set<String> flags) {
this.nommes = nommes;
this.arguments = arguments;
this.flags = flags;
}
public List<String> getNommes() {
return nommes;
}
public Map<String, String> getArguments() {
return arguments;
}
public Set<String> getFlags() {
return flags;
}
public boolean hasTag(String tag) {
return flags.contains(tag);
}
public String getArgument(String name) {
return arguments.get(name);
}
public String getNomme(int pos) {
return nommes.get(pos);
}
public int getNommeCount() {
return nommes.size();
}
}

View File

@ -0,0 +1,19 @@
package com.bernard.juliabot.api;
import java.time.OffsetDateTime;
import net.dv8tion.jda.core.entities.*;
public interface DiscordCCommande extends StringCCommande {
public Message getMessage();
public MessageChannel getChannel();
public User getUser();
public String getContentStripped();
public OffsetDateTime getPostDate();
}

View File

@ -0,0 +1,40 @@
package com.bernard.juliabot.api;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.bernard.juliabot.Julia;
public class JuliaConfig {
public static final String get(String name) {
try {
PreparedStatement st = Julia.theJulia().getJuliaDatabase().prepareStatement("SELECT * FROM juliaConfig WHERE strID=?");
st.setString(1, name);
ResultSet r = st.executeQuery();
if(r.getFetchSize() == 0)
throw new IllegalArgumentException("La configuration "+name+" n'existe pas ... veuillez la rentrer avant de la demander");
String value = r.getString("value");
return value;
} catch (SQLException e) {
e.printStackTrace();
throw new IllegalStateException("Impossible de faire des requetes à la bdd de julia. Est-elle initialisée au moins ?");
}
}
public static final void set(String name, String value) {
try {
PreparedStatement st = Julia.theJulia().getJuliaDatabase().prepareStatement("UPDATE juliaConfig SET value=? WHERE strID=?");
st.setString(1, value);
st.setString(2, value);
int r = st.executeUpdate();
if(r == 0)
throw new IllegalArgumentException("La configuration "+name+" n'a pas pu être modifiée ... existe-elle ?");
} catch (SQLException e) {
e.printStackTrace();
throw new IllegalStateException("Impossible de faire des requetes à la bdd de julia. Est-elle initialisée au moins ?");
}
}
}

View File

@ -0,0 +1,9 @@
package com.bernard.juliabot.api;
public interface StringCCommande extends CCommande{
public String getStringCommand();
public CommandArguments getArguments();
}

View File

@ -0,0 +1,19 @@
package com.bernard.juliabot.api;
import java.sql.Connection;
import com.bernard.juliabot.Julia;
import net.dv8tion.jda.core.JDA;
public class Trukilie {
public static JDA jda() {
return Julia.theJulia().jda;
}
public static Connection juliaDB() {
return Julia.theJulia().getJuliaDatabase();
}
}

View File

@ -0,0 +1,316 @@
package com.bernard.juliabot.internaddon;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import com.bernard.juliabot.CommandCalled;
import com.bernard.juliabot.Julia;
import com.bernard.juliabot.Julia.Laboratory;
import com.bernard.juliabot.JuliaAddon;
import com.bernard.juliabot.api.Command;
import com.bernard.juliabot.api.CommandArguments;
import com.bernard.juliabot.api.Discord;
import com.bernard.juliabot.api.DiscordCCommande;
import com.bernard.juliabot.api.JuLIAddon;
import com.bernard.juliabot.api.StringCCommande;
import com.thedeanda.lorem.LoremIpsum;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.MessageChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
@JuLIAddon(name="internaddon", devs = "Bernard", version="beta", important=true)
public class Internaddon {
public static final String COMMANDEUR = "!!";
@Discord(description = "LE catcheur des commandes discords. Les messages recus sont lus puis executes ici si ce sont des commandes")
public void getCommand(MessageReceivedEvent e) {
if(e.getMessage().getContentRaw().startsWith(COMMANDEUR)) {
String name = e.getMessage().getContentRaw().split(" ")[0].substring(COMMANDEUR.length());
Laboratory labo = Julia.theJulia().laboratoires.get(Julia.theJulia().lecouteur.getLabo(e));//Récupére le labo de l'évent
InternalddonCCommande ccommande = new InternalddonCCommande(e,labo);
try {
CommandCalled called = labo.executeCommand(name, ccommande);
System.out.println(called);
}catch(IllegalArgumentException ex) {
// La commande n'existe pas
e.getChannel().sendMessage("Moi pas connaitre `"+name+"`. Vous apprendre moi ?").queue();
}
}
}
@Command(name = "julia", aliases="juju", description = "Répond à l'appel", admin = true)
public void julia(DiscordCCommande commande) {
User user = commande.getUser();
MessageChannel channel = commande.getChannel();
String[] julias = new String[]{"Présent !", "Présente !", "Présentbleu !", "Présentavion !", "Présent(e) !", "Présent(bleu) !",
"Présent(avion) !", "Présent(e)(bleu) !", "Présent(e)(avion) !", "Présent(bleu)(avion) !", "Présent(e)(bleu)(avion) !",
"Oui, c'est moi", user.getName(), "ailuJ", "42 ... oups", "C'est à moi que tu parle ?!", "Entrez c'est ouvert", "Derriére toi !!!",
"J'ai tujorous pas cropmis a qoui ca sret l'otrahhgrope ...", "Laissez moi préparer la domination du monde en paix s'il vous plaét !",
"Je SuIS Un RObot BZzzBzZZZbZZbZZ", "Juliaaaa dadedidadeda dedadedi dadeda", "Tutturu", "Tadaaaaaaa !"};
String out = julias[(int)Math.floor(Math.random() * julias.length)];
channel.sendMessage(out).queue();
}
@Command(name = "help", aliases= {"ausecours","?","allahuakbar"}, description = "Laissez-vous aider par le meilleur bot du monde", admin = true)
public void help(DiscordCCommande commande) {
StringBuilder s = new StringBuilder();
s.append("```");
Laboratory l = commande.getLabo();
s.append("Vous étes actuellement dans le laboratoire '"+l.getL()+"'\n");
s.append("Liste des addons chargés :\n");
for(JuliaAddon e : l.getLoadedAddons().values())
s.append("\t- "+e.getName()+" en version "+e.getVersion()+"\n");
s.append("\nListe des commandes chargées :\n");
for(String c : l.getLoadedCommands().keySet()) {
s.append("\t- "+c);
String collected = l.getAliases().entrySet().stream()
.filter(e->e.getValue().equals(c))
.map(Map.Entry::getKey)
.collect(Collectors.joining(", "));
if(!collected.isEmpty())
s.append(" a.k.a "+collected);
if(l.getLoadedCommands().get(c).getDesc() != null)
s.append(" :\n\t\t"+l.getLoadedCommands().get(c).getDesc());
s.append('\n');
}
s.append("```");
commande.getChannel().sendMessage(s).queue();
}
@Command(name = "blabla", aliases= {}, description = "Pour vous prouver que je parle", admin = true)
public void blabla(DiscordCCommande commande) {
Message m = commande.getMessage();
m.getChannel().sendMessage("```"+LoremIpsum.getInstance().getWords(150, 200)+"```").queue();
m.delete();
}
@Command(name = "tuerBebePhoque", aliases= {}, description = "Pour votre plaisir", admin = true)
public void tuerBebePhoque(DiscordCCommande commande) {
Message m = commande.getMessage();
m.getChannel().sendMessage("http://toni.mi.free.fr/vanhebdo/actions/phoques/im_phoque_coupGourdinAssomme_Sang.jpg").queue();
}
@Discord(description = "Arthur, par-ce que vous n'étes pas qu'une caricature")
public void shutUp(MessageReceivedEvent e) {
if(e.getAuthor().getIdLong() == 187677269626585089L) {//Yukimyo = L'Orchidoclaste
e.getChannel().sendMessage(e.getAuthor().getAsMention() +" dis du caca").queue();
}
}
@Command(name = "args", description = "Décompose les messages à la Discord'", admin = true)
public void args(DiscordCCommande commande) {
CommandArguments ca = commande.getArguments();
StringBuilder s = new StringBuilder();
s.append("```"+commande.getStringCommand()+"```");
s.append("Liste des nommes : \n");
s.append(IntStream.range(0, ca.getNommeCount()).mapToObj(i -> "\t"+i+" : `"+ca.getNomme(i)+"`").collect(Collectors.joining("\n")));
s.append("\nListe des flags : \n");
s.append(ca.getFlags().stream().map(f->"\t`"+f+"`").collect(Collectors.joining("\n")));
s.append("\nListe des arguments : \n");
commande.getMessage().getChannel().sendMessage(s).queue();
}
@Command(name="update",description = "Met a jour le dossier des addons",admin=true)
public void update(StringCCommande commande) {
Julia.theJulia().update();
}
@Command(name="load",description = "Charge l'addon dans ce laboratoire",admin=true)
public void load(DiscordCCommande commande) {
CommandArguments cc = commande.getArguments();
String addonName = cc.getNomme(1);
String version = cc.getNomme(2);
Laboratory l = commande.getLabo();
String out = "Terminé avec succés";
try {
l.loadAddon(addonName, version);
}catch (Exception e) {
out = "```"+e.getClass().toString()+"\n"+e.getMessage()+"```";
}
commande.getChannel().sendMessage(out);
}
@Command(name="unload",description = "Décharge l'addon de ce laboratoire",admin=true)
public void unload(DiscordCCommande commande) {
CommandArguments cc = commande.getArguments();
String addonName = cc.getNomme(1);
Laboratory l = commande.getLabo();
String out = "Terminé avec succés";
try {
l.unloadAddon(addonName);
}catch (Exception e) {
out = "```"+e.getClass().toString()+"\n"+e.getMessage()+"```";
}
commande.getChannel().sendMessage(out);
}
@Command(name="caca",description = "Déclanche une exception ... Faut bien tester, hein !",admin=true)
public void caca(DiscordCCommande commande) {
throw new IllegalStateException("Nan mais tout va bien ... je fait ce qu'on m'a demandé ^^");
}
public class InternalddonCCommande implements DiscordCCommande,StringCCommande{
Message m;
Laboratory labo;
public InternalddonCCommande(MessageReceivedEvent e,Laboratory labo) {
m = e.getMessage();
this.labo = labo;
}
@Override
public String getStringCommand() {
return m.getContentRaw();
}
@Override
public CommandArguments getArguments() {
return parseCommandArguments(getStringCommand());
}
@Override
public Message getMessage() {
return m;
}
@Override
public MessageChannel getChannel() {
return m.getChannel();
}
@Override
public User getUser() {
return m.getAuthor();
}
@Override
public String getContentStripped() {
return m.getContentStripped();
}
@Override
public OffsetDateTime getPostDate() {
return m.getCreationTime();
}
@Override
public Laboratory getLabo() {
return labo;
}
}
public static CommandArguments parseCommandArguments(String raw) {
List<String> nommes = new ArrayList<String>();
Map<String,String> arguments = new HashMap<>();
Set<String> flags = new HashSet<>();
String state = "n";
String reading = "";
List<String> stringized = new ArrayList<>();
for(String morceau : raw.split(" ")) {
if(state.equals("n")) {
if(morceau.isEmpty())
continue;
if(morceau.startsWith("\"") || morceau.startsWith("`")) {
state = String.valueOf(morceau.charAt(0));
morceau = morceau.substring(1);
}else {
stringized.add(morceau);
continue;
}
}
if(state.equals("\"") || state.equals("`")) {
if(morceau.isEmpty()) {
reading += " ";
continue;
}
if(morceau.endsWith(state)) {
reading += morceau.substring(0, morceau.length()-1);
stringized.add(reading);
reading = "";
state = "n";
continue;
}
reading += morceau + " ";
continue;
}
}
for(String morceau : stringized) {
if(state.equals("n")) {
if(morceau.isEmpty())
continue;
if(morceau.startsWith("--")) {
state = "#"+morceau.substring(2);
continue;
}
if(morceau.startsWith("-")) {
flags.add(morceau.substring(1));
continue;
}
nommes.add(morceau);
continue;
}
if(state.startsWith("#")) {
arguments.put(state.substring(1), morceau);
continue;
}
}
return new CommandArguments(nommes, arguments, flags);
}
}

View File

@ -0,0 +1,35 @@
package com.bernard.juliabot.internaddon;
import java.io.*;
import java.util.function.Consumer;
import net.dv8tion.jda.core.entities.Message;
public class UnstableMessage extends OutputStream{
MConsumer thisConsumer = new MConsumer();
public UnstableMessage(Message m) {
// TODO Auto-generated constructor stub
m.editMessage(""/* a préciser */).queue(thisConsumer, (e) -> {
});
}
@Override
public void write(int arg0) throws IOException {
// TODO Auto-generated method stub
}
public class MConsumer implements Consumer<Message>{
@Override
public void accept(Message arg0) {
// TODO Auto-generated method stub
}
}
}