Update Biscuit to work on multiple guilds simultaneously

This commit is contained in:
Ghoti 2020-07-15 01:48:50 -05:00
parent ac5f3672fd
commit 4b443a1a6c
67 changed files with 2173 additions and 1236 deletions

View File

@ -25,6 +25,7 @@
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>

View File

@ -1,2 +1,4 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding/<project>=UTF-8

View File

@ -9,4 +9,5 @@ org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.fpghoti</groupId>
<artifactId>Biscuit</artifactId>
<version>1.5</version>
<version>1.6</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
@ -36,7 +36,7 @@
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
@ -46,6 +46,14 @@
<configuration>
<encoding>UTF-8</encoding>
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>org.tuxdude.logback.extensions:logback-colorizer</artifact>
<includes>
<include>**</include>
</includes>
</filter>
</filters>
</configuration>
</execution>
</executions>
@ -88,88 +96,18 @@
<artifactId>spigot-api</artifactId>
<version>1.15.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.15.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
<exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.15-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<artifactId>bungeecord-config</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-event</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-protocol</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>netty-transport-native-unix-common</artifactId>
<groupId>io.netty</groupId>
</exclusion>
<exclusion>
<artifactId>bungeecord-chat</artifactId>
<groupId>net.md-5</groupId>
</exclusion>
<exclusion>
<artifactId>snakeyaml</artifactId>
<groupId>org.yaml</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
@ -226,4 +164,3 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

25
pom.xml
View File

@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.fpghoti</groupId>
<artifactId>Biscuit</artifactId>
<version>1.5</version>
<version>1.6</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
@ -40,7 +40,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
@ -50,6 +50,14 @@
<configuration>
<encoding>UTF-8</encoding>
<minimizeJar>true</minimizeJar>
<filters>
<filter>
<artifact>org.tuxdude.logback.extensions:logback-colorizer</artifact>
<includes>
<include>**</include>
</includes>
</filter>
</filters>
</configuration>
</execution>
</executions>
@ -91,6 +99,17 @@
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>org.tuxdude.logback.extensions</groupId>
<artifactId>logback-colorizer</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>com.github.CrabMustard</groupId>
<artifactId>emoji-java</artifactId>
@ -148,7 +167,7 @@
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>4.1.1_155</version>
<version>4.2.0_177</version>
</dependency>
<dependency>
<groupId>com.github.cage</groupId>

View File

