Auto stash before merge of "master" and "origin/master"

This commit is contained in:
Alex Stewart
2020-02-25 18:25:17 -05:00
parent d5346b3727
commit 6be6bd4033
17 changed files with 1356 additions and 1271 deletions
+11
View File
@@ -17,6 +17,8 @@
"Localized Commands","dbstats","" "Localized Commands","dbstats",""
"Localized Commands","defaultdance","" "Localized Commands","defaultdance",""
"Localized Commands","derp","" "Localized Commands","derp",""
"Localized Commands","derpi",""
"Localized Commands","e6",""
"Localized Commands","e621","" "Localized Commands","e621",""
"Localized Commands","eightball, 8ball","" "Localized Commands","eightball, 8ball",""
"Localized Commands","fetch","" "Localized Commands","fetch",""
@@ -48,6 +50,7 @@
"Localized Commands","stats","" "Localized Commands","stats",""
"Localized Commands","teey","" "Localized Commands","teey",""
"Localized Commands","tony, stark, dontfeelgood, dontfeelsogood","tony, stark, dontfeelgood, dontfeelsogood, snap" "Localized Commands","tony, stark, dontfeelgood, dontfeelsogood","tony, stark, dontfeelgood, dontfeelsogood, snap"
"Localized Commands","tradebeans",""
"Localized Commands","tweet","" "Localized Commands","tweet",""
"Localized Commands","vote","" "Localized Commands","vote",""
"Localized Commands","wolfram","" "Localized Commands","wolfram",""
@@ -110,8 +113,10 @@
"Localized Strings","DBFlushInfo","Takes all objects queued for the database and writes them to the database, then says how many were written." "Localized Strings","DBFlushInfo","Takes all objects queued for the database and writes them to the database, then says how many were written."
"Localized Strings","DBStatsInfo","Shows current statistics for the database" "Localized Strings","DBStatsInfo","Shows current statistics for the database"
"Localized Strings","DefaultDanceInfo","y'all know forknife, get ready to dance, or make a friend dance with @!" "Localized Strings","DefaultDanceInfo","y'all know forknife, get ready to dance, or make a friend dance with @!"
"Localized Strings","DerpiError",""
"Localized Strings","DoWorkFinished","I finished with my work! :D" "Localized Strings","DoWorkFinished","I finished with my work! :D"
"Localized Strings","DoWorkInfo","Occupies a core for a few seconds" "Localized Strings","DoWorkInfo","Occupies a core for a few seconds"
"Localized Strings","E6Blacklisted","I can't show that image ;3; (it may be blacklisted)"
"Localized Strings","EightBallError","Hmm? You'll need to ask a question!" "Localized Strings","EightBallError","Hmm? You'll need to ask a question!"
"Localized Strings","EightBallInfo","Answers a yes or no question! Warning: Kitty can not actually tell the future, she claims no responsibility for any lion mauling, lack of lottery wins, or felony charges." "Localized Strings","EightBallInfo","Answers a yes or no question! Warning: Kitty can not actually tell the future, she claims no responsibility for any lion mauling, lack of lottery wins, or felony charges."
"Localized Strings","EightBallMaybe1","Reply hazy, try again." "Localized Strings","EightBallMaybe1","Reply hazy, try again."
@@ -182,7 +187,10 @@
"Localized Strings","MapVersion","Using mapgen v0.1" "Localized Strings","MapVersion","Using mapgen v0.1"
"Localized Strings","MapWidth","" "Localized Strings","MapWidth",""
"Localized Strings","ModInfo","Mod is a super command for admin or mod use only!\n\t`mod ban @user` will ban a user from the server\n\t`mod kick @user` will kick the user from the server" "Localized Strings","ModInfo","Mod is a super command for admin or mod use only!\n\t`mod ban @user` will ban a user from the server\n\t`mod kick @user` will kick the user from the server"
"Localized Strings","MusicAddTrack",""
"Localized Strings","MusicInfo","" "Localized Strings","MusicInfo",""
"Localized Strings","MusicVolChanged","Volume set to %s!"
"Localized Strings","MusicVolCurrent","Volume is at %s!"
"Localized Strings","PerishInfo","Adds a red, 'a n g e r y' overlay to your icon or the icon of a friend you mentioned" "Localized Strings","PerishInfo","Adds a red, 'a n g e r y' overlay to your icon or the icon of a friend you mentioned"
"Localized Strings","PingInfo","Will respond with Pong!" "Localized Strings","PingInfo","Will respond with Pong!"
"Localized Strings","PingResponse","Pong!" "Localized Strings","PingResponse","Pong!"
@@ -271,6 +279,8 @@
"Command Enabler","dbstats","1" "Command Enabler","dbstats","1"
"Command Enabler","defaultdance","1" "Command Enabler","defaultdance","1"
"Command Enabler","derp","1" "Command Enabler","derp","1"
"Command Enabler","derpi","1"
"Command Enabler","e6","1"
"Command Enabler","e621","1" "Command Enabler","e621","1"
"Command Enabler","eightball, 8ball","1" "Command Enabler","eightball, 8ball","1"
"Command Enabler","fetch","1" "Command Enabler","fetch","1"
@@ -313,6 +323,7 @@
"Command Enabler","stats","1" "Command Enabler","stats","1"
"Command Enabler","teey","1" "Command Enabler","teey","1"
"Command Enabler","tony, stark, dontfeelgood, dontfeelsogood","1" "Command Enabler","tony, stark, dontfeelgood, dontfeelsogood","1"
"Command Enabler","tradebeans","1"
"Command Enabler","tweet","1" "Command Enabler","tweet","1"
"Command Enabler","vote","1" "Command Enabler","vote","1"
"Command Enabler","wolfram","1" "Command Enabler","wolfram","1"
1 Type Key Value
17 Localized Commands dbstats
18 Localized Commands defaultdance
19 Localized Commands derp
20 Localized Commands derpi
21 Localized Commands e6
22 Localized Commands e621
23 Localized Commands eightball, 8ball
24 Localized Commands fetch
50 Localized Commands stats
51 Localized Commands teey
52 Localized Commands tony, stark, dontfeelgood, dontfeelsogood tony, stark, dontfeelgood, dontfeelsogood, snap
53 Localized Commands tradebeans
54 Localized Commands tweet
55 Localized Commands vote
56 Localized Commands wolfram
113 Localized Strings DBFlushInfo Takes all objects queued for the database and writes them to the database, then says how many were written.
114 Localized Strings DBStatsInfo Shows current statistics for the database
115 Localized Strings DefaultDanceInfo y'all know forknife, get ready to dance, or make a friend dance with @!
116 Localized Strings DerpiError
117 Localized Strings DoWorkFinished I finished with my work! :D
118 Localized Strings DoWorkInfo Occupies a core for a few seconds
119 Localized Strings E6Blacklisted I can't show that image ;3; (it may be blacklisted)
120 Localized Strings EightBallError Hmm? You'll need to ask a question!
121 Localized Strings EightBallInfo Answers a yes or no question! Warning: Kitty can not actually tell the future, she claims no responsibility for any lion mauling, lack of lottery wins, or felony charges.
122 Localized Strings EightBallMaybe1 Reply hazy, try again.
187 Localized Strings MapVersion Using mapgen v0.1
188 Localized Strings MapWidth
189 Localized Strings ModInfo Mod is a super command for admin or mod use only!\n\t`mod ban @user` will ban a user from the server\n\t`mod kick @user` will kick the user from the server
190 Localized Strings MusicAddTrack
191 Localized Strings MusicInfo
192 Localized Strings MusicVolChanged Volume set to %s!
193 Localized Strings MusicVolCurrent Volume is at %s!
194 Localized Strings PerishInfo Adds a red, 'a n g e r y' overlay to your icon or the icon of a friend you mentioned
195 Localized Strings PingInfo Will respond with Pong!
196 Localized Strings PingResponse Pong!
279 Command Enabler dbstats 1
280 Command Enabler defaultdance 1
281 Command Enabler derp 1
282 Command Enabler derpi 1
283 Command Enabler e6 1
284 Command Enabler e621 1
285 Command Enabler eightball, 8ball 1
286 Command Enabler fetch 1
323 Command Enabler stats 1
324 Command Enabler teey 1
325 Command Enabler tony, stark, dontfeelgood, dontfeelsogood 1
326 Command Enabler tradebeans 1
327 Command Enabler tweet 1
328 Command Enabler vote 1
329 Command Enabler wolfram 1
+21 -21
View File
@@ -1,22 +1,22 @@
function plugin(message, user) function plugin(message, user)
local index; local index;
local concat; local concat;
if(string.find(message, "https://derpicdn.net/img"))then if(string.find(message, "https://derpicdn.net/img"))then
if(string.find(message, "view/"))then if(string.find(message, "view/"))then
index = string.find(message, "/[^/]*$"); index = string.find(message, "/[^/]*$");
return "!derpi ID:" .. string.sub(message, index + 1, string.find(message, ".[^.]*$")-1); return "!derpi ID:" .. string.sub(message, index + 1, string.find(message, ".[^.]*$")-1);
else else
if(string.find(message, "download/"))then if(string.find(message, "download/"))then
index = string.find(message, "_"); index = string.find(message, "_");
concat = string.sub(message, 0, index-1); concat = string.sub(message, 0, index-1);
return "!derpi ID:" .. string.sub(concat, string.find(message, "/[^/]*$") + 1); return "!derpi ID:" .. string.sub(concat, string.find(message, "/[^/]*$") + 1);
else else
index = string.find(message, "/[^/]*$"); index = string.find(message, "/[^/]*$");
concat = string.sub(message, 0, index - 1); concat = string.sub(message, 0, index - 1);
index = string.find(concat, "/[^/]*$"); index = string.find(concat, "/[^/]*$");
return "!derpi ID:" .. string.sub(concat, index + 1); return "!derpi ID:" .. string.sub(concat, index + 1);
end end
end end
end end
end end
+7 -7
View File
@@ -1,8 +1,8 @@
function plugin(message, user) function plugin(message, user)
if(string.find(message, "https://static1.e621.net/data") or string.find(message, "https://static1.e926.net/data"))then if(string.find(message, "https://static1.e621.net/data") or string.find(message, "https://static1.e926.net/data"))then
if(string.find(message, " "))then if(string.find(message, " "))then
message = string.sub(message, 0, string.find(message, " ")); message = string.sub(message, 0, string.find(message, " "));
end end
return "!e6 md5:" .. string.sub(message, string.find(message, "/[^/]*$") + 1 ,string.find(message, ".[^.]*$") - 1); return "!e6 md5:" .. string.sub(message, string.find(message, "/[^/]*$") + 1 ,string.find(message, ".[^.]*$") - 1);
end end
end end
+1 -1
View File
@@ -20,7 +20,7 @@ public class CommandBetBeans extends Command
{ {
String call = ""; String call = "";
int min = 50; int min = 20;
int bet = 0; int bet = 0;
int win = 0; int win = 0;
+71 -71
View File
@@ -1,72 +1,72 @@
package commands.general; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
import dataStructures.KittyEmbed; import dataStructures.KittyEmbed;
import dataStructures.KittyGuild; import dataStructures.KittyGuild;
import dataStructures.KittyRating; import dataStructures.KittyRating;
import dataStructures.KittyRole; import dataStructures.KittyRole;
import dataStructures.KittyUser; import dataStructures.KittyUser;
import dataStructures.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import network.NetworkDerpi; import network.NetworkDerpi;
public class CommandDerpi extends Command public class CommandDerpi extends Command
{ {
NetworkDerpi searcher = new NetworkDerpi(); NetworkDerpi searcher = new NetworkDerpi();
KittyEmbed response; KittyEmbed response;
// Required constructor // Required constructor
public CommandDerpi(KittyRole level, KittyRating rating) { super(level, rating); } public CommandDerpi(KittyRole level, KittyRating rating) { super(level, rating); }
@Override @Override
public String getHelpText() { return "Will search derpibooru for the tags entered, if KittyBot's content filter allows it"; } public String getHelpText() { return "Will search derpibooru for the tags entered, if KittyBot's content filter allows it"; }
@Override @Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res) public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{ {
if(guild.contentRating == KittyRating.Filtered) if(guild.contentRating == KittyRating.Filtered)
{ {
try try
{ {
response = searcher.getDerpi(input.args.replace(',', ' ') + " safe").output(); response = searcher.getDerpi(input.args.replace(',', ' ') + " safe").output();
res.send(response); res.send(response);
} }
catch(Exception e) catch(Exception e)
{ {
res.send(LocStrings.stub("DerpiError")); res.send(LocStrings.stub("DerpiError"));
} }
} }
else else
{ {
if(input.args == null || input.args.length() == 0) if(input.args == null || input.args.length() == 0)
res.send("DerpiNoSearchError"); res.send("DerpiNoSearchError");
else else
{ {
response = searcher.getDerpi(input.args).output(); response = searcher.getDerpi(input.args).output();
try try
{ {
res.send(response); res.send(response);
} }
catch(Exception e) catch(Exception e)
{ {
res.send(LocStrings.stub("DerpiError")); res.send(LocStrings.stub("DerpiError"));
} }
} }
} }
if(input.args.startsWith("ID:")) if(input.args.startsWith("ID:"))
{ {
response = searcher.getDerpiByID(input.args.substring(input.args.indexOf(':'))).output(); response = searcher.getDerpiByID(input.args.substring(input.args.indexOf(':'))).output();
try try
{ {
res.send(response); res.send(response);
} }
catch(Exception e) catch(Exception e)
{ {
res.send(LocStrings.stub("DerpiError")); res.send(LocStrings.stub("DerpiError"));
} }
} }
} }
} }
+75 -59
View File
@@ -1,60 +1,76 @@
package commands.general; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import dataStructures.*; import dataStructures.*;
import network.NetworkE6; import network.NetworkE6;
public class CommandE6 extends Command public class CommandE6 extends Command
{ {
NetworkE6 searcher = new NetworkE6(); NetworkE6 searcher = new NetworkE6();
KittyEmbed response; KittyEmbed response;
GenericImage image;
public CommandE6(KittyRole level, KittyRating rating) { super(level, rating); }
public CommandE6(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
public String getHelpText() @Override
{ public String getHelpText()
String toRet = "Will search e6"; {
toRet += "21 for the tags entered, if KittyBot's content filter allows it"; String toRet = "Will search e6";
return toRet; toRet += "21 for the tags entered, if KittyBot's content filter allows it";
} return toRet;
}
@Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res) @Override
{ public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
if(guild.contentRating == KittyRating.Filtered || !guild.channels.get(Long.getLong(channel.uniqueID)).mature) {
{ if(guild.contentRating == KittyRating.Filtered || !guild.channels.get(Long.getLong(channel.uniqueID)).mature)
if(!guild.channels.get(Long.getLong(channel.uniqueID)).mature) {
{ if(!guild.channels.get(Long.getLong(channel.uniqueID)).mature)
res.send("This channel is SFW only! Have some (probably) wholesome content ^^~"); {
} res.send("This channel is SFW only! Have some (probably) wholesome content ^^~");
response = searcher.getE6(input.args + " rating:safe").output(); }
try
{ image = searcher.getE6(input.args + " rating:safe");
res.send(response); try
} {
catch(Exception e) response = image.output();
{ }
res.send(LocStrings.stub("E6Blacklisted")); catch(Exception e)
} {
} res.send(LocStrings.stub("E6Blacklisted"));
else return;
{ }
if(input.args == null || input.args.length() == 0) try
res.send("E6NoSearchError"); {
else if(response.authorText == null)
{ {
try Exception e = new Exception();
{ throw e;
response = searcher.getE6(input.args).output(); }
res.send(response); res.send(response);
} }
catch(Exception e) catch(Exception e)
{ {
res.send(LocStrings.stub("E6Blacklisted")); res.send(LocStrings.stub("E6Blacklisted"));
} }
} }
} else
} {
if(input.args == null || input.args.length() == 0)
res.send("E6NoSearchError");
else
{
try
{
response = searcher.getE6(input.args).output();
res.send(response);
}
catch(Exception e)
{
res.send(LocStrings.stub("E6Blacklisted"));
}
}
}
}
} }
+1
View File
@@ -18,6 +18,7 @@ public class CommandMusicMain extends Command
framework.addCommand("skip", new SubCommandSkip(KittyRole.General, KittyRating.Safe)); framework.addCommand("skip", new SubCommandSkip(KittyRole.General, KittyRating.Safe));
framework.addCommand("stop", new SubCommandStop(KittyRole.General, KittyRating.Safe)); framework.addCommand("stop", new SubCommandStop(KittyRole.General, KittyRating.Safe));
framework.addCommand("playlist", new SubCommandPlaylist(KittyRole.General, KittyRating.Safe)); framework.addCommand("playlist", new SubCommandPlaylist(KittyRole.General, KittyRating.Safe));
framework.addCommand("volume", new SubCommandVolume(KittyRole.General, KittyRating.Safe));
} }
@Override @Override
+2 -1
View File
@@ -1,5 +1,6 @@
package commands.music; package commands.music;
import core.LocStrings;
import core.SubCommand; import core.SubCommand;
import core.SubCommandFormattable; import core.SubCommandFormattable;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
@@ -27,6 +28,6 @@ public class SubCommandAddTrack extends SubCommand
video = YT.getYT(video); video = YT.getYT(video);
} }
guild.audio.playVideo(video); guild.audio.playVideo(video);
return new SubCommandFormattable(video); return new SubCommandFormattable(String.format(LocStrings.stub("MusicAddTrack"), video));
} }
} }
+23 -23
View File
@@ -1,23 +1,23 @@
package commands.music; package commands.music;
import core.SubCommand; import core.SubCommand;
import core.SubCommandFormattable; import core.SubCommandFormattable;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
import dataStructures.KittyGuild; import dataStructures.KittyGuild;
import dataStructures.KittyRating; import dataStructures.KittyRating;
import dataStructures.KittyRole; import dataStructures.KittyRole;
import dataStructures.KittyUser; import dataStructures.KittyUser;
import dataStructures.UserInput; import dataStructures.UserInput;
public class SubCommandSkip extends SubCommand public class SubCommandSkip extends SubCommand
{ {
public SubCommandSkip(KittyRole level, KittyRating rating) { super(level, rating); } public SubCommandSkip(KittyRole level, KittyRating rating) { super(level, rating); }
{ {
} }
@Override @Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input) public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{ {
return new SubCommandFormattable(guild.audio.skipVideo(guild.audio.player)); return new SubCommandFormattable(guild.audio.skipVideo(guild.audio.player));
} }
} }
+42
View File
@@ -0,0 +1,42 @@
package commands.music;
import core.LocStrings;
import core.SubCommand;
import core.SubCommandFormattable;
import dataStructures.KittyChannel;
import dataStructures.KittyGuild;
import dataStructures.KittyRating;
import dataStructures.KittyRole;
import dataStructures.KittyUser;
import dataStructures.UserInput;
public class SubCommandVolume extends SubCommand
{
public SubCommandVolume(KittyRole level, KittyRating rating) { super(level, rating); }
{
}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
int newVol = guild.audio.getVolume(guild.audio.player);
if(input.args != null)
{
try
{
newVol = Integer.parseInt(input.args);
if(newVol > 100 || newVol <1)
{
return new SubCommandFormattable(String.format(LocStrings.stub("MusicVolOOB")));
}
guild.audio.changeVolume(guild.audio.player, newVol);
}
catch(Exception e)
{
return new SubCommandFormattable(String.format(LocStrings.stub("MusicVolCurrent"), newVol));
}
}
return new SubCommandFormattable(String.format(LocStrings.stub("MusicVolChanged"), newVol));
}
}
+235 -234
View File
@@ -1,234 +1,235 @@
package core; package core;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import commands.characters.CommandCharacterMain; import commands.characters.CommandCharacterMain;
import commands.general.*; import commands.general.*;
import commands.guildrole.CommandGuildRoleMain; import commands.guildrole.CommandGuildRoleMain;
import commands.mod.CommandModMain; import commands.mod.CommandModMain;
import commands.music.CommandMusicMain; import commands.music.CommandMusicMain;
import commands.poll.CommandPollMain; import commands.poll.CommandPollMain;
import commands.raffle.CommandRaffleMain; import commands.raffle.CommandRaffleMain;
import dataStructures.*; import dataStructures.*;
import utils.GlobalLog; import utils.GlobalLog;
import utils.LogFilter; import utils.LogFilter;
public class CommandManager public class CommandManager
{ {
// Variables // Variables
private HashMap<String, Command> commands; private HashMap<String, Command> commands;
private ArrayList<CommandThread> threadAccumulator; private ArrayList<CommandThread> threadAccumulator;
private CommandEnabler commandEnabler; private CommandEnabler commandEnabler;
private long invokeCount; private long invokeCount;
// Singleton // Singleton
public static CommandManager instance; public static CommandManager instance;
// Default Constructor // Default Constructor
public CommandManager(CommandEnabler commandEnabler) public CommandManager(CommandEnabler commandEnabler)
{ {
GlobalLog.log(LogFilter.Core, "Initializing " + this.getClass().getSimpleName()); GlobalLog.log(LogFilter.Core, "Initializing " + this.getClass().getSimpleName());
if(instance == null) if(instance == null)
{ {
this.commands = new HashMap<String, Command>(); this.commands = new HashMap<String, Command>();
this.threadAccumulator = new ArrayList<CommandThread>(); this.threadAccumulator = new ArrayList<CommandThread>();
this.invokeCount = 0; this.invokeCount = 0;
this.commandEnabler = commandEnabler; this.commandEnabler = commandEnabler;
registerAllCommands(); registerAllCommands();
instance = this; instance = this;
} }
else else
{ {
GlobalLog.error(LogFilter.Core, "You can't have two of the following: " + this.getClass().getSimpleName()); GlobalLog.error(LogFilter.Core, "You can't have two of the following: " + this.getClass().getSimpleName());
} }
} }
// Registers all the commands for the instance // Registers all the commands for the instance
public void registerAllCommands() public void registerAllCommands()
{ {
this.commands.clear(); this.commands.clear();
// Dev // Dev
this.register(LocCommands.stub("work"), new CommandDoWork(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("work"), new CommandDoWork(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("shutdown"), new CommandShutdown(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("shutdown"), new CommandShutdown(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("stats"), new CommandStats(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("stats"), new CommandStats(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("invite"), new CommandInvite(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("invite"), new CommandInvite(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("buildHelp"), new CommandHelpBuilder(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("buildHelp"), new CommandHelpBuilder(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("tweet"), new CommandTweet(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("tweet"), new CommandTweet(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("dbflush"), new CommandDBFlush(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("dbflush"), new CommandDBFlush(KittyRole.Dev, KittyRating.Safe));
this.register(LocCommands.stub("dbstats"), new CommandDBStats(KittyRole.Dev, KittyRating.Safe)); this.register(LocCommands.stub("dbstats"), new CommandDBStats(KittyRole.Dev, KittyRating.Safe));
// Admin // Admin
this.register(LocCommands.stub("rating"), new CommandRating(KittyRole.Admin, KittyRating.Safe)); this.register(LocCommands.stub("rating"), new CommandRating(KittyRole.Admin, KittyRating.Safe));
this.register(LocCommands.stub("indicator"), new CommandChangeIndicator(KittyRole.Admin, KittyRating.Safe)); this.register(LocCommands.stub("indicator"), new CommandChangeIndicator(KittyRole.Admin, KittyRating.Safe));
// Mod // Mod
this.register(LocCommands.stub("givebeans"), new CommandGiveBeans(KittyRole.Mod, KittyRating.Safe)); this.register(LocCommands.stub("givebeans"), new CommandGiveBeans(KittyRole.Mod, KittyRating.Safe));
this.register(LocCommands.stub("mod"), new CommandModMain(KittyRole.Mod, KittyRating.Safe)); this.register(LocCommands.stub("mod"), new CommandModMain(KittyRole.Mod, KittyRating.Safe));
// General // General
this.register(LocCommands.stub("fetch"), new CommandFetch(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("fetch"), new CommandFetch(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("teey"), new CommandTeey(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("teey"), new CommandTeey(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("perish, thenperish"), new CommandPerish(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("perish, thenperish"), new CommandPerish(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("yeet"), new CommandYeet(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("yeet"), new CommandYeet(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("ping"), new CommandPing(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("ping"), new CommandPing(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("boop"), new CommandBoop(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("boop"), new CommandBoop(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("roll"), new CommandRoll(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("roll"), new CommandRoll(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("choose"), new CommandChoose(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("choose"), new CommandChoose(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("help"), new CommandHelp(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("help"), new CommandHelp(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("info, about"), new CommandInfo(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("info, about"), new CommandInfo(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("wolfram"), new CommandWolfram(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("wolfram"), new CommandWolfram(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("c++, g++, cplus, cpp"), new CommandColiru(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("c++, g++, cplus, cpp"), new CommandColiru(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("java, jdoodle"), new CommandJDoodle(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("java, jdoodle"), new CommandJDoodle(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("beans"), new CommandBeansShow(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("beans"), new CommandBeansShow(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("kittyrole"), new CommandRole(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("kittyrole"), new CommandRole(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("bet"), new CommandBetBeans(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("bet"), new CommandBetBeans(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("map"), new CommandMap(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("map"), new CommandMap(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("rpstart"), new CommandRPStart(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("rpstart"), new CommandRPStart(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("rpend"), new CommandRPEnd(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("rpend"), new CommandRPEnd(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("tony, stark, dontfeelgood, dontfeelsogood"), new CommandStark(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("tony, stark, dontfeelgood, dontfeelsogood"), new CommandStark(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("blur"), new CommandBlurry(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("blur"), new CommandBlurry(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("eightball, 8ball"), new CommandEightBall(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("eightball, 8ball"), new CommandEightBall(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("catch"), new CommandCatch(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("catch"), new CommandCatch(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("bethistory"), new CommandBetHistory(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("bethistory"), new CommandBetHistory(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("crouton"), new CommandCrouton(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("crouton"), new CommandCrouton(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("benchmark, bench"), new CommandBenchmark(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("benchmark, bench"), new CommandBenchmark(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("leaderboard"), new CommandLeaderboard(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("leaderboard"), new CommandLeaderboard(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("color, colour"), new CommandColor(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("color, colour"), new CommandColor(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("remind"), new CommandRemind(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("remind"), new CommandRemind(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("role"), new CommandGuildRoleMain(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("role"), new CommandGuildRoleMain(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("character"), new CommandCharacterMain(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("character"), new CommandCharacterMain(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("raffle"), new CommandRaffleMain(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("raffle"), new CommandRaffleMain(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("poll"), new CommandPollMain(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("poll"), new CommandPollMain(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("music"), new CommandMusicMain(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("music"), new CommandMusicMain(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("defaultdance"), new CommandDefaultDance(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("defaultdance"), new CommandDefaultDance(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("getsauce"), new CommandGetSauce(KittyRole.General, KittyRating.Safe)); this.register(LocCommands.stub("getsauce"), new CommandGetSauce(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("tradebeans"), new CommandTradeBeans(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("e6"), new CommandE6(KittyRole.General, KittyRating.Filtered));
this.register(LocCommands.stub("derpi"), new CommandDerpi(KittyRole.General, KittyRating.Filtered)); this.register(LocCommands.stub("e6"), new CommandE6(KittyRole.General, KittyRating.Filtered));
} this.register(LocCommands.stub("derpi"), new CommandDerpi(KittyRole.General, KittyRating.Filtered));
}
// Allows the command manager to keep track of a command. Takes a pair (the un-localized and localzied commands)
// and the command associated with the localized commands. // Allows the command manager to keep track of a command. Takes a pair (the un-localized and localzied commands)
public void register(Pair<String, String> pair, Command command) // and the command associated with the localized commands.
{ public void register(Pair<String, String> pair, Command command)
if(pair == null || pair.Second == null) {
return; if(pair == null || pair.Second == null)
return;
String[] keys = pair.Second.split(",");
String[] keys = pair.Second.split(",");
for(int i = 0; i < keys.length; ++i)
{ for(int i = 0; i < keys.length; ++i)
String key = keys[i].trim().toLowerCase(); {
String key = keys[i].trim().toLowerCase();
command.registeredNames.add(key);
Command old = commands.put(key, command); command.registeredNames.add(key);
Command old = commands.put(key, command);
if(old != null)
{ if(old != null)
GlobalLog.warn(LogFilter.Core, "Writing over a command with the key " + key); {
return; GlobalLog.warn(LogFilter.Core, "Writing over a command with the key " + key);
} return;
}
GlobalLog.log(LogFilter.Core, "Command registered under key " + key);
} GlobalLog.log(LogFilter.Core, "Command registered under key " + key);
} }
}
// Calls the command but on a whole new thread!
public boolean invokeOnNewThread(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response responseContext) // Calls the command but on a whole new thread!
{ public boolean invokeOnNewThread(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response responseContext)
// This is here to prevent spinning up a thread if this wasn't even a command. {
if(input == null || !input.isValid()) // This is here to prevent spinning up a thread if this wasn't even a command.
return false; if(input == null || !input.isValid())
return false;
// At this point, verify that the command is enabled. If we don't have any info
// on if it's enabled or not, we assume it's enabled to prevent broken functionality due // At this point, verify that the command is enabled. If we don't have any info
// to formatting or casing issues. // on if it's enabled or not, we assume it's enabled to prevent broken functionality due
if(input.key != null && !commandEnabler.isEnabled(input.key)) // to formatting or casing issues.
return false; if(input.key != null && !commandEnabler.isEnabled(input.key))
return false;
Command command = commands.get(input.key);
if(command != null) Command command = commands.get(input.key);
{ if(command != null)
// Spin up a thread and begin it. The thread carries the info needed to invoke the command. {
CommandThread newThread = new CommandThread(this, input, guild, channel, user, responseContext); // Spin up a thread and begin it. The thread carries the info needed to invoke the command.
threadAccumulator.add(newThread); CommandThread newThread = new CommandThread(this, input, guild, channel, user, responseContext);
newThread.start(); threadAccumulator.add(newThread);
return true; newThread.start();
} return true;
else }
{ else
GlobalLog.warn(LogFilter.Command, "User " + user.name + " tried to invoke command that doesn't exist: " + input.key); {
return false; GlobalLog.warn(LogFilter.Command, "User " + user.name + " tried to invoke command that doesn't exist: " + input.key);
} return false;
} }
}
// Calls the command specified with the key, providing user information arguments, etc.
void invoke(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response responseContext) // Calls the command specified with the key, providing user information arguments, etc.
{ void invoke(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response responseContext)
if(input == null || !input.isValid()) {
return; if(input == null || !input.isValid())
return;
Command command = commands.get(input.key);
if(command != null) Command command = commands.get(input.key);
{ if(command != null)
++invokeCount; {
command.invoke(guild, channel, user, input, responseContext); ++invokeCount;
} command.invoke(guild, channel, user, input, responseContext);
} }
}
// Looks up command by name. If it exists, dumps help text, otherwise returns null.
public String getCommandHelpText(String key) // Looks up command by name. If it exists, dumps help text, otherwise returns null.
{ public String getCommandHelpText(String key)
Command command = commands.get(key); {
Command command = commands.get(key);
if(command != null)
return "`" + key + "`: " + command.getHelpText(); if(command != null)
return "`" + key + "`: " + command.getHelpText();
return null;
} return null;
}
// Returns the number of commands sent so far during this program run
public long getInvokeCount() // Returns the number of commands sent so far during this program run
{ public long getInvokeCount()
return invokeCount; {
} return invokeCount;
}
// Returns all commands by name
public ArrayList<Command> getAllRegisteredCommands() // Returns all commands by name
{ public ArrayList<Command> getAllRegisteredCommands()
ArrayList<Command> cmds = new ArrayList<Command>(); {
for(Entry<String, Command> entry : commands.entrySet()) ArrayList<Command> cmds = new ArrayList<Command>();
cmds.add(entry.getValue()); for(Entry<String, Command> entry : commands.entrySet())
cmds.add(entry.getValue());
return cmds;
} return cmds;
}
// Info about threads running packaged into an object
public class ThreadData // Info about threads running packaged into an object
{ public class ThreadData
public HashMap<Thread.State, Integer> states = new HashMap<Thread.State, Integer>(); {
} public HashMap<Thread.State, Integer> states = new HashMap<Thread.State, Integer>();
public ThreadData dumpThreadData() }
{ public ThreadData dumpThreadData()
ThreadData data = new ThreadData(); {
ThreadData data = new ThreadData();
for(int i = 0; i < threadAccumulator.size(); ++i)
{ for(int i = 0; i < threadAccumulator.size(); ++i)
Thread.State state = threadAccumulator.get(i).getState(); {
Integer num = data.states.get(state); Thread.State state = threadAccumulator.get(i).getState();
Integer num = data.states.get(state);
if(num == null)
num = 0; if(num == null)
num = 0;
data.states.put(state, num + 1);
} data.states.put(state, num + 1);
}
return data;
} return data;
} }
}
+478 -478
View File
@@ -1,479 +1,479 @@
package core; package core;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
//import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; //import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
//import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; //import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import core.lua.PluginManager; import core.lua.PluginManager;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
import dataStructures.KittyCore; import dataStructures.KittyCore;
import dataStructures.KittyGuild; import dataStructures.KittyGuild;
import dataStructures.KittyRating; import dataStructures.KittyRating;
import dataStructures.KittyRole; import dataStructures.KittyRole;
import dataStructures.KittyStartupMode; import dataStructures.KittyStartupMode;
import dataStructures.KittyUser; import dataStructures.KittyUser;
import main.Main; import main.Main;
import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.Emote; import net.dv8tion.jda.core.entities.Emote;
import net.dv8tion.jda.core.entities.Game; import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import offline.Ref; import offline.Ref;
import utils.AdminControl; import utils.AdminControl;
//import utils.AudioUtils; //import utils.AudioUtils;
import utils.GlobalLog; import utils.GlobalLog;
import utils.LogFilter; import utils.LogFilter;
import utils.audio.AudioUtils; import utils.audio.AudioUtils;
// NOTE(wisp): Isolated factory to assist with storage and caching if needed. // NOTE(wisp): Isolated factory to assist with storage and caching if needed.
// This also minimizes the number of places JDA interacts with our codebase. // This also minimizes the number of places JDA interacts with our codebase.
// As it stands, if the object name begins with Kitty, it's constructed here. // As it stands, if the object name begins with Kitty, it's constructed here.
// TODO: Make all methods ID based instead of event based // TODO: Make all methods ID based instead of event based
public class ObjectBuilderFactory public class ObjectBuilderFactory
{ {
// Key: guild string id, Value: guild information // Key: guild string id, Value: guild information
private static HashMap<String, KittyGuild> guildCache; private static HashMap<String, KittyGuild> guildCache;
// Key: channel string id, Value: channel information // Key: channel string id, Value: channel information
private static HashMap<String, KittyChannel> channelCache; private static HashMap<String, KittyChannel> channelCache;
// Key: guild string id + user string id, Value: user information // Key: guild string id + user string id, Value: user information
private static HashMap<String, KittyUser> userCache; private static HashMap<String, KittyUser> userCache;
// For tracking and managing object sync // For tracking and managing object sync
private static DatabaseManager database; private static DatabaseManager database;
// Stats tracking and whatnot... for setting stats too internally potentially // Stats tracking and whatnot... for setting stats too internally potentially
private static Stats stats; private static Stats stats;
// RPManger for tracking RP system // RPManger for tracking RP system
private static RPManager rpManager; private static RPManager rpManager;
// Plugin manager // Plugin manager
private static PluginManager pluginManager; private static PluginManager pluginManager;
// Command manager // Command manager
private static CommandManager commandManager; private static CommandManager commandManager;
//Audio track manager //Audio track manager
private static AudioPlayerManager playerManager = new DefaultAudioPlayerManager(); private static AudioPlayerManager playerManager = new DefaultAudioPlayerManager();
// Localization classes - these are singletons, but should be initialized before almost all other // Localization classes - these are singletons, but should be initialized before almost all other
// things so their inclusion in the factory is to ensure they're started at the correct time. // things so their inclusion in the factory is to ensure they're started at the correct time.
@SuppressWarnings("unused") private static LocStrings locStrings; @SuppressWarnings("unused") private static LocStrings locStrings;
@SuppressWarnings("unused") private static LocCommands locCommands; @SuppressWarnings("unused") private static LocCommands locCommands;
// Config // Config
@SuppressWarnings("unused") private static Config config; @SuppressWarnings("unused") private static Config config;
// Lazy initialization multithreaded mutex stuff to prevent explosions. // Lazy initialization multithreaded mutex stuff to prevent explosions.
// TODO: Investigate using 'synchronized' instead potentially // TODO: Investigate using 'synchronized' instead potentially
private static boolean hasInitialized; private static boolean hasInitialized;
private static Semaphore initMutex = new Semaphore(1); private static Semaphore initMutex = new Semaphore(1);
private static JDA kitty; private static JDA kitty;
// This is it, this is how the lazy init starts! // This is it, this is how the lazy init starts!
private static void lazyInit() private static void lazyInit()
{ {
if(hasInitialized) if(hasInitialized)
return; return;
try try
{ {
initMutex.acquire(); initMutex.acquire();
try try
{ {
// structure initialization // structure initialization
// Construct necessary data structures. // Construct necessary data structures.
guildCache = new HashMap<String, KittyGuild>(); guildCache = new HashMap<String, KittyGuild>();
userCache = new HashMap<String, KittyUser>(); userCache = new HashMap<String, KittyUser>();
channelCache = new HashMap<String, KittyChannel>(); channelCache = new HashMap<String, KittyChannel>();
database = null; database = null;
stats = null; stats = null;
AudioSourceManagers.registerRemoteSources(playerManager); AudioSourceManagers.registerRemoteSources(playerManager);
AudioSourceManagers.registerLocalSource(playerManager); AudioSourceManagers.registerLocalSource(playerManager);
// Start by reading from things that are external. Because // Start by reading from things that are external. Because
// we require these things to be resolved before the rest of the application, // we require these things to be resolved before the rest of the application,
// we place them here. // we place them here.
config = new Config(); config = new Config();
} }
finally finally
{ {
initMutex.release(); initMutex.release();
hasInitialized = true; hasInitialized = true;
} }
} }
catch(InterruptedException ie) catch(InterruptedException ie)
{ {
GlobalLog.error(LogFilter.Core, "Issue during object builder lazy initialization." GlobalLog.error(LogFilter.Core, "Issue during object builder lazy initialization."
+ " The factory was not initialized, and kitty will not be able to continue functionally."); + " The factory was not initialized, and kitty will not be able to continue functionally.");
} }
} }
//////////////////////// ////////////////////////
// Extraction Methods // // Extraction Methods //
//////////////////////// ////////////////////////
// Explicitly locks: guildCache // Explicitly locks: guildCache
public static KittyGuild extractGuild(GuildMessageReceivedEvent event) public static KittyGuild extractGuild(GuildMessageReceivedEvent event)
{ {
lazyInit(); lazyInit();
// Look up the guild. This process can only happen in a single-threaded way // Look up the guild. This process can only happen in a single-threaded way
// because of the nature of the cache. We wait until the last second to // because of the nature of the cache. We wait until the last second to
// look up the guild. // look up the guild.
String uid = event.getGuild().getId(); String uid = event.getGuild().getId();
List<Emote> emotes = event.getGuild().getEmotes(); List<Emote> emotes = event.getGuild().getEmotes();
ArrayList<String> emotesString = new ArrayList<String>(); ArrayList<String> emotesString = new ArrayList<String>();
HashMap<Long, KittyChannel> channels = new HashMap<Long, KittyChannel>(); HashMap<Long, KittyChannel> channels = new HashMap<Long, KittyChannel>();
String emote; String emote;
String emoteFix; String emoteFix;
channels.put(Long.getLong(uid), extractChannel(event)); channels.put(Long.getLong(uid), extractChannel(event));
for(int i = 0; i < emotes.size(); i++) for(int i = 0; i < emotes.size(); i++)
{ {
emote = emotes.get(i).toString(); emote = emotes.get(i).toString();
emoteFix = "<:" + emote.substring(2, emote.indexOf("(")); emoteFix = "<:" + emote.substring(2, emote.indexOf("("));
emoteFix += ":" + emote.substring(emote.indexOf("(")+1, emote.length()-1) + ">"; emoteFix += ":" + emote.substring(emote.indexOf("(")+1, emote.length()-1) + ">";
emotesString.add(emoteFix); emotesString.add(emoteFix);
} }
// once we're lazily initialized, we can synchronize w/ the // once we're lazily initialized, we can synchronize w/ the
// guildCache object now instead of having to use a mutex. // guildCache object now instead of having to use a mutex.
KittyGuild guild = null; KittyGuild guild = null;
synchronized (guildCache) synchronized (guildCache)
{ {
KittyGuild cachedGuild = guildCache.get(uid); KittyGuild cachedGuild = guildCache.get(uid);
if(cachedGuild != null) if(cachedGuild != null)
{ {
guild = cachedGuild; guild = cachedGuild;
} }
else else
{ {
// Construct a new guild with defaults // Construct a new guild with defaults
guild = new KittyGuild(uid, new AdminControl(event.getGuild()), emotesString, new AudioUtils(event.getGuild(), playerManager), channels); guild = new KittyGuild(uid, new AdminControl(event.getGuild()), emotesString, new AudioUtils(event.getGuild(), playerManager), channels);
DatabaseManager.instance.globalRegister(guild); DatabaseManager.instance.globalRegister(guild);
guildCache.put(uid, guild); guildCache.put(uid, guild);
} }
} }
return guild; return guild;
} }
// Explicitly locks: guildCache // Explicitly locks: guildCache
public static KittyRole extractRole(GuildMessageReceivedEvent event) public static KittyRole extractRole(GuildMessageReceivedEvent event)
{ {
lazyInit(); lazyInit();
// Looks up the user role. If none is found we check to see if they own // Looks up the user role. If none is found we check to see if they own
// the guild if not, they're assumed to be // the guild if not, they're assumed to be
// allowed to use the bot at a general level. // allowed to use the bot at a general level.
KittyRole role = KittyRole.General; KittyRole role = KittyRole.General;
if(event.getAuthor().getId() == event.getGuild().getOwner().getUser().getId()) if(event.getAuthor().getId() == event.getGuild().getOwner().getUser().getId())
{ {
role = KittyRole.Admin; role = KittyRole.Admin;
} }
String uid = event.getGuild().getId() + event.getAuthor().getId(); String uid = event.getGuild().getId() + event.getAuthor().getId();
synchronized(userCache) synchronized(userCache)
{ {
KittyUser cachedUser = userCache.get(uid); KittyUser cachedUser = userCache.get(uid);
if(cachedUser != null) if(cachedUser != null)
role = cachedUser.getRole(); role = cachedUser.getRole();
} }
return role; return role;
} }
// Explicitly locks: guildCache // Explicitly locks: guildCache
// Extracts the content rating information it can from the provided event. // Extracts the content rating information it can from the provided event.
public static KittyRating extractContentRating(GuildMessageReceivedEvent event) public static KittyRating extractContentRating(GuildMessageReceivedEvent event)
{ {
lazyInit(); lazyInit();
// Look up content rating of the guild, returns a safe content rating. // Look up content rating of the guild, returns a safe content rating.
KittyRating contentRating = KittyRating.Safe; KittyRating contentRating = KittyRating.Safe;
String uid = event.getGuild().getId(); String uid = event.getGuild().getId();
synchronized(guildCache) synchronized(guildCache)
{ {
KittyGuild cachedGuild = guildCache.get(uid); KittyGuild cachedGuild = guildCache.get(uid);
if(cachedGuild != null) if(cachedGuild != null)
contentRating = cachedGuild.contentRating; contentRating = cachedGuild.contentRating;
} }
return contentRating; return contentRating;
} }
// Implicitly locks guild cache by calling ExtractGuild // Implicitly locks guild cache by calling ExtractGuild
public static KittyChannel extractChannel(GuildMessageReceivedEvent event) public static KittyChannel extractChannel(GuildMessageReceivedEvent event)
{ {
lazyInit(); lazyInit();
String channelID = event.getChannel().getId(); String channelID = event.getChannel().getId();
KittyChannel channel = null; KittyChannel channel = null;
synchronized(channelCache) synchronized(channelCache)
{ {
KittyChannel cachedChannel = channelCache.get(channelID); KittyChannel cachedChannel = channelCache.get(channelID);
boolean mature; boolean mature;
if(cachedChannel != null) if(cachedChannel != null)
{ {
channel = cachedChannel; channel = cachedChannel;
} }
else else
{ {
mature = event.getChannel().isNSFW(); mature = event.getChannel().isNSFW();
channel = new KittyChannel(channelID, mature); channel = new KittyChannel(channelID, mature);
channelCache.put(channelID, channel); channelCache.put(channelID, channel);
} }
} }
return channel; return channel;
} }
// Implicitly locks guild cache by calling ExtractRole and ExtractGuild // Implicitly locks guild cache by calling ExtractRole and ExtractGuild
public static KittyUser extractUser(GuildMessageReceivedEvent event) public static KittyUser extractUser(GuildMessageReceivedEvent event)
{ {
lazyInit(); lazyInit();
String uid = event.getGuild().getId() + event.getAuthor().getId(); String uid = event.getGuild().getId() + event.getAuthor().getId();
KittyUser user = null; KittyUser user = null;
synchronized(userCache) synchronized(userCache)
{ {
KittyUser cachedUser = userCache.get(uid); KittyUser cachedUser = userCache.get(uid);
if(cachedUser != null) if(cachedUser != null)
{ {
updateUser(cachedUser, event.getMember()); updateUser(cachedUser, event.getMember());
user = cachedUser; user = cachedUser;
} }
else else
{ {
KittyRole role = extractRole(event); KittyRole role = extractRole(event);
KittyGuild guild = extractGuild(event); KittyGuild guild = extractGuild(event);
String name; String name;
if(event.getMember().getNickname() == null) if(event.getMember().getNickname() == null)
name = event.getAuthor().getName(); name = event.getAuthor().getName();
else else
name = event.getMember().getNickname(); name = event.getMember().getNickname();
String discordID = event.getMember().getUser().getId(); String discordID = event.getMember().getUser().getId();
String avatarID = event.getAuthor().getAvatarUrl(); String avatarID = event.getAuthor().getAvatarUrl();
user = new KittyUser(name, guild, role, uid, avatarID, discordID); user = new KittyUser(name, guild, role, uid, avatarID, discordID);
DatabaseManager.instance.globalRegister(user); DatabaseManager.instance.globalRegister(user);
userCache.put(uid, user); userCache.put(uid, user);
} }
} }
if(event.getMessage().getMentionedMembers().isEmpty()) if(event.getMessage().getMentionedMembers().isEmpty())
return user; return user;
Member mentioned; Member mentioned;
for(int i = 0; i < event.getMessage().getMentionedMembers().size(); i++) for(int i = 0; i < event.getMessage().getMentionedMembers().size(); i++)
{ {
mentioned = event.getMessage().getMentionedMembers().get(i); mentioned = event.getMessage().getMentionedMembers().get(i);
if(mentioned.getNickname() != null) if(mentioned.getNickname() != null)
extractUserByJDAUser(event.getGuild().getId(), mentioned.getNickname(), extractUserByJDAUser(event.getGuild().getId(), mentioned.getNickname(),
mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId()); mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId());
else else
extractUserByJDAUser(event.getGuild().getId(), mentioned.getUser().getName(), extractUserByJDAUser(event.getGuild().getId(), mentioned.getUser().getName(),
mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId()); mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId());
} }
return user; return user;
} }
// TODO: Clean up // TODO: Clean up
public static KittyUser extractUserByJDAUser(String guildID, String name, String userID, String avatarID, String discordID) public static KittyUser extractUserByJDAUser(String guildID, String name, String userID, String avatarID, String discordID)
{ {
lazyInit(); lazyInit();
String uid = guildID + userID; String uid = guildID + userID;
KittyUser user = null; KittyUser user = null;
synchronized(userCache) synchronized(userCache)
{ {
KittyUser cachedUser = userCache.get(uid); KittyUser cachedUser = userCache.get(uid);
if(cachedUser != null) if(cachedUser != null)
{ {
if(name != null) if(name != null)
cachedUser.name = name; cachedUser.name = name;
cachedUser.avatarID = avatarID; cachedUser.avatarID = avatarID;
user = cachedUser; user = cachedUser;
} }
else else
{ {
KittyRole role = KittyRole.General; KittyRole role = KittyRole.General;
KittyGuild guild = guildCache.get(guildID); KittyGuild guild = guildCache.get(guildID);
user = new KittyUser(name, guild, role, uid, avatarID, discordID); user = new KittyUser(name, guild, role, uid, avatarID, discordID);
DatabaseManager.instance.globalRegister(user); DatabaseManager.instance.globalRegister(user);
userCache.put(uid, user); userCache.put(uid, user);
} }
} }
return user; return user;
} }
// There is some redundant lookup occurring. If the user isn't cached yet, then we construct them and cache them. // There is some redundant lookup occurring. If the user isn't cached yet, then we construct them and cache them.
// The assumption is made that the user does, in fact, exist. // The assumption is made that the user does, in fact, exist.
public static KittyUser getKittyUser(String guildID, String userID) public static KittyUser getKittyUser(String guildID, String userID)
{ {
String uid = guildID + userID; String uid = guildID + userID;
KittyUser user = null; KittyUser user = null;
synchronized(userCache) synchronized(userCache)
{ {
user = userCache.get(uid); user = userCache.get(uid);
} }
if(user == null) if(user == null)
{ {
Guild jdaGuild = kitty.getGuildById(guildID); Guild jdaGuild = kitty.getGuildById(guildID);
if(jdaGuild == null) return null; if(jdaGuild == null) return null;
Member jdaMember = jdaGuild.getMemberById(userID); Member jdaMember = jdaGuild.getMemberById(userID);
if(jdaMember == null) return null; if(jdaMember == null) return null;
User jdaUser = jdaMember.getUser(); User jdaUser = jdaMember.getUser();
if(jdaUser == null) return null; if(jdaUser == null) return null;
user = extractUserByJDAUser(guildID, jdaMember.getNickname(), jdaUser.getId(), jdaUser.getAvatarUrl(), jdaUser.getId()); user = extractUserByJDAUser(guildID, jdaMember.getNickname(), jdaUser.getId(), jdaUser.getAvatarUrl(), jdaUser.getId());
updateUser(user, jdaMember); updateUser(user, jdaMember);
} }
return user; return user;
} }
// Updates a user's name appropriately based on nickname if available // Updates a user's name appropriately based on nickname if available
public static void updateUser(KittyUser user, Member member) public static void updateUser(KittyUser user, Member member)
{ {
if(member.getNickname() == null) if(member.getNickname() == null)
{ {
user.name = member.getUser().getName(); user.name = member.getUser().getName();
} }
else else
{ {
user.name = member.getNickname(); user.name = member.getNickname();
} }
user.avatarID = member.getUser().getAvatarUrl(); user.avatarID = member.getUser().getAvatarUrl();
} }
////////////////////////// //////////////////////////
// Construction Methods // // Construction Methods //
////////////////////////// //////////////////////////
// Builds the core of the bot // Builds the core of the bot
public static KittyCore constructKittyCore() throws LoginException, InterruptedException public static KittyCore constructKittyCore() throws LoginException, InterruptedException
{ {
lazyInit(); lazyInit();
// Determine token based on config. Default to test token. // Determine token based on config. Default to test token.
String tokenToUse = Ref.TestToken; String tokenToUse = Ref.TestToken;
if(ConfigGlobals.getStartupMode() == KittyStartupMode.Release) if(ConfigGlobals.getStartupMode() == KittyStartupMode.Release)
tokenToUse = Ref.Token; tokenToUse = Ref.PoguToken;
// Construct bot based on token // Construct bot based on token
kitty = new JDABuilder(AccountType.BOT) kitty = new JDABuilder(AccountType.BOT)
.setToken(tokenToUse).buildBlocking(); .setToken(tokenToUse).buildBlocking();
kitty.getPresence().setGame(Game.playing("with a laser pointer")); kitty.getPresence().setGame(Game.playing("with a laser pointer"));
kitty.addEventListener(new Main()); kitty.addEventListener(new Main());
return new KittyCore(kitty); return new KittyCore(kitty);
} }
// Default construction of the command manager. In order to remotely resolve command enabling // Default construction of the command manager. In order to remotely resolve command enabling
// and disabling, what we do is construct the commands with a localized pair that is checked against // and disabling, what we do is construct the commands with a localized pair that is checked against
// the CommandEnabler object passed in. In theory, we could have multiple CommandManagers, tho we can // the CommandEnabler object passed in. In theory, we could have multiple CommandManagers, tho we can
// only have one CommandEnabler. // only have one CommandEnabler.
public static CommandManager constructCommandManager(CommandEnabler commandEnabler) public static CommandManager constructCommandManager(CommandEnabler commandEnabler)
{ {
lazyInit(); lazyInit();
if(commandManager == null) if(commandManager == null)
commandManager = new CommandManager(commandEnabler); commandManager = new CommandManager(commandEnabler);
return commandManager; return commandManager;
} }
// Default database manager construction. It can be constructed // Default database manager construction. It can be constructed
// in different ways, and so we construct it outside of the constructor for // in different ways, and so we construct it outside of the constructor for
// the factory since it doesn't have to be present / can be elsewhere. // the factory since it doesn't have to be present / can be elsewhere.
// Effectively we cache the database here. // Effectively we cache the database here.
public static DatabaseManager constructDatabaseManager() public static DatabaseManager constructDatabaseManager()
{ {
lazyInit(); lazyInit();
if(database == null) if(database == null)
database = new DatabaseManager(); database = new DatabaseManager();
return database; return database;
} }
public static Stats constructStats(CommandManager manager) public static Stats constructStats(CommandManager manager)
{ {
lazyInit(); lazyInit();
if(stats == null) if(stats == null)
stats = new Stats(manager); stats = new Stats(manager);
return stats; return stats;
} }
public static RPManager constructRPManager() public static RPManager constructRPManager()
{ {
lazyInit(); lazyInit();
if(rpManager == null) if(rpManager == null)
rpManager = new RPManager(); rpManager = new RPManager();
return rpManager; return rpManager;
} }
public static PluginManager constructPluginManager() public static PluginManager constructPluginManager()
{ {
lazyInit(); lazyInit();
if(pluginManager == null) if(pluginManager == null)
pluginManager = new PluginManager(Constants.AssetDirectory + "plugins/"); pluginManager = new PluginManager(Constants.AssetDirectory + "plugins/");
return pluginManager; return pluginManager;
} }
///////////////////// /////////////////////
// Utility Methods // // Utility Methods //
///////////////////// /////////////////////
// Returns number of cached guilds (does not equal total users in the database, only what's in memory) // Returns number of cached guilds (does not equal total users in the database, only what's in memory)
public static Integer getGuildCount() public static Integer getGuildCount()
{ synchronized(guildCache) { synchronized(guildCache)
{ {
return guildCache.size(); return guildCache.size();
} }
} }
// Returns number of cached users (does not equal total users in the database, only what's in memory) // Returns number of cached users (does not equal total users in the database, only what's in memory)
public static Integer getUserCount() public static Integer getUserCount()
{ synchronized(userCache) { synchronized(userCache)
{ {
return userCache.size(); return userCache.size();
} }
} }
} }
+14 -14
View File
@@ -1,15 +1,15 @@
package dataStructures; package dataStructures;
public class KittyChannel public class KittyChannel
{ {
public String uniqueID; public String uniqueID;
public boolean mature; public boolean mature;
public KittyChannel(String uniqueID, boolean mature) public KittyChannel(String uniqueID, boolean mature)
{ {
//super(uniqueID); //super(uniqueID);
this.uniqueID = uniqueID; this.uniqueID = uniqueID;
this.mature = false; this.mature = false;
} }
} }
+180 -180
View File
@@ -1,180 +1,180 @@
package dataStructures; package dataStructures;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import core.DatabaseManager; import core.DatabaseManager;
import core.DatabaseTrackedObject; import core.DatabaseTrackedObject;
import utils.AdminControl; import utils.AdminControl;
import utils.audio.AudioUtils; import utils.audio.AudioUtils;
// Context for a given guild for kittybot. Primarily designed to hold guild-specific settings. // Context for a given guild for kittybot. Primarily designed to hold guild-specific settings.
public class KittyGuild extends DatabaseTrackedObject public class KittyGuild extends DatabaseTrackedObject
{ {
// Variables // Variables
public final String uniqueID; public final String uniqueID;
public KittyRating contentRating; public KittyRating contentRating;
public KittyUser guildOwner; public KittyUser guildOwner;
public boolean polling; public boolean polling;
public String poll; public String poll;
public boolean raffling; public boolean raffling;
public int raffleCost; public int raffleCost;
public ArrayList<String> hasVoted = new ArrayList<String>(); public ArrayList<String> hasVoted = new ArrayList<String>();
public ArrayList<String> emoji = new ArrayList<String>(); public ArrayList<String> emoji = new ArrayList<String>();
public ArrayList <KittyPoll> choices = new ArrayList<KittyPoll>(); public ArrayList <KittyPoll> choices = new ArrayList<KittyPoll>();
public HashMap <Long, KittyChannel> channels; public HashMap <Long, KittyChannel> channels;
public AdminControl control; public AdminControl control;
public AudioUtils audio; public AudioUtils audio;
public ArrayList <KittyUser> raffleUsersUnchosen = new ArrayList<KittyUser>(); public ArrayList <KittyUser> raffleUsersUnchosen = new ArrayList<KittyUser>();
public ArrayList <KittyUser> raffleUsersChosen = new ArrayList<KittyUser>(); public ArrayList <KittyUser> raffleUsersChosen = new ArrayList<KittyUser>();
// Database synced info // Database synced info
private final String roleListName = "guildRoles"; private final String roleListName = "guildRoles";
public final KittyTrackedVector roleList; public final KittyTrackedVector roleList;
private final String beansName = "guildBeans"; private final String beansName = "guildBeans";
public final KittyTrackedLong beans; public final KittyTrackedLong beans;
private String commandIndicator; private String commandIndicator;
private void registerTrackedObjects() private void registerTrackedObjects()
{ {
DatabaseManager.instance.globalRegister(roleList); DatabaseManager.instance.globalRegister(roleList);
DatabaseManager.instance.globalRegister(beans); DatabaseManager.instance.globalRegister(beans);
} }
// Default content for a guild // Default content for a guild
public KittyGuild(String uniqueID, AdminControl adminControl, ArrayList <String> emoji, AudioUtils audio, HashMap<Long, KittyChannel> channels) public KittyGuild(String uniqueID, AdminControl adminControl, ArrayList <String> emoji, AudioUtils audio, HashMap<Long, KittyChannel> channels)
{ {
super(uniqueID); super(uniqueID);
this.uniqueID = uniqueID; this.uniqueID = uniqueID;
roleList = new KittyTrackedVector(roleListName, uniqueID); roleList = new KittyTrackedVector(roleListName, uniqueID);
beans = new KittyTrackedLong(beansName, uniqueID); beans = new KittyTrackedLong(beansName, uniqueID);
registerTrackedObjects(); registerTrackedObjects();
control = adminControl; control = adminControl;
this.contentRating = KittyRating.Safe; this.contentRating = KittyRating.Safe;
this.polling = false; this.polling = false;
this.emoji = emoji; this.emoji = emoji;
this.audio = audio; this.audio = audio;
this.channels = channels; this.channels = channels;
setCommandIndicator("!"); setCommandIndicator("!");
} }
// Explicit constructor // Explicit constructor
public KittyGuild(String commandIndicator, KittyRating contentRating, KittyUser guildOwner, String uniqueID, AudioUtils audio, HashMap<Long, KittyChannel> channels) public KittyGuild(String commandIndicator, KittyRating contentRating, KittyUser guildOwner, String uniqueID, AudioUtils audio, HashMap<Long, KittyChannel> channels)
{ {
super(uniqueID); super(uniqueID);
this.uniqueID = uniqueID; this.uniqueID = uniqueID;
roleList = new KittyTrackedVector(roleListName, uniqueID); roleList = new KittyTrackedVector(roleListName, uniqueID);
beans = new KittyTrackedLong(beansName, uniqueID); beans = new KittyTrackedLong(beansName, uniqueID);
registerTrackedObjects(); registerTrackedObjects();
setCommandIndicator(commandIndicator); setCommandIndicator(commandIndicator);
this.contentRating = contentRating; this.contentRating = contentRating;
this.polling = false; this.polling = false;
this.guildOwner = guildOwner; this.guildOwner = guildOwner;
this.audio = audio; this.audio = audio;
this.channels = channels; this.channels = channels;
} }
public String startPoll(String poll) public String startPoll(String poll)
{ {
polling = true; polling = true;
this.poll = poll; this.poll = poll;
return "Poll `" + poll + "` started! Don't forget to add choices with `!poll choice`~"; return "Poll `" + poll + "` started! Don't forget to add choices with `!poll choice`~";
} }
public String addChoiceToPoll(String choice) public String addChoiceToPoll(String choice)
{ {
choices.add(new KittyPoll(choice)); choices.add(new KittyPoll(choice));
return "Added `" + choice + "` to poll!"; return "Added `" + choice + "` to poll!";
} }
public String endPoll() public String endPoll()
{ {
choices.clear(); choices.clear();
hasVoted.clear(); hasVoted.clear();
this.polling = false; this.polling = false;
poll = null; poll = null;
return "Poll ended!"; return "Poll ended!";
} }
//Raffle methods //Raffle methods
public boolean startRaffle(int beanCost) public boolean startRaffle(int beanCost)
{ {
if(raffling) if(raffling)
{ {
return false; return false;
} }
raffleCost = beanCost; raffleCost = beanCost;
raffling = true; raffling = true;
return true; return true;
} }
public boolean endRaffle() public boolean endRaffle()
{ {
if(raffling) if(raffling)
{ {
raffleCost = 0; raffleCost = 0;
raffling = false; raffling = false;
raffleUsersChosen.removeAll(raffleUsersChosen); raffleUsersChosen.removeAll(raffleUsersChosen);
raffleUsersUnchosen.removeAll(raffleUsersUnchosen); raffleUsersUnchosen.removeAll(raffleUsersUnchosen);
return true; return true;
} }
return false; return false;
} }
public boolean joinRaffle(KittyUser user) public boolean joinRaffle(KittyUser user)
{ {
if(!raffleUsersChosen.contains(user) && !raffleUsersUnchosen.contains(user) && user.getBeans() > raffleCost && raffling) if(!raffleUsersChosen.contains(user) && !raffleUsersUnchosen.contains(user) && user.getBeans() > raffleCost && raffling)
{ {
user.changeBeans(raffleCost); user.changeBeans(-raffleCost);
raffleUsersUnchosen.add(user); raffleUsersUnchosen.add(user);
return true; return true;
} }
return false; return false;
} }
public KittyUser chooseRaffleWinner() public KittyUser chooseRaffleWinner()
{ {
if(!raffleUsersUnchosen.isEmpty()) if(!raffleUsersUnchosen.isEmpty())
{ {
KittyUser chosen = raffleUsersUnchosen.get((int) (Math.random() * raffleUsersUnchosen.size())); KittyUser chosen = raffleUsersUnchosen.get((int) (Math.random() * raffleUsersUnchosen.size()));
raffleUsersUnchosen.remove(chosen); raffleUsersUnchosen.remove(chosen);
raffleUsersChosen.add(chosen); raffleUsersChosen.add(chosen);
return chosen; return chosen;
} }
return null; return null;
} }
@Override @Override
public String serialize() public String serialize()
{ {
return commandIndicator; return commandIndicator;
} }
@Override @Override
public void deSerialzie(String string) public void deSerialzie(String string)
{ {
if(string == null || string.length() == 0) if(string == null || string.length() == 0)
setCommandIndicator("!"); setCommandIndicator("!");
else else
setCommandIndicator(string); setCommandIndicator(string);
} }
public String getCommandIndicator() public String getCommandIndicator()
{ {
return commandIndicator; return commandIndicator;
} }
public void setCommandIndicator(String newIndicator) public void setCommandIndicator(String newIndicator)
{ {
if(newIndicator != commandIndicator) if(newIndicator != commandIndicator)
{ {
commandIndicator = newIndicator; commandIndicator = newIndicator;
markDirty(); markDirty();
} }
} }
} }
+134 -134
View File
@@ -1,135 +1,135 @@
package main; package main;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame; import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import core.CharacterManager; import core.CharacterManager;
import core.CommandEnabler; import core.CommandEnabler;
import core.CommandManager; import core.CommandManager;
import core.DatabaseManager; import core.DatabaseManager;
import core.ObjectBuilderFactory; import core.ObjectBuilderFactory;
import core.RPManager; import core.RPManager;
import core.Stats; import core.Stats;
import core.lua.PluginManager; import core.lua.PluginManager;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
import dataStructures.KittyCore; import dataStructures.KittyCore;
import dataStructures.KittyGuild; import dataStructures.KittyGuild;
import dataStructures.KittyUser; import dataStructures.KittyUser;
import dataStructures.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.audio.AudioSendHandler; import net.dv8tion.jda.core.audio.AudioSendHandler;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.VoiceChannel; import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter; import net.dv8tion.jda.core.hooks.ListenerAdapter;
import net.dv8tion.jda.core.managers.AudioManager; import net.dv8tion.jda.core.managers.AudioManager;
import offline.Ref; import offline.Ref;
import utils.GlobalLog; import utils.GlobalLog;
// http://www.slf4j.org/ - this JDA logging tool has been disabled by specifying NOP implementation. // http://www.slf4j.org/ - this JDA logging tool has been disabled by specifying NOP implementation.
// This is the application entry point, and bot startup location! // This is the application entry point, and bot startup location!
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class Main extends ListenerAdapter public class Main extends ListenerAdapter
{ {
// Variables and bot specific objects // Variables and bot specific objects
private static KittyCore kittyCore; private static KittyCore kittyCore;
private static DatabaseManager databaseManager; private static DatabaseManager databaseManager;
private static CommandManager commandManager; private static CommandManager commandManager;
private static Stats stats; private static Stats stats;
private static RPManager rpManager; private static RPManager rpManager;
private static PluginManager pluginManager; private static PluginManager pluginManager;
private static CharacterManager charManager; private static CharacterManager charManager;
// Initialization and setup // Initialization and setup
public static void main(String[] args) throws InterruptedException, LoginException, Exception public static void main(String[] args) throws InterruptedException, LoginException, Exception
{ {
// Factory startup. The ordering is intentional. // Factory startup. The ordering is intentional.
GlobalLog.initialize(); GlobalLog.initialize();
databaseManager = ObjectBuilderFactory.constructDatabaseManager(); databaseManager = ObjectBuilderFactory.constructDatabaseManager();
commandManager = ObjectBuilderFactory.constructCommandManager(CommandEnabler.instance); // TODO: Untangle this singleton commandManager = ObjectBuilderFactory.constructCommandManager(CommandEnabler.instance); // TODO: Untangle this singleton
stats = ObjectBuilderFactory.constructStats(commandManager); stats = ObjectBuilderFactory.constructStats(commandManager);
charManager = new CharacterManager(); charManager = new CharacterManager();
rpManager = ObjectBuilderFactory.constructRPManager(); rpManager = ObjectBuilderFactory.constructRPManager();
pluginManager = ObjectBuilderFactory.constructPluginManager(); pluginManager = ObjectBuilderFactory.constructPluginManager();
// Bot startup // Bot startup
kittyCore = ObjectBuilderFactory.constructKittyCore(); kittyCore = ObjectBuilderFactory.constructKittyCore();
} }
// When a message is sent in a server that kitty is in, this is what's called. // When a message is sent in a server that kitty is in, this is what's called.
@Override @Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) public void onGuildMessageReceived(GuildMessageReceivedEvent event)
{ {
// Tweak the event as necessary // Tweak the event as necessary
if(!Superintendent.preProcessSetup(event, stats)) if(!Superintendent.preProcessSetup(event, stats))
return; return;
// Factory objects // Factory objects
KittyUser user = ObjectBuilderFactory.extractUser(event); KittyUser user = ObjectBuilderFactory.extractUser(event);
KittyGuild guild = ObjectBuilderFactory.extractGuild(event); KittyGuild guild = ObjectBuilderFactory.extractGuild(event);
KittyChannel channel = ObjectBuilderFactory.extractChannel(event); KittyChannel channel = ObjectBuilderFactory.extractChannel(event);
// Specialized uncached objects // Specialized uncached objects
Response response = new Response(event, kittyCore); Response response = new Response(event, kittyCore);
UserInput input = new UserInput(event, guild); UserInput input = new UserInput(event, guild);
// Tweak object construction as necessary // Tweak object construction as necessary
if(!Superintendent.postProcessSetup(event, user, guild, channel, response, input)) if(!Superintendent.postProcessSetup(event, user, guild, channel, response, input))
return; return;
// Track beans! // Track beans!
user.changeBeans(1); user.changeBeans(1);
// RP logging system // RP logging system
RPManager.instance.addLine(channel, user, input); RPManager.instance.addLine(channel, user, input);
// Run any pre-emptive upkeep we need to // Run any pre-emptive upkeep we need to
if(!Superintendent.perCommandUpkeepPre(pluginManager)) if(!Superintendent.perCommandUpkeepPre(pluginManager))
return; return;
// Attempt to spin up a command. If the command doesn't exist. // Attempt to spin up a command. If the command doesn't exist.
// Run plugins right before invoking the commands but after all other setup. // Run plugins right before invoking the commands but after all other setup.
if(commandManager.invokeOnNewThread(guild, channel, user, input, response) == false) if(commandManager.invokeOnNewThread(guild, channel, user, input, response) == false)
{ {
List<String> pluginOutput = pluginManager.runAll(input.message, user); List<String> pluginOutput = pluginManager.runAll(input.message, user);
if(pluginOutput != null && pluginOutput.size() > 0) if(pluginOutput != null && pluginOutput.size() > 0)
{ {
for(int i = 0; i < pluginOutput.size(); ++i) for(int i = 0; i < pluginOutput.size(); ++i)
{ {
if(pluginOutput.get(i).startsWith("!")) if(pluginOutput.get(i).startsWith("!"))
{ {
commandManager.invokeOnNewThread(guild, channel, user, new UserInput(pluginOutput.get(i).substring(1), guild), response); commandManager.invokeOnNewThread(guild, channel, user, new UserInput(pluginOutput.get(i).substring(1), guild), response);
} }
else else
{ {
response.send(pluginOutput.get(i)); response.send(pluginOutput.get(i));
} }
} }
} }
} }
// Run any upkeep in post we need to // Run any upkeep in post we need to
if(!Superintendent.perCommandUpkeepPost(kittyCore, databaseManager)) if(!Superintendent.perCommandUpkeepPost(kittyCore, databaseManager))
return; return;
} }
} }
+48 -48
View File
@@ -1,48 +1,48 @@
package network; package network;
import java.util.List; import java.util.List;
import com.google.gson.Gson; import com.google.gson.Gson;
import offline.Ref; import offline.Ref;
import utils.HTTPUtils; import utils.HTTPUtils;
public class NetworkSauceNAO public class NetworkSauceNAO
{ {
private static final Gson jsonParser_ = new Gson(); private static final Gson jsonParser_ = new Gson();
private static final String API_ROOT = "https://saucenao.com/search.php?db=999&output_type=2&numres=10&api_key=" + Ref.SauceNAOKey +"&url="; private static final String API_ROOT = "https://saucenao.com/search.php?db=999&output_type=2&numres=10&api_key=" + Ref.SauceNAOKey +"&url=";
NetworkE6 e6Sauce = new NetworkE6(); NetworkE6 e6Sauce = new NetworkE6();
private class SauceNAOResponseObject private class SauceNAOResponseObject
{ {
List<SauceNAOResult> results; List<SauceNAOResult> results;
} }
private class SauceNAOResult private class SauceNAOResult
{ {
SauceNAOData data; SauceNAOData data;
} }
private class SauceNAOData private class SauceNAOData
{ {
String [] ext_urls; String [] ext_urls;
} }
public String getSauce(String input) public String getSauce(String input)
{ {
input = input.trim(); input = input.trim();
input = input.replace("+", "%2B"); input = input.replace("+", "%2B");
input = input.replace(" ", "%20"); input = input.replace(" ", "%20");
String res = HTTPUtils.sendGETRequest(API_ROOT + input); String res = HTTPUtils.sendGETRequest(API_ROOT + input);
SauceNAOResponseObject sauce = jsonParser_.fromJson(res, SauceNAOResponseObject.class); SauceNAOResponseObject sauce = jsonParser_.fromJson(res, SauceNAOResponseObject.class);
String sauceUrl = sauce.results.get(0).data.ext_urls[0]; String sauceUrl = sauce.results.get(0).data.ext_urls[0];
if(sauceUrl.startsWith("https://e621.net/post/show/")) if(sauceUrl.startsWith("https://e621.net/post/show/"))
{ {
System.out.println("id:" + sauceUrl.substring(26)); System.out.println("id:" + sauceUrl.substring(26));
return e6Sauce.getE6("id:" + sauceUrl.substring(27)).toString(); return e6Sauce.getE6("id:" + sauceUrl.substring(27)).toString();
} }
return sauce.results.get(0).data.ext_urls[0]; return sauce.results.get(0).data.ext_urls[0];
} }
} }
+13
View File
@@ -119,6 +119,16 @@ public class AudioUtils
return null; return null;
} }
public int getVolume(AudioPlayer player)
{
return player.getVolume();
}
public void changeVolume(AudioPlayer player, int newVol)
{
player.setVolume(newVol);
}
public String skipVideo(AudioPlayer player) public String skipVideo(AudioPlayer player)
{ {
player.stopTrack(); player.stopTrack();
@@ -152,6 +162,9 @@ class MusicController extends Thread
@Override @Override
public void run() public void run()
{ {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
AudioTrack nowPlaying = null; AudioTrack nowPlaying = null;
do do
{ {