@ -1,192 +0,0 @@
package com.fpghoti.biscuit;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import org.slf4j.Logger;
import com.fpghoti.biscuit.captcha.BCage;
import com.fpghoti.biscuit.commands.CommandManager;
import com.fpghoti.biscuit.config.PropertiesRetrieval;
import com.fpghoti.biscuit.timer.BiscuitTimer;
import com.fpghoti.biscuit.user.PreUser;
import com.github.cage.Cage;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Invite;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
public class Biscuit {
private JDA jda;
private Logger logger;
private CommandManager commandManager;
private Timer timer;
private List<BiscuitTimer> timers;
private File captchaDir;
private Cage cage;
private HashMap<String, Integer> inviteUses;
public Biscuit(JDA jda, Logger log) {
this.jda = jda;
this.logger = log;
commandManager = new CommandManager();
timer = new Timer();
timers = new ArrayList<BiscuitTimer>();
if(!Main.isPlugin) {
captchaDir = new File("captcha");
}else {
captchaDir = new File(PluginCore.plugin.getDataFolder(), "captcha");
}
captchaDir.mkdir();
cage = new BCage();
wipeCaptchaDir();
loadPreUsers();
inviteUses = new HashMap<String, Integer>();
if(canManageServer() && PropertiesRetrieval.checkJoinInvite()) {
for(Guild g : jda.getGuilds()) {
g.retrieveInvites().queue((invs) -> {
indexInvites(invs);
});
}
}
}
public boolean canManageServer() {
for(Guild g : jda.getGuilds()) {
if(g.getSelfMember().hasPermission(Permission.MANAGE_SERVER)) {
return true;
}
}
return false;
}
public void log(String message) {
logger.info(message);
}
public void warn(String message) {
logger.warn(message);
}
public void error(String message) {
logger.error(message);
}
public JDA getJDA() {
return jda;
}
public CommandManager getCommandManager() {
return commandManager;
}
public void say(TextChannel channel, String message) {
channel.sendMessage(message).queue();
}
public void loadTimers() {
timer.cancel();
timer = new Timer();
for(BiscuitTimer t : timers) {
timer.schedule(t,t.getDelay(), t.getPeriod());
}
}
public void addTimer(BiscuitTimer bt) {
timers.add(bt);
}
public void removeTimer(BiscuitTimer bt) {
timers.remove(bt);
}
public void wipeCaptchaDir() {
Main.log.info("Wiping captcha files...");
boolean good = true;
File[] files = captchaDir.listFiles();
for (File file : files){
if (!file.delete()){
good = false;
Main.log.error("Could not remove captcha file: " + file);
}
}
if(good) {
Main.log.info("All captcha files successfully removed!");
}else {
Main.log.error("Some captcha file(s) could not be removed!");
}
}
public Cage getCage() {
return this.cage;
}
public ArrayList<TextChannel> getCaptchaLogChannels() {
ArrayList<TextChannel> ch = new ArrayList<TextChannel>();
for(Guild g : jda.getGuilds()) {
for(TextChannel t : g.getTextChannels()) {
if(t.getName().equalsIgnoreCase(PropertiesRetrieval.getCaptchaLogChannel())) {
ch.add(t);
}
}
}
return ch;
}
public void captchaLog(String msg) {
if(PropertiesRetrieval.logCaptcha()) {
for(TextChannel t : getCaptchaLogChannels()) {
t.sendMessage(msg).queue();
}
}
}
private void loadPreUsers() {
for(Guild g : jda.getGuilds()) {
for(Member m : g.getMembers()) {
User u = m.getUser();
if(!PreUser.preUserExists(u)) {
if(m.getRoles().size() == 1) {
for(Role role : m.getRoles()){
if(role.getName().equalsIgnoreCase(PropertiesRetrieval.getDefaultRole())){
PreUser.users.add(new PreUser(u));
}
}
}
}
}
}
}
private void indexInvites(List<Invite> invs) {
for(Invite i : invs) {
String code = i.getCode();
int uses = i.getUses();
inviteUses.put(code, uses);
}
}
public HashMap<String, Integer> getInviteUses(){
return inviteUses;
}
public void setInviteUses(HashMap<String, Integer> c) {
inviteUses = c;
}
public void clearInviteUses() {
inviteUses.clear();
}
}

View File

@ -1,16 +1,22 @@
package com.fpghoti.biscuit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.fusesource.jansi.AnsiConsole;
import com.fpghoti.biscuit.biscuit.Biscuit;
import com.fpghoti.biscuit.commands.BaseCommand;
import com.fpghoti.biscuit.commands.CommandListener;
import com.fpghoti.biscuit.commands.CommandManager;
import com.fpghoti.biscuit.commands.client.AddCommand;
import com.fpghoti.biscuit.commands.client.ChanIDCommand;
import com.fpghoti.biscuit.commands.client.DivideCommand;
import com.fpghoti.biscuit.commands.client.GetConfigCommand;
import com.fpghoti.biscuit.commands.client.GuildIDCommand;
import com.fpghoti.biscuit.commands.client.ToggleRoleCommand;
import com.fpghoti.biscuit.commands.client.HelpCommand;
import com.fpghoti.biscuit.commands.client.MultiplyCommand;
@ -19,34 +25,38 @@ import com.fpghoti.biscuit.commands.client.MakeInviteCommand;
import com.fpghoti.biscuit.commands.client.PingCommand;
import com.fpghoti.biscuit.commands.client.PowerCommand;
import com.fpghoti.biscuit.commands.client.RecentSpammersCommand;
import com.fpghoti.biscuit.commands.client.SaveConfigCommand;
import com.fpghoti.biscuit.commands.client.SoftMuteCommand;
import com.fpghoti.biscuit.commands.client.SquareRootCommand;
import com.fpghoti.biscuit.commands.client.SubtractCommand;
import com.fpghoti.biscuit.commands.client.UIDCommand;
import com.fpghoti.biscuit.commands.client.UnSoftMuteCommand;
import com.fpghoti.biscuit.commands.client.WikiCommand;
import com.fpghoti.biscuit.commands.console.GuildSayCommand;
import com.fpghoti.biscuit.commands.console.SayCommand;
import com.fpghoti.biscuit.commands.console.ShutdownConsoleCommand;
import com.fpghoti.biscuit.config.ConfigRetrieval;
import com.fpghoti.biscuit.config.PropertiesRetrieval;
import com.fpghoti.biscuit.listener.DMListener;
import com.fpghoti.biscuit.listener.GuildListener;
import com.fpghoti.biscuit.listener.JoinListener;
import com.fpghoti.biscuit.listener.MessageDeleteListener;
import com.fpghoti.biscuit.listener.MessageEditListener;
import com.fpghoti.biscuit.listener.MessageReceiveListener;
import com.fpghoti.biscuit.listener.ReactionListener;
import com.fpghoti.biscuit.listener.RoleListener;
import com.fpghoti.biscuit.timer.task.BotMsgRemoveTimer;
import com.fpghoti.biscuit.logging.BColor;
import com.fpghoti.biscuit.logging.BiscuitLog;
import com.fpghoti.biscuit.timer.task.ChatCountTimer;
import com.fpghoti.biscuit.timer.task.DecrementTimer;
import com.fpghoti.biscuit.timer.task.FastMsgRemoveTimer;
import com.fpghoti.biscuit.timer.task.SlowMsgRemoveTimer;
import com.fpghoti.biscuit.timer.task.SoftMuteTimer;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.ChunkingFilter;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
public class Main {
@ -55,21 +65,30 @@ public class Main {
public RollingFileAppender<String> we;
public SizeAndTimeBasedRollingPolicy<String> wes;
public static final Logger log = LoggerFactory.getLogger("ch.qos.logback.core.ConsoleAppender");
private static final BiscuitLog log = new BiscuitLog();
private static ArrayList<Biscuit> biscuits;
private static Biscuit mainBiscuit;
public static Scanner sc;
public static Biscuit biscuit;
public static boolean ready = false;
public static boolean isPlugin = false;
public static boolean shutdownStarted = false;
public static void main(String[] args){
ConfigRetrieval.generateConfig();
log.info("========================= Welcome to Biscuit =========================");
startJDA();
biscuit = new Biscuit(jda, log);
startCommandListener();
final Properties properties = new Properties();
try {
properties.load(Main.class.getClassLoader().getResourceAsStream("info.properties"));
} catch (IOException e) {
log.error("Could not determine Biscuit version.");
}
String version = properties.getProperty("version");
AnsiConsole.systemInstall();
log.info(BColor.CYAN_BOLD + "========================= WELCOME TO BISCUIT =========================");
log.info("Running version: " + BColor.MAGENTA_BOLD + version);
mainBiscuit = new Biscuit(null, null, log);
startJDA();
jda.addEventListener(new GuildListener());
jda.addEventListener(new MessageReceiveListener());
jda.addEventListener(new MessageEditListener());
jda.addEventListener(new MessageDeleteListener());
@ -77,19 +96,21 @@ public class Main {
jda.addEventListener(new DMListener());
jda.addEventListener(new ReactionListener());
jda.addEventListener(new RoleListener());
biscuits = new ArrayList<Biscuit>();
for(Guild g : jda.getGuilds()) {
Biscuit biscuit = new Biscuit(jda, g, log);
biscuit.addTimer(new ChatCountTimer(biscuit));
biscuit.addTimer(new SoftMuteTimer(biscuit));
biscuit.addTimer(new DecrementTimer(biscuit));
biscuit.loadTimers();
biscuits.add(biscuit);
}
startCommandListener();
String link = "NULL";
biscuit.addTimer(new ChatCountTimer());
biscuit.addTimer(new BotMsgRemoveTimer());
biscuit.addTimer(new FastMsgRemoveTimer());
biscuit.addTimer(new SlowMsgRemoveTimer());
biscuit.addTimer(new SoftMuteTimer());
biscuit.addTimer(new DecrementTimer());
biscuit.loadTimers();
List<BaseCommand> commands = biscuit.getCommandManager().getCommands();
List<BaseCommand> commands = CommandManager.getCommands();
//Client
@ -109,28 +130,37 @@ public class Main {
commands.add(new DivideCommand());
commands.add(new PowerCommand());
commands.add(new MakeInviteCommand());
commands.add(new GetConfigCommand());
commands.add(new SaveConfigCommand());
commands.add(new GuildIDCommand());
commands.add(new WikiCommand());
//Console
commands.add(new SayCommand());
commands.add(new GuildSayCommand());
commands.add(new ShutdownConsoleCommand());
link = "https://discordapp.com/oauth2/authorize?&client_id=" + jda.getSelfUser().getId() + "&scope=bot";
link = "https://discord.com/oauth2/authorize?&client_id=" + jda.getSelfUser().getId() + "&permissions=8&scope=bot";
log.info("Connection successful!");
log.info("Startup successful!");
log.info("You can add this bot to Discord using this link:");
log.info(link);
log.info("======================================================================");
log.info(BColor.CYAN_BOLD + "======================================================================");
log.info("CHAT LOGS BEGIN HERE:");
ready = true;
}
@SuppressWarnings("deprecation")
private static void startJDA() {
String token = PropertiesRetrieval.getToken();
String token = mainBiscuit.getProperties().getToken();
log.info("Connecting bot to Discord.");
try{
jda = new JDABuilder(AccountType.BOT).setToken(token).build();
jda = JDABuilder.createDefault(token)
.setChunkingFilter(ChunkingFilter.ALL)
.setMemberCachePolicy(MemberCachePolicy.ALL)
.enableIntents(GatewayIntent.getIntents(GatewayIntent.DEFAULT))
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.build();
try {
jda.awaitReady();
} catch (InterruptedException e) {
@ -144,31 +174,35 @@ public class Main {
}
}
public static Biscuit getMainBiscuit() {
return mainBiscuit;
}
private static void startCommandListener() {
if(!isPlugin) {
sc = new Scanner(System.in);
CommandListener cl = new CommandListener();
cl.sc = sc;
cl.jda = jda;
CommandListener cl = new CommandListener(sc, log);
jda.addEventListener(cl);
new Thread(cl).start();
}else {
CommandListener cl = new CommandListener();
cl.jda = jda;
CommandListener cl = new CommandListener(null, log);
jda.addEventListener(cl);
}
}
public static Biscuit getBiscuit() {
return biscuit;
public static ArrayList<Biscuit> getBiscuits() {
return biscuits;
}
public static void shutdown() {
if(!shutdownStarted) {
shutdownStarted = true;
log.info("Shutting down...");
biscuit.wipeCaptchaDir();
mainBiscuit.log("Shutting down...");
ArrayList<Biscuit> list = new ArrayList<Biscuit>(biscuits);
for(Biscuit b : list) {
b.remove();
}
mainBiscuit.wipeCaptchaDir();
if(jda != null) {
jda.shutdown();
}
@ -179,6 +213,20 @@ public class Main {
}
}
public static JDA getJDA() {
return jda;
}
public static BiscuitLog getLogger() {
return log;
}
public static void registerBiscuit(Biscuit b) {
biscuits.add(b);
}
public static void unregisterBiscuit(Biscuit b) {
biscuits.remove(b);
}
}

View File

@ -10,31 +10,27 @@ import com.fpghoti.biscuit.commands.CommandManager;
public class PluginCore extends JavaPlugin{
public static PluginCore plugin;
public void onEnable(){
plugin = this;
Main.isPlugin = true;
String[] args = {};
Main.main(args);
}
public void onDisable() {
Main.shutdown();
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
CommandManager m = Main.getBiscuit().getCommandManager();
if(m != null) {
if(sender instanceof Player) {
Player p = (Player)sender;
if(!p.hasPermission("biscuit.admin")) {
return false;
}
if(sender instanceof Player) {
Player p = (Player)sender;
if(!p.hasPermission("biscuit.admin")) {
return false;
}
return m.dispatch(label,args);
}
return false;
return CommandManager.dispatch(label,args);
}
}

View File

@ -0,0 +1,328 @@
package com.fpghoti.biscuit.biscuit;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.CopyOnWriteArrayList;
import com.fpghoti.biscuit.Main;
import com.fpghoti.biscuit.PluginCore;
import com.fpghoti.biscuit.captcha.BCage;
import com.fpghoti.biscuit.config.BiscuitConfig;
import com.fpghoti.biscuit.config.BiscuitProperties;
import com.fpghoti.biscuit.logging.BColor;
import com.fpghoti.biscuit.logging.BiscuitLog;
import com.fpghoti.biscuit.timer.BiscuitTimer;
import com.fpghoti.biscuit.timer.task.ChatCountTimer;
import com.fpghoti.biscuit.timer.task.DecrementTimer;
import com.fpghoti.biscuit.timer.task.SoftMuteTimer;
import com.fpghoti.biscuit.user.PreUser;
import com.github.cage.Cage;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Invite;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
public class Biscuit {
public static Biscuit getBiscuit(Guild g) {
for(Biscuit b : Main.getBiscuits()) {
if(b.getGuild().getId().equals(g.getId())) {
return b;
}
}
return null;
}
public static Biscuit getBiscuit(String guildcode) {
for(Biscuit b : Main.getBiscuits()) {
if(b.getProperties().getGuildCode().equalsIgnoreCase(guildcode)) {
return b;
}
}
return null;
}
public static ArrayList<PreUser> getPreUsers(User u) {
ArrayList<PreUser> pres = new ArrayList<PreUser>();
for(Guild g : Main.getJDA().getGuilds()) {
if(g.isMember(u)){
Biscuit b = getBiscuit(g);
if(b.preUserExists(u)) {
pres.add(b.getPreUser(u));
}
}
}
return pres;
}
public static Biscuit loadGuild(Guild g) {
Biscuit biscuit = new Biscuit(Main.getJDA(), g, Main.getLogger());
biscuit.addTimer(new ChatCountTimer(biscuit));
biscuit.addTimer(new SoftMuteTimer(biscuit));
biscuit.addTimer(new DecrementTimer(biscuit));
biscuit.loadTimers();
Main.registerBiscuit(biscuit);
return biscuit;
}
private boolean isMain;
private JDA jda;
private BiscuitLog logger;
private Timer timer;
private List<BiscuitTimer> timers;
private File captchaDir;
private Cage cage;
private Guild guild;
private HashMap<String, Integer> inviteUses;
private BiscuitConfig config;
private BiscuitProperties properties;
private BiscuitMessageStore messageStore;
private CopyOnWriteArrayList<PreUser> users = new CopyOnWriteArrayList<PreUser>();
public Biscuit(JDA jda, Guild guild, BiscuitLog log) {
this.jda = jda;
this.guild = guild;
this.logger = log;
this.isMain = guild == null;
this.messageStore = new BiscuitMessageStore(this);
this.config = new BiscuitConfig(this);
config.generateConfig();
this.properties = new BiscuitProperties(this);
timer = new Timer();
timers = new ArrayList<BiscuitTimer>();
if(!Main.isPlugin) {
captchaDir = new File("captcha");
captchaDir.mkdir();
}else {
captchaDir = new File(PluginCore.plugin.getDataFolder(), "captcha");
}
cage = new BCage();
if(isMain) {
wipeCaptchaDir();
}
if(!isMain) {
loadPreUsers();
inviteUses = new HashMap<String, Integer>();
if(canManageServer() && properties.checkJoinInvite()) {
guild.retrieveInvites().queue((invs) -> {
indexInvites(invs);
});
}
}
}
public BiscuitConfig getConfig() {
return config;
}
public BiscuitProperties getProperties() {
return properties;
}
public BiscuitMessageStore getMessageStore() {
return messageStore;
}
public Guild getGuild() {
return guild;
}
public boolean canManageServer() {
return guild.getSelfMember().hasPermission(Permission.MANAGE_SERVER);
}
public void log(String message) {
if(properties == null) {
logger.info(message);
return;
}
logger.info("[" + BColor.CYAN + properties.getGuildCode().toUpperCase() + BColor.RESET + "]: " + message);
}
public void warn(String message) {
if(properties == null) {
logger.warn(message);
return;
}
logger.warn("[" + properties.getGuildCode().toUpperCase() + "]: " + message);
}
public void error(String message) {
if(properties == null) {
logger.error(message);
return;
}
logger.error("[" + properties.getGuildCode().toUpperCase() + "]: " + message);
}
public JDA getJDA() {
return jda;
}
public void say(TextChannel channel, String message) {
channel.sendMessage(message).queue();
}
public void loadTimers() {
timer.cancel();
timer = new Timer();
for(BiscuitTimer t : timers) {
timer.schedule(t,t.getDelay(), t.getPeriod());
}
}
public void addTimer(BiscuitTimer bt) {
timers.add(bt);
}
public void removeTimer(BiscuitTimer bt) {
timers.remove(bt);
}
public void wipeCaptchaDir() {
log("Wiping captcha files...");
boolean good = true;
File[] files = captchaDir.listFiles();
for (File file : files){
if (!file.delete()){
good = false;
error("Could not remove captcha file: " + file);
}
}
if(good) {
log("All captcha files successfully removed!");
}else {
error("Some captcha file(s) could not be removed!");
}
}
public Cage getCage() {
return this.cage;
}
public ArrayList<TextChannel> getCaptchaLogChannels() {
ArrayList<TextChannel> ch = new ArrayList<TextChannel>();
for(TextChannel t : guild.getTextChannels()) {
if(t.getName().equalsIgnoreCase(properties.getCaptchaLogChannel())) {
ch.add(t);
}
}
return ch;
}
public void captchaLog(String msg) {
if(properties.logCaptcha()) {
for(TextChannel t : getCaptchaLogChannels()) {
t.sendMessage(msg).queue();
}
}
}
private void loadPreUsers() {
if(!properties.captchaEnabled()) {
return;
}
for(Member m : guild.getMembers()) {
User u = m.getUser();
if(!preUserExists(u)) {
if(m.getRoles().size() == 1) {
for(Role role : m.getRoles()){
if(role.getName().equalsIgnoreCase(properties.getDefaultRole())){
log(BColor.MAGENTA_BOLD + "Adding pre-join check for user " + u.getName() + " (" + u.getAsMention() + ")...");
users.add(new PreUser(u,this));
}
}
}
}
}
}
private void indexInvites(List<Invite> invs) {
for(Invite i : invs) {
String code = i.getCode();
int uses = i.getUses();
inviteUses.put(code, uses);
}
}
public HashMap<String, Integer> getInviteUses(){
return inviteUses;
}
public void setInviteUses(HashMap<String, Integer> c) {
inviteUses = c;
}
public void clearInviteUses() {
inviteUses.clear();
}
public void addPreUser(PreUser user) {
users.add(user);
}
public void removePreUser(PreUser user) {
users.remove(user);
}
public CopyOnWriteArrayList<PreUser> getPreUsers(){
return users;
}
public PreUser getPreUser(User user) {
for(PreUser u : users) {
if(u.getUser().getId().equals(user.getId())) {
return u;
}
}
return null;
}
public boolean preUserExists(User user) {
return getPreUser(user) != null;
}
public File getConfigDir() {
boolean isMain = guild == null;
if(isMain) {
if(Main.isPlugin) {
return PluginCore.plugin.getDataFolder();
}else {
return new File("").getAbsoluteFile();
}
}else {
File dir;
if(!Main.isPlugin) {
dir = new File("guilds");
}else {
dir = new File(PluginCore.plugin.getDataFolder(), "guilds");
}
dir.mkdir();
return dir;
}
}
public void remove() {
log("Removing guild biscuit...");
for(BiscuitTimer t : timers) {
t.cancel();
}
for(PreUser p : users) {
p.remove();
}
Main.unregisterBiscuit(this);
}
}

View File

@ -0,0 +1,148 @@
package com.fpghoti.biscuit.biscuit;
import java.util.ArrayList;
import java.util.HashMap;
import net.dv8tion.jda.api.entities.User;
public class BiscuitMessageStore {
Biscuit biscuit;
private HashMap<User, Integer> messageCounts = new HashMap<>();
private HashMap<User, Integer> messagesTenSeconds = new HashMap<>();
private HashMap<User, Integer> messagesTwoMin = new HashMap<>();
private ArrayList<User> spammers = new ArrayList<User>();
private ArrayList<User> spamWarned = new ArrayList<User>();
private ArrayList<User> softmuted = new ArrayList<User>();
public BiscuitMessageStore(Biscuit b) {
this.biscuit = b;
}
public String getSpammerList() {
String msg = "Recent spammers:";
for( User u: spammers){
msg = msg + " " + u.getAsMention();
}
return msg;
}
public void forgetChats() {
messageCounts.clear();
messagesTenSeconds.clear();
}
public void allowSoftMutedMessage() {
messagesTwoMin.clear();
}
public boolean isTwoMinCountEmpty() {
return messagesTwoMin.isEmpty();
}
public boolean hasTwoMinCount(User user) {
return messagesTwoMin.containsKey(user);
}
public void setTwoMinCount(User user, Integer i) {
messagesTwoMin.put(user,i);
}
public int getTwoMinCount(User user) {
return messagesTwoMin.get(user);
}
public void removeTwoMinCount(User user) {
messagesTwoMin.remove(user);
}
public boolean isTenSecondCountEmpty() {
return messagesTenSeconds.isEmpty();
}
public boolean hasTenSecondCount(User user) {
return messagesTenSeconds.containsKey(user);
}
public void setTenSecondCount(User user, Integer i) {
messagesTenSeconds.put(user,i);
}
public int getTenSecondsCount(User user) {
return messagesTenSeconds.get(user);
}
public void removeTenSecondsCount(User user) {
messagesTenSeconds.remove(user);
}
public boolean isMessageCountEmpty() {
return messageCounts.isEmpty();
}
public boolean hasMessageCount(User user) {
return messageCounts.containsKey(user);
}
public void setMessageCount(User user, Integer i) {
messageCounts.put(user,i);
}
public int getMessageCount(User user) {
return messageCounts.get(user);
}
public void removeMessageCount(User user) {
messageCounts.remove(user);
}
public void addSpammer(User u) {
spammers.add(u);
}
public void removeSpammer(User u) {
spammers.remove(u);
}
public boolean isSpammer(User u) {
return spammers.contains(u);
}
public boolean hasNoSpammers() {
return spammers.isEmpty();
}
public void addSpamWarned(User u) {
spamWarned.add(u);
}
public void removeSpamWarned(User u) {
spamWarned.remove(u);
}
public boolean isSpamWarned(User u) {
return spamWarned.contains(u);
}
public boolean hasNoSpamWarned() {
return spamWarned.isEmpty();
}
public void addSoftmuted(User u) {
softmuted.add(u);
}
public void removeSoftmuted(User u) {
softmuted.remove(u);
}
public boolean isSoftmuted(User u) {
return softmuted.contains(u);
}
public boolean hasNoSoftmuted() {
return softmuted.isEmpty();
}
}

View File

@ -2,13 +2,10 @@ package com.fpghoti.biscuit.commands;
import java.util.Scanner;
import org.slf4j.Logger;
import com.fpghoti.biscuit.Main;
import com.fpghoti.biscuit.config.PropertiesRetrieval;
import com.fpghoti.biscuit.biscuit.Biscuit;
import com.fpghoti.biscuit.logging.BiscuitLog;
import com.fpghoti.biscuit.util.PermUtil;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
@ -16,23 +13,29 @@ import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class CommandListener extends ListenerAdapter implements Runnable {
public Scanner sc;
public JDA jda;
Logger log = Main.log;
private Scanner sc;
private BiscuitLog log;
public CommandListener(Scanner sc, BiscuitLog log) {
this.sc = sc;
this.log = log;
}
@Override
public void onMessageReceived(MessageReceivedEvent event){
if (event.isFromType(ChannelType.TEXT)) {
if(PermUtil.isAdmin(event.getMember()) || !PropertiesRetrieval.restrictCmdChannels() || (PropertiesRetrieval.restrictCmdChannels() && isBotChannel(event.getTextChannel()))) {
if(!event.getAuthor().isBot() && event.getMessage().getContentDisplay().startsWith(PropertiesRetrieval.getCommandSignifier()) && event.getMessage().getAuthor().getId() != event.getJDA().getSelfUser().getId()){
Main.getBiscuit().getCommandManager().parse(event.getMessage().getContentRaw().toLowerCase(), event);
Biscuit b = Biscuit.getBiscuit(event.getGuild());
if(PermUtil.isAdmin(event.getMember()) || !b.getProperties().restrictCmdChannels() || (b.getProperties().restrictCmdChannels() && isBotChannel(event.getTextChannel()))) {
if(!event.getAuthor().isBot() && event.getMessage().getContentDisplay().startsWith(b.getProperties().getCommandSignifier()) && event.getMessage().getAuthor().getId() != event.getJDA().getSelfUser().getId()){
CommandManager.parse(event.getMessage().getContentRaw().toLowerCase(), event);
}
}
}
}
private boolean isBotChannel(TextChannel c) {
for(String s : PropertiesRetrieval.getCmdChannels()) {
Biscuit b = Biscuit.getBiscuit(c.getGuild());
for(String s : b.getProperties().getCmdChannels()) {
if(s.equals(c.getName())) {
return true;
}
@ -55,7 +58,7 @@ public class CommandListener extends ListenerAdapter implements Runnable {
private void runCommand(String label, String[] args) {
log.info(label);
Main.getBiscuit().getCommandManager().dispatch(label, args);
CommandManager.dispatch(label, args);
}
}

View File

@ -3,9 +3,8 @@ package com.fpghoti.biscuit.commands;
import java.util.ArrayList;
import java.util.List;
import com.fpghoti.biscuit.Biscuit;
import com.fpghoti.biscuit.Main;
import com.fpghoti.biscuit.config.PropertiesRetrieval;
import com.fpghoti.biscuit.biscuit.Biscuit;
import com.fpghoti.biscuit.util.PermUtil;
import com.fpghoti.biscuit.util.Util;
@ -13,11 +12,12 @@ import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
public class CommandManager {
private List<BaseCommand> commands = new ArrayList<BaseCommand>();
private static List<BaseCommand> commands = new ArrayList<BaseCommand>();
public void parse(String message, MessageReceivedEvent e){
public static void parse(String message, MessageReceivedEvent e){
Biscuit b = Biscuit.getBiscuit(e.getGuild());
ArrayList<String> split = new ArrayList<String>();
String fixed = message.replaceFirst(PropertiesRetrieval.getCommandSignifier(), "");
String fixed = message.replaceFirst(b.getProperties().getCommandSignifier(), "");
String[] splitMsg = fixed.split(" ");
for(String s: splitMsg){
split.add(s);
@ -30,18 +30,20 @@ public class CommandManager {
}
public boolean dispatch(String label, String[] args) {
public static boolean dispatch(String label, String[] args) {
return dispatch(null,label,args);
}
public boolean dispatch(MessageReceivedEvent e, String label, String[] args) {
public static boolean dispatch(MessageReceivedEvent e, String label, String[] args) {
Biscuit b = Main.getMainBiscuit();
boolean isMain = true;
if(e != null) {
if(Util.contains(PropertiesRetrieval.disabledCommands(), label)) {
b = Biscuit.getBiscuit(e.getGuild());
isMain = false;
if(Util.contains(b.getProperties().disabledCommands(), label)) {
return false;
}
if(!PermUtil.isAdmin(e.getMember()) && Util.contains(PropertiesRetrieval.disabledUserCommands(), label)) {
if(!PermUtil.isAdmin(e.getMember()) && Util.contains(b.getProperties().disabledUserCommands(), label)) {
return false;
}
@ -83,8 +85,17 @@ public class CommandManager {
}
}
}else {
if(Util.contains(PropertiesRetrieval.getCustomCmds(), label)) {
CustomCommand cc = new CustomCommand(label);
if(Util.contains(Main.getMainBiscuit().getProperties().getCustomCmds(), label)) {
CustomCommand cc = new CustomCommand(label, Main.getMainBiscuit());
if(args.length >= 1) {
commandReply(e, "``Command:" + " " + cc.getName() + "``");
commandReply(e, "``Description:" + " " + cc.getDescription() + "``");
commandReply(e, "``Usage:" + " " + cc.getUsage() + "``");
}else {
commandReply(e, CustomCommand.fixPlaceholders(e, cc.getMessage()));
}
}else if(!isMain && Util.contains(b.getProperties().getCustomCmds(), label)) {
CustomCommand cc = new CustomCommand(label, b);
if(args.length >= 1) {
commandReply(e, "``Command:" + " " + cc.getName() + "``");
commandReply(e, "``Description:" + " " + cc.getDescription() + "``");
@ -97,25 +108,24 @@ public class CommandManager {
return true;
}
public void commandReply(MessageReceivedEvent e, String msg) {
Biscuit b = Main.getBiscuit();
public static void commandReply(MessageReceivedEvent e, String msg) {
if(e != null) {
b.say(e.getTextChannel(), msg);
e.getTextChannel().sendMessage(msg).queue();
}else {
b.log(msg);
Main.getLogger().info(msg);
}
}
public void addCommand(BaseCommand command) {
public static void addCommand(BaseCommand command) {
commands.add(command);
}
public void removeCommand(BaseCommand command) {
public static void removeCommand(BaseComma