21 Commits
Author SHA1 Message Date
Matthew Cech 8cfb3b951c = dew placeholder wip 2019-10-17 21:43:19 -07:00
Matthew Cech 01f39aba68 - removed unused unused 2019-09-26 20:07:52 -07:00
Matthew Cech e642551019 + Added stubs and some error checking to prevent lockout. 2019-09-14 01:31:16 -07:00
Matthew Cech 861aa95d96 = Adjusting last message response to be a bit less horrible. Still needs overhaul. 2019-09-14 01:11:24 -07:00
Matthew Cech 9b5ae3371d + Highly experimental last message info now saved 2019-09-14 00:56:45 -07:00
Matthew Cech 9d0bbf0ed1 + Added exception logging and fixed dice rolling 2019-09-13 22:32:37 -07:00
Matthew Cech b96d96c849 + Added super basic initial implementaiton of realm visualization and input 2019-09-13 00:28:26 -07:00
Matthew Cech e81e0972a3 + Added visualize basics 2019-09-12 23:51:20 -07:00
Matthew Cech b3187bb89d = Updated color to allow for parsing even with text after it 2019-09-12 23:18:23 -07:00
Matthew Cech d681bb6a4d Merge branch 'develop' into feature/dew 2019-09-12 22:50:23 -07:00
Matthew Cech 96b4533b39 = read/write first pass - seems to work! :D 2019-09-12 02:35:59 -07:00
Matthew Cech 498c3b84bc + Added lua reading and writing basics 2019-09-12 00:17:07 -07:00
Matthew Cech 4b8b125d05 + Added lua writing functionality 2019-09-11 23:10:36 -07:00
Matthew Cech cf7bd68658 + Added adapter concept 2019-09-11 19:53:20 -07:00
Matthew Cech 1e73f6adae + Weh csv 2019-09-11 14:43:09 -07:00
Matthew Cech 9d892e7fc2 + Added "weh" command 2019-09-11 14:42:01 -07:00
Matthew Cech 2fd273c298 + Added core base for dew 2019-09-11 14:28:18 -07:00
Matthew Cech 7581dab87d + Added dew command and generated CSV content for it 2019-09-11 14:10:56 -07:00
Matthew Cech 28377cf78e = Move benchmark core to fit existing standard 2019-09-11 14:03:02 -07:00
Matthew Cech d1dfab411e = Updated return, sorted bench 2019-09-11 14:01:32 -07:00
Matthew Cech 770ed84983 + Add dew base 2019-09-11 13:58:46 -07:00
116 changed files with 3030 additions and 3461 deletions
+2 -4
View File
@@ -12,6 +12,7 @@
<classpathentry kind="lib" path="lib/httpclient-4.5.5.jar"/> <classpathentry kind="lib" path="lib/httpclient-4.5.5.jar"/>
<classpathentry kind="lib" path="lib/httpcore-4.4.9.jar"/> <classpathentry kind="lib" path="lib/httpcore-4.4.9.jar"/>
<classpathentry kind="lib" path="lib/WolframAlpha-1.1.jar"/> <classpathentry kind="lib" path="lib/WolframAlpha-1.1.jar"/>
<classpathentry kind="lib" path="lib/JDA-3.7.1_385-withDependencies.jar"/>
<classpathentry kind="lib" path="lib/sqlite-jdbc-3.23.1.jar"/> <classpathentry kind="lib" path="lib/sqlite-jdbc-3.23.1.jar"/>
<classpathentry kind="lib" path="lib/slf4j-jdk14-1.7.25.jar"/> <classpathentry kind="lib" path="lib/slf4j-jdk14-1.7.25.jar"/>
<classpathentry kind="lib" path="lib/twitter4j-core-4.0.7-javadoc.jar"/> <classpathentry kind="lib" path="lib/twitter4j-core-4.0.7-javadoc.jar"/>
@@ -23,10 +24,7 @@
<classpathentry kind="lib" path="lib/commons-collections4-4.3.jar"/> <classpathentry kind="lib" path="lib/commons-collections4-4.3.jar"/>
<classpathentry kind="lib" path="lib/commons-lang3-3.9.jar"/> <classpathentry kind="lib" path="lib/commons-lang3-3.9.jar"/>
<classpathentry kind="lib" path="lib/commons-text-1.6.jar"/> <classpathentry kind="lib" path="lib/commons-text-1.6.jar"/>
<classpathentry kind="lib" path="lib/google-http-client-1.32.0.jar"/>
<classpathentry kind="lib" path="lib/google-api-services-youtube-v3-rev212-1.25.0.jar"/> <classpathentry kind="lib" path="lib/google-api-services-youtube-v3-rev212-1.25.0.jar"/>
<classpathentry kind="lib" path="lib/nanohttpd-2.3.1.jar"/> <classpathentry kind="lib" path="lib/lavaplayer-1.3.19.jar"/>
<classpathentry kind="lib" path="lib/LavaPlayerJar-1.3.50-jar-with-dependencies.jar"/>
<classpathentry kind="lib" path="lib/JDA-4.2.0_168-withDependencies.jar"/>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>
-2
View File
@@ -68,5 +68,3 @@ rP\.txt
*.log *.log
cloc\.exe cloc\.exe
beanImage.png
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

+8 -23
View File
@@ -1,6 +1,4 @@
"Type","Key","Value" "Type","Key","Value"
"Globals","mode (dev or release)","dev"
"Globals","activity","with a laser pointer"
"Localized Commands","beans","" "Localized Commands","beans",""
"Localized Commands","benchmark, bench","" "Localized Commands","benchmark, bench",""
"Localized Commands","bet","" "Localized Commands","bet",""
@@ -18,12 +16,10 @@
"Localized Commands","dbstats","" "Localized Commands","dbstats",""
"Localized Commands","defaultdance","" "Localized Commands","defaultdance",""
"Localized Commands","derp","" "Localized Commands","derp",""
"Localized Commands","derpi","" "Localized Commands","dew",""
"Localized Commands","e6",""
"Localized Commands","e621","" "Localized Commands","e621",""
"Localized Commands","eightball, 8ball","" "Localized Commands","eightball, 8ball",""
"Localized Commands","fetch","" "Localized Commands","fetch",""
"Localized Commands","getsauce",""
"Localized Commands","givebeans","" "Localized Commands","givebeans",""
"Localized Commands","help","" "Localized Commands","help",""
"Localized Commands","indicator","" "Localized Commands","indicator",""
@@ -51,15 +47,13 @@
"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, trade",""
"Localized Commands","tweet","" "Localized Commands","tweet",""
"Localized Commands","vote","" "Localized Commands","vote",""
"Localized Commands","weh",""
"Localized Commands","wolfram","" "Localized Commands","wolfram",""
"Localized Commands","work","" "Localized Commands","work",""
"Localized Commands","yeet","" "Localized Commands","yeet",""
"Localized Strings","AddGuildRoleFailure","Failed to add %s to %s" "Localized Strings","AddGuildRoleFailure","Failed to add %s to %s"
"Localized Strings","BeansImageBottomText","BEANS"
"Localized Strings","BeansImageTopText","YOU HAVE"
"Localized Strings","BeansShowDisplay","You have %s beans!" "Localized Strings","BeansShowDisplay","You have %s beans!"
"Localized Strings","BeansShowInfo","Displays how many beans you have" "Localized Strings","BeansShowInfo","Displays how many beans you have"
"Localized Strings","BeansShowMentioned","I took a look and %sbeans!" "Localized Strings","BeansShowMentioned","I took a look and %sbeans!"
@@ -68,13 +62,12 @@
"Localized Strings","BetBeansInfo","Allows you to bet your beans, set your amount after the command! Warning! House always wins!nSets of 3 will get 2x, 4 will get 10x, and 5 will get 1000x" "Localized Strings","BetBeansInfo","Allows you to bet your beans, set your amount after the command! Warning! House always wins!nSets of 3 will get 2x, 4 will get 10x, and 5 will get 1000x"
"Localized Strings","BetBeansLose","Sorry, you didn't win, try again!" "Localized Strings","BetBeansLose","Sorry, you didn't win, try again!"
"Localized Strings","BetBeansLowBet","Please bet with at least 20 beans!" "Localized Strings","BetBeansLowBet","Please bet with at least 20 beans!"
"Localized Strings","BetBeansMinThreshold","" "Localized Strings","BetBeansMinThreshold","50"
"Localized Strings","BetBeansNotEnough","You don't have enough beans!" "Localized Strings","BetBeansNotEnough","You don't have enough beans!"
"Localized Strings","BetBeansNotValid","That's not a valid bet!" "Localized Strings","BetBeansNotValid","That's not a valid bet!"
"Localized Strings","BetBeansWin","You won %s beans!" "Localized Strings","BetBeansWin","You won %s beans!"
"Localized Strings","BetHistoryInfo","Gives how many beans I've ~~stolen~~ won from your bets!" "Localized Strings","BetHistoryInfo","Gives how many beans I've ~~stolen~~ won from your bets!"
"Localized Strings","BetHistoryOptionalPNGPath","" "Localized Strings","BetHistoryOutput","I have %s treats from betting!"
"Localized Strings","BetHistoryOutput","I have %s beans from betting!"
"Localized Strings","BlurryInfo","Blurs your icon or the icon of a friend you mentioned" "Localized Strings","BlurryInfo","Blurs your icon or the icon of a friend you mentioned"
"Localized Strings","BoopInfo","Kitty will react with a counter" "Localized Strings","BoopInfo","Kitty will react with a counter"
"Localized Strings","BoopMultiple","%s booped several others - %s!" "Localized Strings","BoopMultiple","%s booped several others - %s!"
@@ -117,10 +110,9 @@
"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","DewInfo","A fun little dev experiment!"
"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."
@@ -151,7 +143,6 @@
"Localized Strings","FetchInfo","Throw a custom emote and I'll try to bring it back.... maybe" "Localized Strings","FetchInfo","Throw a custom emote and I'll try to bring it back.... maybe"
"Localized Strings","FetchRunAway","*Runs away and doesn't return for a long time*" "Localized Strings","FetchRunAway","*Runs away and doesn't return for a long time*"
"Localized Strings","FetchStare","*Stares at %s*" "Localized Strings","FetchStare","*Stares at %s*"
"Localized Strings","GetSauceInfo",""
"Localized Strings","GiveBeansInfo","Gives beans to the mentioned users!" "Localized Strings","GiveBeansInfo","Gives beans to the mentioned users!"
"Localized Strings","GiveBeansInvalid","That's not a valid number!" "Localized Strings","GiveBeansInvalid","That's not a valid number!"
"Localized Strings","GiveBeansNoneMentioned","You didn't mention anyone!" "Localized Strings","GiveBeansNoneMentioned","You didn't mention anyone!"
@@ -191,11 +182,7 @@
"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","MusicVolOOB",""
"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!"
@@ -251,13 +238,13 @@
"Localized Strings","TeeyInfo","Teey yourself back into existance, or teey a friend with @!" "Localized Strings","TeeyInfo","Teey yourself back into existance, or teey a friend with @!"
"Localized Strings","TradeBeansInfo","Give your friends some of your beans! Just don't forget to @ them!" "Localized Strings","TradeBeansInfo","Give your friends some of your beans! Just don't forget to @ them!"
"Localized Strings","TradeBeansIntParseError","That's not a real number! D:" "Localized Strings","TradeBeansIntParseError","That's not a real number! D:"
"Localized Strings","TradeBeansMultipleUsersTagged",""
"Localized Strings","TradeBeansNoTargetError","Don't forget to tag who you want to give the beans to!" "Localized Strings","TradeBeansNoTargetError","Don't forget to tag who you want to give the beans to!"
"Localized Strings","TradeBeansNotEnoughError","You can't give more beans than you have!" "Localized Strings","TradeBeansNotEnoughError","You can't give more beans than you have!"
"Localized Strings","TradeBeansStealingBeans","Hey %s! Stealing is wrong! Let's see how you like it! *steals 10 beans*" "Localized Strings","TradeBeansStealingBeans","Hey %s! Stealing is wrong! Let's see how you like it! *steals 10 beans*"
"Localized Strings","TradeBeansSuccess","%s gave %s %s beans!" "Localized Strings","TradeBeansSuccess","%s gave %s %s beans!"
"Localized Strings","TweetError","Tweet command failed!" "Localized Strings","TweetError","Tweet command failed!"
"Localized Strings","TweetInfo","Kitty will tweet to her personal twitter account" "Localized Strings","TweetInfo","Kitty will tweet to her personal twitter account"
"Localized Strings","WehInfo","Weh"
"Localized Strings","WolframError","Something went wrong!" "Localized Strings","WolframError","Something went wrong!"
"Localized Strings","WolframInfo","Will query wolframalpha with your question and give a full image output of the answer" "Localized Strings","WolframInfo","Will query wolframalpha with your question and give a full image output of the answer"
"Localized Strings","WolframNoArgs","You need to provide some arguments!" "Localized Strings","WolframNoArgs","You need to provide some arguments!"
@@ -285,12 +272,10 @@
"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","dew","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"
"Command Enabler","getsauce","1"
"Command Enabler","givebeans","1" "Command Enabler","givebeans","1"
"Command Enabler","guildroleadd","1" "Command Enabler","guildroleadd","1"
"Command Enabler","guildroleallowed","1" "Command Enabler","guildroleallowed","1"
@@ -329,9 +314,9 @@
"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, trade","1"
"Command Enabler","tweet","1" "Command Enabler","tweet","1"
"Command Enabler","vote","1" "Command Enabler","vote","1"
"Command Enabler","weh","1"
"Command Enabler","wolfram","1" "Command Enabler","wolfram","1"
"Command Enabler","work","1" "Command Enabler","work","1"
"Command Enabler","yeet","1" "Command Enabler","yeet","1"
1 Type Key Value
Globals mode (dev or release) dev
Globals activity with a laser pointer
2 Localized Commands beans
3 Localized Commands benchmark, bench
4 Localized Commands bet
16 Localized Commands dbstats
17 Localized Commands defaultdance
18 Localized Commands derp
19 Localized Commands derpi dew
Localized Commands e6
20 Localized Commands e621
21 Localized Commands eightball, 8ball
22 Localized Commands fetch
Localized Commands getsauce
23 Localized Commands givebeans
24 Localized Commands help
25 Localized Commands indicator
47 Localized Commands stats
48 Localized Commands teey
49 Localized Commands tony, stark, dontfeelgood, dontfeelsogood tony, stark, dontfeelgood, dontfeelsogood, snap
Localized Commands tradebeans, trade
50 Localized Commands tweet
51 Localized Commands vote
52 Localized Commands weh
53 Localized Commands wolfram
54 Localized Commands work
55 Localized Commands yeet
56 Localized Strings AddGuildRoleFailure Failed to add %s to %s
Localized Strings BeansImageBottomText BEANS
Localized Strings BeansImageTopText YOU HAVE
57 Localized Strings BeansShowDisplay You have %s beans!
58 Localized Strings BeansShowInfo Displays how many beans you have
59 Localized Strings BeansShowMentioned I took a look and %sbeans!
62 Localized Strings BetBeansInfo Allows you to bet your beans, set your amount after the command! Warning! House always wins!nSets of 3 will get 2x, 4 will get 10x, and 5 will get 1000x
63 Localized Strings BetBeansLose Sorry, you didn't win, try again!
64 Localized Strings BetBeansLowBet Please bet with at least 20 beans!
65 Localized Strings BetBeansMinThreshold 50
66 Localized Strings BetBeansNotEnough You don't have enough beans!
67 Localized Strings BetBeansNotValid That's not a valid bet!
68 Localized Strings BetBeansWin You won %s beans!
69 Localized Strings BetHistoryInfo Gives how many beans I've ~~stolen~~ won from your bets!
70 Localized Strings BetHistoryOptionalPNGPath BetHistoryOutput I have %s treats from betting!
Localized Strings BetHistoryOutput I have %s beans from betting!
71 Localized Strings BlurryInfo Blurs your icon or the icon of a friend you mentioned
72 Localized Strings BoopInfo Kitty will react with a counter
73 Localized Strings BoopMultiple %s booped several others - %s!
110 Localized Strings DBFlushInfo Takes all objects queued for the database and writes them to the database, then says how many were written.
111 Localized Strings DBStatsInfo Shows current statistics for the database
112 Localized Strings DefaultDanceInfo y'all know forknife, get ready to dance, or make a friend dance with @!
113 Localized Strings DerpiError DewInfo A fun little dev experiment!
114 Localized Strings DoWorkFinished I finished with my work! :D
115 Localized Strings DoWorkInfo Occupies a core for a few seconds
Localized Strings E6Blacklisted I can't show that image ;3; (it may be blacklisted)
116 Localized Strings EightBallError Hmm? You'll need to ask a question!
117 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.
118 Localized Strings EightBallMaybe1 Reply hazy, try again.
143 Localized Strings FetchInfo Throw a custom emote and I'll try to bring it back.... maybe
144 Localized Strings FetchRunAway *Runs away and doesn't return for a long time*
145 Localized Strings FetchStare *Stares at %s*
Localized Strings GetSauceInfo
146 Localized Strings GiveBeansInfo Gives beans to the mentioned users!
147 Localized Strings GiveBeansInvalid That's not a valid number!
148 Localized Strings GiveBeansNoneMentioned You didn't mention anyone!
182 Localized Strings MapVersion Using mapgen v0.1
183 Localized Strings MapWidth
184 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
185 Localized Strings MusicInfo
Localized Strings MusicVolChanged Volume set to %s!
Localized Strings MusicVolCurrent Volume is at %s!
Localized Strings MusicVolOOB
186 Localized Strings PerishInfo Adds a red, 'a n g e r y' overlay to your icon or the icon of a friend you mentioned
187 Localized Strings PingInfo Will respond with Pong!
188 Localized Strings PingResponse Pong!
238 Localized Strings TeeyInfo Teey yourself back into existance, or teey a friend with @!
239 Localized Strings TradeBeansInfo Give your friends some of your beans! Just don't forget to @ them!
240 Localized Strings TradeBeansIntParseError That's not a real number! D:
Localized Strings TradeBeansMultipleUsersTagged
241 Localized Strings TradeBeansNoTargetError Don't forget to tag who you want to give the beans to!
242 Localized Strings TradeBeansNotEnoughError You can't give more beans than you have!
243 Localized Strings TradeBeansStealingBeans Hey %s! Stealing is wrong! Let's see how you like it! *steals 10 beans*
244 Localized Strings TradeBeansSuccess %s gave %s %s beans!
245 Localized Strings TweetError Tweet command failed!
246 Localized Strings TweetInfo Kitty will tweet to her personal twitter account
247 Localized Strings WehInfo Weh
248 Localized Strings WolframError Something went wrong!
249 Localized Strings WolframInfo Will query wolframalpha with your question and give a full image output of the answer
250 Localized Strings WolframNoArgs You need to provide some arguments!
272 Command Enabler dbstats 1
273 Command Enabler defaultdance 1
274 Command Enabler derp 1
275 Command Enabler derpi dew 1
Command Enabler e6 1
276 Command Enabler e621 1
277 Command Enabler eightball, 8ball 1
278 Command Enabler fetch 1
Command Enabler getsauce 1
279 Command Enabler givebeans 1
280 Command Enabler guildroleadd 1
281 Command Enabler guildroleallowed 1
314 Command Enabler stats 1
315 Command Enabler teey 1
316 Command Enabler tony, stark, dontfeelgood, dontfeelsogood 1
Command Enabler tradebeans, trade 1
317 Command Enabler tweet 1
318 Command Enabler vote 1
319 Command Enabler weh 1
320 Command Enabler wolfram 1
321 Command Enabler work 1
322 Command Enabler yeet 1
Binary file not shown.
-22
View File
@@ -1,22 +0,0 @@
function plugin(message, user)
local index;
local concat;
if(string.find(message, "https://derpicdn.net/img"))then
if(string.find(message, "view/"))then
index = string.find(message, "/[^/]*$");
return "!derpi ID:" .. string.sub(message, index + 1, string.find(message, ".[^.]*$")-1);
else
if(string.find(message, "download/"))then
index = string.find(message, "_");
concat = string.sub(message, 0, index-1);
return "!derpi ID:" .. string.sub(concat, string.find(message, "/[^/]*$") + 1);
else
index = string.find(message, "/[^/]*$");
concat = string.sub(message, 0, index - 1);
index = string.find(concat, "/[^/]*$");
return "!derpi ID:" .. string.sub(concat, index + 1);
end
end
end
end
-8
View File
@@ -1,8 +0,0 @@
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, " "))then
message = string.sub(message, 0, string.find(message, " "));
end
return "!e6 md5:" .. string.sub(message, string.find(message, "/[^/]*$") + 1 ,string.find(message, ".[^.]*$") - 1);
end
end
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-138
View File
@@ -1,138 +0,0 @@
package commands.beans;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import core.Command;
import core.Constants;
import core.LocStrings;
import dataStructures.KittyChannel;
import dataStructures.KittyGuild;
import dataStructures.KittyRating;
import dataStructures.KittyRole;
import dataStructures.KittyUser;
import dataStructures.Response;
import dataStructures.UserInput;
public class CommandBeansShow extends Command
{
public CommandBeansShow(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
public String getHelpText() { return LocStrings.stub("BeansShowInfo"); };
@Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
if(input.mentions == null)
{
//res.send("" + user.getBeans());
try {
res.sendFile(combineImages(user.getBeans()), "png");
} catch (IOException e) {
e.printStackTrace();
}
// res.send(String.format(LocStrings.stub("BeansShowDisplay"), user.getBeans()));
}
else
{
String mentionedBeans = "";
for(KittyUser mentioned:input.mentions)
{
mentionedBeans += mentioned.name + " has " + mentioned.getBeans() + " ";
}
res.send(String.format(LocStrings.stub("BeansShowMentioned"), mentionedBeans));
}
}
private File combineImages(long beans) throws IOException
{
// Acquire images
BufferedImage imageBase = ImageIO.read(new File(Constants.AssetDirectory + "beans/BeansBG.png"));
BufferedImage thouBean = ImageIO.read(new File(Constants.AssetDirectory + "beans/thouBean.png"));
BufferedImage hunBean = ImageIO.read(new File(Constants.AssetDirectory + "beans/hunBean.png"));
BufferedImage tenBean = ImageIO.read(new File(Constants.AssetDirectory + "beans/tenBean.png"));
BufferedImage oneBean = ImageIO.read(new File(Constants.AssetDirectory + "beans/oneBean.png"));
final int baseWidth = imageBase.getWidth();
final int baseHeight = imageBase.getHeight();
long calcBean = beans;
long thousands = beans / 1000;
calcBean = beans % 1000;
long hundreds = (calcBean / 100);
calcBean = calcBean % 100;
long tens = (calcBean / 10);
calcBean = calcBean % 10;
long ones = calcBean;
BufferedImage beanImage = new BufferedImage(baseWidth, baseHeight, BufferedImage.TYPE_INT_ARGB);
Graphics beanGraphics = beanImage.getGraphics();
Rectangle rect = new Rectangle(0, 0, baseWidth, baseHeight);
beanGraphics.drawImage(imageBase,0,0,null);
for(int i = 0; i < ones; i++)
{
int x = (int)(Math.random() * (baseWidth - oneBean.getWidth())) + 1;
int y = (int)(Math.random() * (baseHeight - oneBean.getHeight())) + 1;
beanGraphics.drawImage(oneBean, x, y, null);
}
for(int i = 0; i < tens; i++)
{
int x = (int)(Math.random() * (baseWidth - tenBean.getWidth())) + 1;
int y = (int)(Math.random() * (baseHeight - tenBean.getHeight())) + 1;
beanGraphics.drawImage(tenBean, x, y, null);
}
for(int i = 0; i < hundreds; i++)
{
int x = (int)(Math.random() * (baseWidth - hunBean.getWidth())) + 1;
int y = (int)(Math.random() * (baseHeight - hunBean.getHeight())) + 1;
beanGraphics.drawImage(hunBean, x, y, null);
}
for(int i = 0; i < thousands; i++)
{
int x = (int)(Math.random() * (baseWidth - thouBean.getWidth())) + 1;
int y = (int)(Math.random() * (baseHeight - thouBean.getHeight())) + 1;
beanGraphics.drawImage(thouBean, x, y, null);
}
try {
@SuppressWarnings("unused")
Font font = null;
font = Font.createFont(Font.TRUETYPE_FONT, new File(Constants.AssetDirectory +"fonts/B612Mono-Regular.ttf"));
} catch (Exception e)
{
}
Font beanFont = new Font("font", Font.BOLD, 45);
beanGraphics.setFont(beanFont);
drawCenteredString(beanGraphics, LocStrings.stub("BeansImageTopText"), rect, beanFont, .25);
drawCenteredString(beanGraphics, "" + beans, rect, beanFont, .5);
drawCenteredString(beanGraphics, LocStrings.stub("BeansImageBottomText"), rect, beanFont, .75);
ImageIO.write(beanImage, "PNG", new File("beanImage.png"));
return new File("beanImage.png");
}
private void drawCenteredString(Graphics beanGraphics, String text, Rectangle rect, Font font, double segment)
{
FontMetrics metrics = beanGraphics.getFontMetrics(font);
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
int y = (int)(rect.y + ((rect.height - metrics.getHeight()) * segment) + metrics.getAscent());
beanGraphics.drawString(text, x, y);
}
}
@@ -2,11 +2,11 @@ package commands.benchmark;
import java.util.List; import java.util.List;
import core.benchmark.BenchmarkCommand; import commands.benchmark.core.BenchmarkCommand;
import core.benchmark.BenchmarkEntry; import commands.benchmark.core.BenchmarkEntry;
import core.benchmark.BenchmarkFormattable; import commands.benchmark.core.BenchmarkFormattable;
import core.benchmark.BenchmarkInput; import commands.benchmark.core.BenchmarkInput;
import core.benchmark.BenchmarkManager; import commands.benchmark.core.BenchmarkManager;
public class BenchmarkCommandCompare extends BenchmarkCommand public class BenchmarkCommandCompare extends BenchmarkCommand
{ {
@@ -2,7 +2,11 @@ package commands.benchmark;
import java.util.List; import java.util.List;
import core.benchmark.*; import commands.benchmark.core.BenchmarkCommand;
import commands.benchmark.core.BenchmarkEntry;
import commands.benchmark.core.BenchmarkFormattable;
import commands.benchmark.core.BenchmarkInput;
import commands.benchmark.core.BenchmarkManager;
public class BenchmarkCommandFind extends BenchmarkCommand public class BenchmarkCommandFind extends BenchmarkCommand
{ {
@@ -2,11 +2,11 @@ package commands.benchmark;
import java.util.List; import java.util.List;
import core.benchmark.BenchmarkCommand; import commands.benchmark.core.BenchmarkCommand;
import core.benchmark.BenchmarkEntry; import commands.benchmark.core.BenchmarkEntry;
import core.benchmark.BenchmarkFormattable; import commands.benchmark.core.BenchmarkFormattable;
import core.benchmark.BenchmarkInput; import commands.benchmark.core.BenchmarkInput;
import core.benchmark.BenchmarkManager; import commands.benchmark.core.BenchmarkManager;
import dataStructures.KittyEmbed; import dataStructures.KittyEmbed;
import java.awt.Color; import java.awt.Color;
@@ -1,9 +1,9 @@
package commands.general; package commands.benchmark;
import commands.benchmark.core.BenchmarkFormattable;
import commands.benchmark.core.BenchmarkFramework;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import core.benchmark.BenchmarkFormattable;
import core.benchmark.BenchmarkFramework;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
import dataStructures.KittyGuild; import dataStructures.KittyGuild;
import dataStructures.KittyRating; import dataStructures.KittyRating;
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
public abstract class BenchmarkCommand public abstract class BenchmarkCommand
{ {
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
public class BenchmarkEntry public class BenchmarkEntry
{ {
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
import dataStructures.KittyEmbed; import dataStructures.KittyEmbed;
import dataStructures.Response; import dataStructures.Response;
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
import java.util.HashMap; import java.util.HashMap;
import commands.benchmark.*; import commands.benchmark.*;
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
import utils.StringUtils; import utils.StringUtils;
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
import utils.GlobalLog; import utils.GlobalLog;
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
@@ -1,4 +1,4 @@
package core.benchmark; package commands.benchmark.core;
public enum BenchmarkType public enum BenchmarkType
{ {
+43
View File
@@ -0,0 +1,43 @@
package commands.dew;
import commands.dew.core.impl.DewCore;
import core.Command;
import core.LocStrings;
import core.SubCommandFramework;
import dataStructures.KittyChannel;
import dataStructures.KittyGuild;
import dataStructures.KittyRating;
import dataStructures.KittyRole;
import dataStructures.KittyUser;
import dataStructures.Response;
import dataStructures.UserInput;
public class CommandDew extends Command
{
public static DewCore core;
SubCommandFramework framework = new SubCommandFramework();
@Override
public String getHelpText() { return LocStrings.stub("DewInfo"); }
@Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
framework.run(guild, channel, user, input).Call(res);
}
public CommandDew(KittyRole level, KittyRating rating)
{
super(level, rating);
core = new DewCore(framework);
framework.addCommand("luatest", new CommandDewLuaTest(KittyRole.Dev, KittyRating.Safe));
framework.addCommand("realm", new CommandDewRealm(KittyRole.Dev, KittyRating.Safe));
framework.addCommand("w", new CommandDewInput("w", KittyRole.Dev, KittyRating.Safe));
framework.addCommand("a", new CommandDewInput("a", KittyRole.Dev, KittyRating.Safe));
framework.addCommand("s", new CommandDewInput("s", KittyRole.Dev, KittyRating.Safe));
framework.addCommand("d", new CommandDewInput("d", KittyRole.Dev, KittyRating.Safe));
framework.addCommand("capture", new CommandDewCapture(KittyRole.Dev, KittyRating.Safe));
}
}
+28
View File
@@ -0,0 +1,28 @@
package commands.dew;
import commands.dew.adapter.KittyAdapterDewPlayer;
import commands.dew.core.impl.DewCore;
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 CommandDewCapture extends SubCommand
{
public CommandDewCapture(KittyRole roleLevel, KittyRating contentRating)
{
super(roleLevel, contentRating);
}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
KittyAdapterDewPlayer player = DewCore.getOrCreate(user);
DewCore.playersCaptured.add(player);
return null;//new SubCommandFormattable("captured input for " + user.name);
}
}
+41
View File
@@ -0,0 +1,41 @@
package commands.dew;
import commands.dew.adapter.KittyAdapterDewPlayer;
import commands.dew.core.impl.DewCore;
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 CommandDewInput extends SubCommand
{
String letter = "";
public CommandDewInput(String letter, KittyRole roleLevel, KittyRating contentRating)
{
super(roleLevel, contentRating);
this.letter = letter.toLowerCase();
}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
KittyAdapterDewPlayer player = DewCore.getOrCreate(user);
int x = player.getRealmX();
int y = player.getRealmY();
switch(letter)
{
case "w": player.setRealmPos(x, y - 1); break;
case "a": player.setRealmPos(x - 1, y); break;
case "s": player.setRealmPos(x, y + 1); break;
case "d": player.setRealmPos(x + 1, y); break;
}
return new SubCommandFormattable(DewCore.drawWorld(player));
}
}
+67
View File
@@ -0,0 +1,67 @@
package commands.dew;
import java.util.UUID;
import commands.dew.core.data.*;
import commands.dew.core.impl.DewLuaCore;
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 CommandDewLuaTest extends SubCommand
{
public CommandDewLuaTest(KittyRole roleLevel, KittyRating contentRating)
{
super(roleLevel, contentRating);
}
private String asCodeBlock(String string)
{
return "```lua\n" + string + "```";
}
private String asCodeLine(String string)
{
return "`" + string + "`";
}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
String out = "";
try
{
out += "**Testing writing...\n**";
DewRealm m = new DewRealm();
m.id = UUID.randomUUID().toString();
String out1 = DewLuaCore.toLua(m);
out += asCodeBlock(out1);
String out2 = DewLuaCore.toLua(new DewMovementInfo());
out += asCodeBlock(out2);
out += "**Testing Reading...**\n";
DewRealm map = new DewRealm();
DewLuaCore.fromLua(map, out1);
out += "ID from 1st write: " + asCodeLine(map.id) + "\n";
DewMovementInfo move = new DewMovementInfo();
DewLuaCore.fromLua(move, out2);
out += "Qualified type test: " + asCodeLine(move.toString()) + "\n";
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
return new SubCommandFormattable(out);
}
}
+31
View File
@@ -0,0 +1,31 @@
package commands.dew;
import commands.dew.adapter.KittyAdapterDewPlayer;
import commands.dew.core.impl.DewCore;
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 CommandDewRealm extends SubCommand
{
public CommandDewRealm(KittyRole roleLevel, KittyRating contentRating)
{
super(roleLevel, contentRating);
}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
KittyAdapterDewPlayer player = DewCore.getOrCreate(user);
String out = DewCore.drawWorld(player);
return new SubCommandFormattable(out);
}
}
@@ -0,0 +1,71 @@
package commands.dew.adapter;
import commands.dew.core.api.IDewPlayer;
import commands.dew.core.data.DewRealm;
import dataStructures.KittyUser;
public class KittyAdapterDewPlayer implements IDewPlayer
{
private KittyUser user;
private String realmID;
private int x;
private int y;
public KittyAdapterDewPlayer(DewRealm realm, KittyUser user, int x, int y)
{
this.user = user;
this.realmID = realm.id;
this.x = x;
this.y = y;
}
public String getVisual()
{
return user.name.length() >= 1 ? user.name.substring(0, 1) : "@";
}
public boolean isUser(KittyUser user)
{
return user.uniqueID == user.uniqueID;
}
public void setRealmPos(int x, int y)
{
this.x = x;
this.y = y;
}
////////////////////////////
// Interface requirements //
////////////////////////////
@Override
public String getName()
{
return user.name;
}
@Override
public String getUniqueID()
{
return user.uniqueID;
}
@Override
public String getCurrentRealmID()
{
return realmID;
}
@Override
public int getRealmX()
{
return x;
}
@Override
public int getRealmY()
{
return y;
}
}
+5
View File
@@ -0,0 +1,5 @@
package commands.dew.core.api;
public interface IDewCore {
}
@@ -0,0 +1,6 @@
package commands.dew.core.api;
public interface IDewEntity
{
public String getUniqueID();
}
@@ -0,0 +1,6 @@
package commands.dew.core.api;
public interface IDewLuaCore
{
}
@@ -0,0 +1,6 @@
package commands.dew.core.api;
public interface IDewLuaSerializable<T>
{
// Type info for derived class encoded in T
}
@@ -0,0 +1,19 @@
package commands.dew.core.api;
// Commands are standalone pieces of data that contain only structures.
// Each command is simplistic and represents an action in the game world.
// Format:
/*
return
{
name="SomeCommand",
data={
-- some object here --
}
}
*/
public interface IDewMessage<T>
{
public String getMessageName();
public T getData();
}
@@ -0,0 +1,9 @@
package commands.dew.core.api;
public interface IDewPlayer extends IDewEntity
{
public String getName();
public String getCurrentRealmID();
public int getRealmX();
public int getRealmY();
}
@@ -0,0 +1,18 @@
package commands.dew.core.data;
public enum DewMapTile
{
// Assign multiples of 2 for flag purposes
Default(0), Grass(1), Tree(2);
private final int value;
private DewMapTile(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
}
@@ -0,0 +1,11 @@
package commands.dew.core.data;
import commands.dew.core.api.IDewLuaSerializable;
// Treat all data objects as structs for the purposes of this.
public class DewMovementInfo implements IDewLuaSerializable<DewMovementInfo>
{
public String entityID;
public int x;
public int y;
}
+9
View File
@@ -0,0 +1,9 @@
package commands.dew.core.data;
import commands.dew.core.api.IDewLuaSerializable;
public final class DewRealm implements IDewLuaSerializable<DewRealm>
{
public String id = "0";
public int[][] map = new int[12][24]; // [Rows][Columns]
}
+174
View File
@@ -0,0 +1,174 @@
package commands.dew.core.impl;
import java.util.ArrayList;
import java.util.List;
import commands.dew.adapter.KittyAdapterDewPlayer;
import commands.dew.core.data.DewMapTile;
import commands.dew.core.data.DewRealm;
import core.SubCommandFormattable;
import core.SubCommandFramework;
import dataStructures.KittyChannel;
import dataStructures.KittyGuild;
import dataStructures.KittyUser;
import dataStructures.Response;
import dataStructures.UserInput;
import utils.GlobalLog;
import utils.LogFilter;
public class DewCore
{
// TODO: Make realm and players both per-realm
public static String responseHeader = "[Dewdrop Forest]";
public static DewRealm realm;
public static List<KittyAdapterDewPlayer> players;
public static List<KittyAdapterDewPlayer> playersCaptured;
private static SubCommandFramework framework;
public DewCore(SubCommandFramework framework)
{
DewCore.framework = framework;
DewCore.realm = new DewRealm();
DewCore.players = new ArrayList<KittyAdapterDewPlayer>();
DewCore.playersCaptured = new ArrayList<KittyAdapterDewPlayer>();
for(int y = 0; y < realm.map.length; ++y)
{
for(int x = 0; x < realm.map[y].length; ++x)
{
realm.map[y][x] = DewMapTile.Grass.getValue();
}
}
}
// Returns false if not captured, true if captured.
public static boolean ProcessIfCaptured(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput baseInput, Response res)
{
// Search for a captured player.
KittyAdapterDewPlayer player = null;
for(KittyAdapterDewPlayer p : playersCaptured)
{
if(p.getUniqueID() == user.uniqueID)
{
player = p;
break;
}
}
// If we didn't find that the person is captured, return false since we don't need to do anything.
if(player == null)
return false;
// See if we run anything - also, check to see if we need to exit.
boolean didRun = false;
try
{
UserInput toEdit = new UserInput(baseInput);
String key = toEdit.message.toLowerCase().trim();
toEdit.key = key;
toEdit.args = key;
switch(key)
{
case "cap":
case "capture":
case "uncapture":
case "stop":
case "quit":
case "exit":
playersCaptured.remove(player);
return false;
}
SubCommandFormattable f = framework.run(guild, channel, user, toEdit);
if(f != null)
{
Response.GetLastMessage((String last) -> {
if(last.contains(responseHeader))
Response.EditLastMessage(f.resString);
});
didRun = true;
}
}
catch(Exception e)
{
GlobalLog.error(LogFilter.Command, e);
}
if(didRun)
{
baseInput.deleteOriginInput();
}
return didRun;
}
public static KittyAdapterDewPlayer getOrCreate(KittyUser user)
{
for(KittyAdapterDewPlayer player : players)
{
if(player.getUniqueID() == user.uniqueID)
{
return player;
}
}
KittyAdapterDewPlayer player = new KittyAdapterDewPlayer(realm, user, 10, 10);
players.add(player);
return player;
}
public static String drawWorld(KittyAdapterDewPlayer player)
{
// Build empty world buffer
String[][] worldBuffer = new String[realm.map.length][realm.map[0].length];
// Build world
for(int y = 0; y < realm.map.length; ++y)
{
for(int x = 0; x < realm.map[y].length; ++x)
{
switch(DewMapTile.values()[realm.map[y][x]])
{
case Grass:
worldBuffer[y][x] = ",";
break;
default:
worldBuffer[y][x] = " ";
break;
}
}
}
// Build players
for(KittyAdapterDewPlayer p : players)
{
worldBuffer[p.getRealmY()][p.getRealmX()] = p.getVisual();
}
// Draw world
String out = "";
out += responseHeader + "\n";
out += "**Realm ID - ** `" + realm.id + "`\n";
for(int y = 0; y < worldBuffer.length; ++y)
{
out += "`";
for(int x = 0; x < worldBuffer[y].length; ++x)
{
out += worldBuffer[y][x];
}
out += "`";
out += "\n";
}
out += "**Stats**\n";
out += "`Player Name` - `" + player.getName() + "`\n";
out += "`Player Icon` - `" + player.getVisual() + "`\n";
return out;
}
}
+153
View File
@@ -0,0 +1,153 @@
package commands.dew.core.impl;
import java.lang.reflect.Field;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.jse.JsePlatform;
import commands.dew.core.api.IDewLuaCore;
import commands.dew.core.api.IDewLuaSerializable;
public class DewLuaCore implements IDewLuaCore
{
private static Globals globalLuaCore = null;
public static String toLua(IDewLuaSerializable<?> item)
{
return toLua(item, 0);
}
private static String tab(int num)
{
String line = "";
for(int i = 0; i < num; ++i)
line += "\t";
return line;
}
public static String toLua(IDewLuaSerializable<?> item, int tabs)
{
String out = tab(tabs) + "return {\n";
// Set up type information
out += tab(tabs + 1) + "type=\"" + item.getClass().getTypeName() + "\",\n";
// Set up data information
out += tab(tabs + 1) + "data={\n";
// Write data
Field[] fields = item.getClass().getDeclaredFields();
for(int i = 0; i < fields.length; ++i)
{
Field current = fields[i];
try
{
String line = "";
String fieldType = current.getType().toString().toLowerCase();
line += tab(tabs + 2);
line += current.getName() + "=";
switch(fieldType)
{
case "int":
line += "" + current.get(item);
break;
case "class java.lang.string":
String content = (String)current.get(item);
if(content == null || content.length() == 0)
line += "\"\"";
else
line += "\"" + content + "\"";
break;
// wrong name
case "dewmaptile ":
line += "\"" + current.get(item).toString() + "\"";
break;
default:
line += "nil";
System.err.print("Type could not be foramtted as lua: " + fieldType + "\n");
break;
}
// If we're not the last line, add a comma.
if(i != fields.length - 1)
line += ",";
out += line + "\n";
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
out += tab(tabs + 1) + "}\n";
out += tab(tabs)+ "}\n";
return out;
}
@SuppressWarnings({ "unchecked" })
public static <T> void fromLua(T obj, String lua)
{
if(globalLuaCore == null)
{
globalLuaCore = JsePlatform.standardGlobals();
}
LuaValue luaResult = globalLuaCore.load(lua).call();
String type = luaResult.get("type").toString();
try
{
LuaValue data = luaResult.get("data");
Class<T> concreteClass = (Class<T>) Class.forName(type);
for(Field field : concreteClass.getDeclaredFields())
{
String name = field.getName();
LuaValue value = data.get(name);
if(!value.isnil())
{
String fieldType = field.getType().toString().toLowerCase();
switch(fieldType)
{
case "int":
field.set(obj, value.toint());
break;
case "class java.lang.string":
field.set(obj, value.toString());
break;
// Not the right name
case "dewmaptile":
default:
System.err.print("Could not set field of type: " + fieldType + "\n");
break;
}
}
else
{
System.err.println("Field was not in lua: " + name);
}
}
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}
@@ -0,0 +1,8 @@
package commands.dew.core.messages;
import commands.dew.core.api.IDewLuaSerializable;
public class DewMessageMovement implements IDewLuaSerializable<DewMessageMovement>
{
}
@@ -0,0 +1,29 @@
package commands.general;
import core.Command;
import core.LocStrings;
import dataStructures.*;
public class CommandBeansShow extends Command
{
public CommandBeansShow(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
public String getHelpText() { return LocStrings.stub("BeansShowInfo"); };
@Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
if(input.mentions == null)
res.send(String.format(LocStrings.stub("BeansShowDisplay"), user.getBeans()));
else
{
String mentionedBeans = "";
for(KittyUser mentioned:input.mentions)
{
mentionedBeans += mentioned.name + " has " + mentioned.getBeans() + " ";
}
res.send(String.format(LocStrings.stub("BeansShowMentioned"), mentionedBeans));
}
}
}
@@ -1,4 +1,4 @@
package commands.beans; package commands.general;
import java.util.Random; import java.util.Random;
@@ -20,7 +20,7 @@ public class CommandBetBeans extends Command
{ {
String call = ""; String call = "";
int min = 20; int min = 50;
int bet = 0; int bet = 0;
int win = 0; int win = 0;
@@ -36,8 +36,7 @@ public class CommandBetBeans extends Command
} }
catch (Exception e) catch (Exception e)
{ {
GlobalLog.log(LogFilter.Command, "Betting took place, but a value was not specified in the config file " GlobalLog.log(LogFilter.Command, "Betting took place, but a value was not specified in the config file so 50 was used as the minimum bet threshold. Consider specifying BetBeansMinThreshold.");
+ "so 50 was used as the minimum bet threshold. Consider specifying BetBeansMinThreshold.");
} }
try try
@@ -1,45 +1,25 @@
package commands.beans; package commands.general;
import java.io.File; import core.Command;
import core.LocStrings;
import core.Command; import dataStructures.KittyChannel;
import core.LocStrings; import dataStructures.KittyGuild;
import dataStructures.KittyChannel; import dataStructures.KittyRating;
import dataStructures.KittyGuild; import dataStructures.KittyRole;
import dataStructures.KittyRating; import dataStructures.KittyUser;
import dataStructures.KittyRole; import dataStructures.Response;
import dataStructures.KittyUser; import dataStructures.UserInput;
import dataStructures.Response;
import dataStructures.UserInput; public class CommandBetHistory extends Command
import utils.GlobalLog; {
import utils.LogFilter; public CommandBetHistory(KittyRole level, KittyRating rating) { super(level, rating); }
public class CommandBetHistory extends Command @Override
{ public String getHelpText() { return LocStrings.stub("BetHistoryInfo"); }
public CommandBetHistory(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
@Override public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
public String getHelpText() { return LocStrings.stub("BetHistoryInfo"); } {
res.send(String.format(LocStrings.stub("BetHistoryOutput"), guild.beans.get()));
@Override }
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
// Send primary response
res.send(String.format(LocStrings.stub("BetHistoryOutput"), guild.beans.get()));
// Look up extra information to see if we ahve a flair image
String optional = LocStrings.stub("BetHistoryOptionalPNGPath");
if(optional != null && optional.length() > 0)
{
File responseImage = new File(optional);
if(responseImage.exists())
{
res.sendFile(responseImage, ".png");
}
else
{
GlobalLog.warn(LogFilter.Command, "Optional PNG image for bet history was specified, but the file could not be found.");
}
}
}
} }
@@ -1,4 +1,4 @@
package commands.images; package commands.general;
import java.awt.Color; import java.awt.Color;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
+2 -3
View File
@@ -68,23 +68,22 @@ public class CommandBoop extends Command
{ {
if(input.mentions == null) if(input.mentions == null)
{ {
// No one is booped, just the bot!
boopTracker.applyBoop(); boopTracker.applyBoop();
res.send(String.format(LocStrings.stub("BoopStandard"), user.name, boopTracker.howMany())); res.send(String.format(LocStrings.stub("BoopStandard"), user.name, boopTracker.howMany()));
} }
else else
{ {
// When someone boops one other person
if(input.mentions.length == 1) if(input.mentions.length == 1)
{ {
boopTracker.applyBoop();
res.send(String.format(LocStrings.stub("BoopPerson"), user.name, input.mentions[0].name)); res.send(String.format(LocStrings.stub("BoopPerson"), user.name, input.mentions[0].name));
return; return;
} }
// A number of people have been booped
String booped = ""; String booped = "";
for(int i = 0; i < input.mentions.length; i++) for(int i = 0; i < input.mentions.length; i++)
{ {
boopTracker.applyBoop();
if(i < input.mentions.length-1) if(i < input.mentions.length-1)
booped += input.mentions[i].name + ", "; booped += input.mentions[i].name + ", ";
else else
@@ -1,71 +1,71 @@
package commands.images; package commands.general;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.ImageOverlayBuilder; import utils.ImageOverlayBuilder;
import utils.ImageUtils; import utils.ImageUtils;
public class CommandCatch extends Command public class CommandCatch extends Command
{ {
// Required constructor // Required constructor
public CommandCatch(KittyRole level, KittyRating rating) { super(level, rating); } public CommandCatch(KittyRole level, KittyRating rating) { super(level, rating); }
private static Long num = 0l; private static Long num = 0l;
@Override @Override
public String getHelpText() { return LocStrings.stub("CatchInfo"); } public String getHelpText() { return LocStrings.stub("CatchInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
String name = null; String name = null;
File catchFile = null; File catchFile = null;
File catcheeFile = null; File catcheeFile = null;
synchronized(num) synchronized(num)
{ {
name = "catch_" + num + ".gif"; name = "catch_" + num + ".gif";
++num; ++num;
} }
try try
{ {
KittyUser person = null; KittyUser person = null;
if(input.mentions == null) if(input.mentions == null)
person = user; person = user;
else else
person = input.mentions[0]; person = input.mentions[0];
String catchFilename = ImageUtils.downloadFromURL(person.avatarID, ".png"); String catchFilename = ImageUtils.downloadFromURL(person.avatarID, ".png");
if(catchFilename == null) if(catchFilename == null)
return; return;
catcheeFile = new File(catchFilename); catcheeFile = new File(catchFilename);
ImageOverlayBuilder builder = new ImageOverlayBuilder("assets/catch/frames/", "catch ", 92, 18); ImageOverlayBuilder builder = new ImageOverlayBuilder("assets/catch/frames/", "catch ", 92, 18);
builder.overlay(ImageIO.read(catcheeFile), name); builder.overlay(ImageIO.read(catcheeFile), name);
} }
catch (IOException e) catch (IOException e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
catchFile = new File (name); catchFile = new File (name);
res.sendFile(catchFile, "gif"); res.sendFile(catchFile, "gif");
// Thread cleanup... // Thread cleanup...
ImageUtils.blockingFileDelete(catchFile); ImageUtils.blockingFileDelete(catchFile);
ImageUtils.blockingFileDelete(catcheeFile); ImageUtils.blockingFileDelete(catcheeFile);
} }
} }
+2 -10
View File
@@ -27,20 +27,12 @@ public class CommandChoose extends Command
String [] choices = input.args.split(","); String [] choices = input.args.split(",");
if(choices.length <= 1) if(choices.length == 1)
{ {
res.send(LocStrings.stub("ChooseOne")); res.send(LocStrings.stub("ChooseOne"));
return; return;
} }
for(int i = 0; i < choices.length; i ++)
{
if (choices[i].equals(""))
{
choices[i] = "KittyBot is the best!";
}
}
res.send(String.format(LocStrings.stub("ChooseChoice"), (choices[(int) (Math.random()*choices.length)]).toString())); res.send(String.format(LocStrings.stub("ChooseChoice"), (choices[(int) (Math.random()*choices.length)]).toString()));
} }
} }
@@ -1,4 +1,4 @@
package commands.network; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
+21 -1
View File
@@ -31,8 +31,28 @@ public class CommandColor extends Command
@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(input.args == null || input.args.length() == 0)
{
res.send(LocStrings.stub("ColorNotSearchable"));
return;
}
String toFind = null;
String[] split = input.args.split(" ");
if(split.length >= 1)
toFind = split[0];
// First, try and parse out the color to make sure we can even get it. // First, try and parse out the color to make sure we can even get it.
ColorData colorData = theColorAPI.lookupHex(input.args); ColorData colorData = null;
if(toFind == null)
{
colorData = theColorAPI.lookupHex(input.args.trim());
}
else
{
colorData = theColorAPI.lookupHex(toFind.trim());
}
// Verify the color was even found // Verify the color was even found
if(colorData == null) if(colorData == null)
@@ -1,35 +1,35 @@
package commands.dev; package commands.general;
import core.Command; import core.Command;
import core.Constants; import core.Constants;
import core.DatabaseManager; import core.DatabaseManager;
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;
public class CommandDBFlush extends Command public class CommandDBFlush extends Command
{ {
public CommandDBFlush(KittyRole level, KittyRating rating) { super(level, rating); } public CommandDBFlush(KittyRole level, KittyRating rating) { super(level, rating); }
@Override @Override
public String getHelpText() { return LocStrings.stub("DBFlushInfo"); } public String getHelpText() { return LocStrings.stub("DBFlushInfo"); }
@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)
{ {
int numUpdated = DatabaseManager.instance.upkeep(); int numUpdated = DatabaseManager.instance.upkeep();
KittyEmbed embed = new KittyEmbed(); KittyEmbed embed = new KittyEmbed();
embed.title = "Database queue flushed"; embed.title = "Database queue flushed";
embed.descriptionText = "**Dirty:** " + numUpdated; embed.descriptionText = "**Dirty:** " + numUpdated;
embed.color = Constants.ColorDefault; embed.color = Constants.ColorDefault;
res.send(embed); res.send(embed);
} }
} }
@@ -1,43 +1,43 @@
package commands.dev; package commands.general;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import core.Command; import core.Command;
import core.Constants; import core.Constants;
import core.DatabaseManager; import core.DatabaseManager;
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;
public class CommandDBStats extends Command public class CommandDBStats extends Command
{ {
DateFormat dateFormat; DateFormat dateFormat;
public CommandDBStats(KittyRole level, KittyRating rating) public CommandDBStats(KittyRole level, KittyRating rating)
{ {
super(level, rating); super(level, rating);
dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
} }
@Override @Override
public String getHelpText() { return LocStrings.stub("DBStatsInfo"); } public String getHelpText() { return LocStrings.stub("DBStatsInfo"); }
@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)
{ {
KittyEmbed embed = new KittyEmbed(); KittyEmbed embed = new KittyEmbed();
embed.title = "Database Info"; embed.title = "Database Info";
embed.descriptionText = "**Tracked Items:** " + DatabaseManager.instance.getTrackedObjectsSize(); embed.descriptionText = "**Tracked Items:** " + DatabaseManager.instance.getTrackedObjectsSize();
embed.descriptionText += "\n"; embed.descriptionText += "\n";
embed.descriptionText += "**Last Upkeep:** " + dateFormat.format(DatabaseManager.instance.getLastUpkeep()) + " UTC-7"; embed.descriptionText += "**Last Upkeep:** " + dateFormat.format(DatabaseManager.instance.getLastUpkeep()) + " UTC-7";
embed.color = Constants.ColorDefault; embed.color = Constants.ColorDefault;
res.send(embed); res.send(embed);
} }
} }
@@ -1,71 +1,71 @@
package commands.images; package commands.general;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.ImageOverlayBuilder; import utils.ImageOverlayBuilder;
import utils.ImageUtils; import utils.ImageUtils;
public class CommandDefaultDance extends Command public class CommandDefaultDance extends Command
{ {
// Required constructor // Required constructor
public CommandDefaultDance(KittyRole level, KittyRating rating) { super(level, rating); } public CommandDefaultDance(KittyRole level, KittyRating rating) { super(level, rating); }
private static Long num = 0l; private static Long num = 0l;
@Override @Override
public String getHelpText() { return LocStrings.stub("DefaultDanceInfo"); } public String getHelpText() { return LocStrings.stub("DefaultDanceInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
String name = null; String name = null;
File dancerFile = null; File dancerFile = null;
File danceeFile = null; File danceeFile = null;
synchronized(num) synchronized(num)
{ {
name = "defaultDance_" + num + ".gif"; name = "defaultDance_" + num + ".gif";
++num; ++num;
} }
try try
{ {
KittyUser person = null; KittyUser person = null;
if(input.mentions == null) if(input.mentions == null)
person = user; person = user;
else else
person = input.mentions[0]; person = input.mentions[0];
String yeeteeFilename = ImageUtils.downloadFromURL(person.avatarID, ".png"); String yeeteeFilename = ImageUtils.downloadFromURL(person.avatarID, ".png");
if(yeeteeFilename == null) if(yeeteeFilename == null)
return; return;
danceeFile = new File(yeeteeFilename); danceeFile = new File(yeeteeFilename);
ImageOverlayBuilder builder = new ImageOverlayBuilder("assets/dance/default/", "defaultDance ", 118, 18); ImageOverlayBuilder builder = new ImageOverlayBuilder("assets/dance/default/", "defaultDance ", 118, 18);
builder.overlay(ImageIO.read(danceeFile), name); builder.overlay(ImageIO.read(danceeFile), name);
} }
catch (IOException e) catch (IOException e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
dancerFile = new File (name); dancerFile = new File (name);
res.sendFile(dancerFile, "gif"); res.sendFile(dancerFile, "gif");
// Thread cleanup... // Thread cleanup...
ImageUtils.blockingFileDelete(dancerFile); ImageUtils.blockingFileDelete(dancerFile);
ImageUtils.blockingFileDelete(danceeFile); ImageUtils.blockingFileDelete(danceeFile);
} }
} }
@@ -1,33 +1,33 @@
package commands.dev; package commands.general;
import core.*; import core.*;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
public class CommandDoWork extends Command public class CommandDoWork extends Command
{ {
// Required constructor // Required constructor
public CommandDoWork(KittyRole level, KittyRating rating) { super(level, rating); } public CommandDoWork(KittyRole level, KittyRating rating) { super(level, rating); }
@Override @Override
public String getHelpText() { return LocStrings.stub("DoWorkInfo"); } public String getHelpText() { return LocStrings.stub("DoWorkInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
@SuppressWarnings("unused") @SuppressWarnings("unused")
long thispieceofshit = 0; long thispieceofshit = 0;
for(int i = 0; i < 200000000 + Math.random() * 30; i ++) for(int i = 0; i < 200000000 + Math.random() * 30; i ++)
{ {
thispieceofshit += Math.log((double)i); thispieceofshit += Math.log((double)i);
} }
res.send(LocStrings.stub("DoWorkFinished")); res.send(LocStrings.stub("DoWorkFinished"));
} }
} }
@@ -1,4 +1,4 @@
package commands.beans; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
@@ -1,136 +1,136 @@
package commands.dev; package commands.general;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import core.Stats; import core.Stats;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.GlobalLog; import utils.GlobalLog;
import utils.ImageUtils; import utils.ImageUtils;
public class CommandHelpBuilder extends Command { public class CommandHelpBuilder extends Command {
public CommandHelpBuilder(KittyRole role, KittyRating rating) { public CommandHelpBuilder(KittyRole role, KittyRating rating) {
super(role, rating); super(role, rating);
} }
@Override @Override
public String getHelpText() { return LocStrings.stub("HelpBuilderInfo"); } public String getHelpText() { return LocStrings.stub("HelpBuilderInfo"); }
@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)
{ {
// Holds command groups // Holds command groups
HashMap<KittyRole, ArrayList<Command>> commandsByRole = new HashMap<KittyRole, ArrayList<Command>>(); HashMap<KittyRole, ArrayList<Command>> commandsByRole = new HashMap<KittyRole, ArrayList<Command>>();
// Populate w/ empty array lists // Populate w/ empty array lists
for(int i = 0; i < KittyRole.values().length; ++i) for(int i = 0; i < KittyRole.values().length; ++i)
commandsByRole.put(KittyRole.values()[i], new ArrayList<Command>()); commandsByRole.put(KittyRole.values()[i], new ArrayList<Command>());
// Sort commands out // Sort commands out
ArrayList<Command> commands = Stats.instance.getAllCommands(); ArrayList<Command> commands = Stats.instance.getAllCommands();
for(int i = 0; i < commands.size(); ++i) for(int i = 0; i < commands.size(); ++i)
{ {
Command current = commands.get(i); Command current = commands.get(i);
commandsByRole.get(current.requiredRole()).add(current); commandsByRole.get(current.requiredRole()).add(current);
} }
// Format outstring and send it back for now // Format outstring and send it back for now
String out = ""; String out = "";
out += populateSection(KittyRole.Admin, commandsByRole, true) + "\n"; out += populateSection(KittyRole.Admin, commandsByRole, true) + "\n";
out += populateSection(KittyRole.Mod, commandsByRole, true) + "\n"; out += populateSection(KittyRole.Mod, commandsByRole, true) + "\n";
out += populateSection(KittyRole.General, commandsByRole, false) + "\n"; out += populateSection(KittyRole.General, commandsByRole, false) + "\n";
// Write out file // Write out file
String filename = "buildhelp_out.txt"; String filename = "buildhelp_out.txt";
try { try {
PrintWriter writer = new PrintWriter(filename); PrintWriter writer = new PrintWriter(filename);
writer.println(out); writer.println(out);
writer.flush(); writer.flush();
writer.close(); writer.close();
} }
catch (FileNotFoundException e) catch (FileNotFoundException e)
{ {
GlobalLog.error(e.toString()); GlobalLog.error(e.toString());
return; return;
} }
File file = new File(filename); File file = new File(filename);
res.sendFile(file, "txt"); res.sendFile(file, "txt");
ImageUtils.blockingFileDelete(file); ImageUtils.blockingFileDelete(file);
} }
// Generates the section for a specific role, optionally adding spacing after for another section // Generates the section for a specific role, optionally adding spacing after for another section
private String populateSection(KittyRole role, HashMap<KittyRole, ArrayList<Command>> commandsByRole, boolean delimitSection) private String populateSection(KittyRole role, HashMap<KittyRole, ArrayList<Command>> commandsByRole, boolean delimitSection)
{ {
// Formatting variables // Formatting variables
final String headerStart = "<h2>"; final String headerStart = "<h2>";
final String headerEnd = "</h2>\n"; final String headerEnd = "</h2>\n";
final String sectionStart = "<p>\n"; final String sectionStart = "<p>\n";
final String sectionEnd = "</p>"; final String sectionEnd = "</p>";
final String indent = " "; final String indent = " ";
final String leadStart = "<code>"; final String leadStart = "<code>";
final String leadEnd = "</code>"; final String leadEnd = "</code>";
final String leadFollow = ": "; final String leadFollow = ": ";
final String lineDelimiter = "<br/>\n"; final String lineDelimiter = "<br/>\n";
final String sectionDelimiter = "\n\n"; final String sectionDelimiter = "\n\n";
String accumulated = ""; String accumulated = "";
ArrayList<Command> commands = commandsByRole.get(role); ArrayList<Command> commands = commandsByRole.get(role);
ArrayList<Command> commandsSoFar = new ArrayList<Command>(); ArrayList<Command> commandsSoFar = new ArrayList<Command>();
if(commands.size() > 0) if(commands.size() > 0)
{ {
String roleStr = role.toString(); String roleStr = role.toString();
roleStr = roleStr.substring(0, 1).toUpperCase() + roleStr.toLowerCase().substring(1); roleStr = roleStr.substring(0, 1).toUpperCase() + roleStr.toLowerCase().substring(1);
// Section header // Section header
accumulated += headerStart + roleStr + " commands" + headerEnd; accumulated += headerStart + roleStr + " commands" + headerEnd;
accumulated += sectionStart; accumulated += sectionStart;
// Section content // Section content
for(int i = 0; i < commands.size(); ++i) for(int i = 0; i < commands.size(); ++i)
{ {
accumulated += indent; accumulated += indent;
Command command = commands.get(i); Command command = commands.get(i);
// Skip multiples // Skip multiples
if(commandsSoFar.contains(command)) if(commandsSoFar.contains(command))
continue; continue;
else else
commandsSoFar.add(command); commandsSoFar.add(command);
// Write out all the keys and the help text // Write out all the keys and the help text
ArrayList<String> keys = command.registeredNames(); ArrayList<String> keys = command.registeredNames();
for(int j = 0; j < keys.size(); ++j) for(int j = 0; j < keys.size(); ++j)
{ {
if(j != 0) if(j != 0)
accumulated += ", "; accumulated += ", ";
accumulated += leadStart + keys.get(j) + leadEnd; accumulated += leadStart + keys.get(j) + leadEnd;
} }
accumulated += leadFollow + commands.get(i).getHelpText() + lineDelimiter;; accumulated += leadFollow + commands.get(i).getHelpText() + lineDelimiter;;
} }
accumulated += sectionEnd; accumulated += sectionEnd;
// Add spaces after if needed // Add spaces after if needed
if(delimitSection) if(delimitSection)
accumulated += sectionDelimiter; accumulated += sectionDelimiter;
} }
return accumulated; return accumulated;
} }
} }
@@ -1,4 +1,4 @@
package commands.dev; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
@@ -1,4 +1,4 @@
package commands.network; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
+2 -2
View File
@@ -7,7 +7,7 @@ import core.Command;
import core.Constants; import core.Constants;
import core.DatabaseManager; import core.DatabaseManager;
import core.LocStrings; import core.LocStrings;
import core.ObjectBuilder; import core.ObjectBuilderFactory;
import dataStructures.KittyChannel; import dataStructures.KittyChannel;
import dataStructures.KittyEmbed; import dataStructures.KittyEmbed;
import dataStructures.KittyGuild; import dataStructures.KittyGuild;
@@ -98,7 +98,7 @@ public class CommandLeaderboard extends Command
{ {
// Only now that we've sorted do we do the full construction and caching of users // Only now that we've sorted do we do the full construction and caching of users
Pair<Long, String> userPair = users.get(i); Pair<Long, String> userPair = users.get(i);
KittyUser cachedUser = ObjectBuilder.getKittyUser(guildID, userPair.Second); KittyUser cachedUser = ObjectBuilderFactory.getKittyUser(guildID, userPair.Second);
if(cachedUser == null) if(cachedUser == null)
continue; continue;
@@ -1,105 +1,105 @@
package commands.images; package commands.general;
import java.awt.Color; import java.awt.Color;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.ImageUtils; import utils.ImageUtils;
public class CommandPerish extends Command public class CommandPerish extends Command
{ {
public CommandPerish(KittyRole level, KittyRating rating) { super(level, rating); } public CommandPerish(KittyRole level, KittyRating rating) { super(level, rating); }
@Override @Override
public String getHelpText() { return LocStrings.stub("PerishInfo"); }; public String getHelpText() { return LocStrings.stub("PerishInfo"); };
private static Long num = 0l; private static Long num = 0l;
@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)
{ {
String name = null; String name = null;
String filename = null; String filename = null;
File preProcessed = null; File preProcessed = null;
File postProcessed = null; File postProcessed = null;
synchronized(num) synchronized(num)
{ {
name = "perish_" + num + ".png"; name = "perish_" + num + ".png";
++num; ++num;
} }
try try
{ {
try try
{ {
filename = ImageUtils.downloadFromURL(input.args.split(" ")[0], ".png"); filename = ImageUtils.downloadFromURL(input.args.split(" ")[0], ".png");
preProcessed = new File(filename); preProcessed = new File(filename);
} }
catch(Exception e) catch(Exception e)
{ {
KittyUser person = user; KittyUser person = user;
if(input.mentions != null) if(input.mentions != null)
person = input.mentions[0]; person = input.mentions[0];
filename = ImageUtils.downloadFromURL(person.avatarID, ".png"); filename = ImageUtils.downloadFromURL(person.avatarID, ".png");
if(filename == null) if(filename == null)
return; return;
} }
preProcessed = new File(filename); preProcessed = new File(filename);
applyTintEffect(ImageIO.read(preProcessed), name); applyTintEffect(ImageIO.read(preProcessed), name);
} }
catch (IOException e) catch (IOException e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
postProcessed = new File(name); postProcessed = new File(name);
res.sendFile(postProcessed, "png"); res.sendFile(postProcessed, "png");
ImageUtils.blockingFileDelete(preProcessed); ImageUtils.blockingFileDelete(preProcessed);
ImageUtils.blockingFileDelete(postProcessed); ImageUtils.blockingFileDelete(postProcessed);
} }
private static void applyTintEffect(BufferedImage image, String name) throws IOException private static void applyTintEffect(BufferedImage image, String name) throws IOException
{ {
// Iterate over each column left to right and touch up each pixel // Iterate over each column left to right and touch up each pixel
for(int x = 0; x < image.getWidth(); ++x) for(int x = 0; x < image.getWidth(); ++x)
{ {
for(int y = 0; y < image.getHeight(); ++y) for(int y = 0; y < image.getHeight(); ++y)
{ {
Color c = new Color(image.getRGB(x, y), true); Color c = new Color(image.getRGB(x, y), true);
int red = c.getRed(); int red = c.getRed();
red += 100; red += 100;
if(red > 255) if(red > 255)
red = 255; red = 255;
int green = c.getGreen(); int green = c.getGreen();
int blue = c.getBlue(); int blue = c.getBlue();
blue += 20; blue += 20;
if(blue > 255) if(blue > 255)
blue = 255; blue = 255;
Color tinted = new Color(red, green, blue, c.getAlpha()); Color tinted = new Color(red, green, blue, c.getAlpha());
image.setRGB(x, y, tinted.getRGB()); image.setRGB(x, y, tinted.getRGB());
} }
} }
File outputfile = new File(name); File outputfile = new File(name);
ImageIO.write(image, "png", outputfile); ImageIO.write(image, "png", outputfile);
} }
} }
+16 -19
View File
@@ -7,6 +7,8 @@ import java.util.Stack;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import dataStructures.*; import dataStructures.*;
import utils.GlobalLog;
import utils.LogFilter;
public class CommandRoll extends Command public class CommandRoll extends Command
{ {
@@ -22,9 +24,7 @@ public class CommandRoll extends Command
{ {
KittyEmbed embed = new KittyEmbed(); KittyEmbed embed = new KittyEmbed();
embed.title = user.name +"'s roll!"; embed.title = user.name +"'s roll!";
System.out.println("HERE");
embed.descriptionText = rollDice(input.args); embed.descriptionText = rollDice(input.args);
System.out.println("THERE");
Random numGen = new Random(user.name.hashCode()); Random numGen = new Random(user.name.hashCode());
float hue = numGen.nextFloat(); float hue = numGen.nextFloat();
float sat = .7f; float sat = .7f;
@@ -34,6 +34,7 @@ public class CommandRoll extends Command
} }
catch(Exception e) catch(Exception e)
{ {
GlobalLog.error(LogFilter.Command, e);
res.send(LocStrings.stub("RollError")); res.send(LocStrings.stub("RollError"));
} }
} }
@@ -43,11 +44,10 @@ public class CommandRoll extends Command
Stack<Integer> values = new Stack<Integer>(); Stack<Integer> values = new Stack<Integer>();
Stack<Character> operators = new Stack<Character>(); Stack<Character> operators = new Stack<Character>();
String steps = ""; String steps = "";
for(int i = 0; i < thing.length(); i ++) for(int i = 0; i < thing.length(); i ++)
{ {
char current = thing.charAt(i); char current = thing.charAt(i);
System.out.println("ROLLING");
switch(current) switch(current)
{ {
case '+': case '+':
@@ -125,11 +125,8 @@ public class CommandRoll extends Command
{ {
steps += "\n" + calculate(values, operators); steps += "\n" + calculate(values, operators);
} }
if(steps != "")
{ return "Roll```" + thing + "```" + "Steps```" + steps + "```" + "Final value ```" + values.pop() +"```";
return "Roll```" + thing + "```" + "Steps```" + steps + "```" + "Final value ```" + values.pop() +"```";
}
return "That's not a roll that's just " + values.pop() +"!";
} }
@@ -176,18 +173,18 @@ public class CommandRoll extends Command
private int[] roll(int first, int second) private int[] roll(int first, int second)
{ {
int roll = 0; int numberOfDice = first;
int dice = first; int diceSideCount = second;
int sides = second; int [] rolls = new int[numberOfDice];
int [] rolls = new int [dice];
if(dice < 1) GlobalLog.log("number: " + numberOfDice + " diceSides: " + diceSideCount);
if(numberOfDice < 1)
return new int[0]; return new int[0];
for(int i = 0; dice > i; i ++)
{ for(int i = 0; i < numberOfDice; i++)
roll = (int)(Math.random() * sides) + 1; rolls[i] = (int)(Math.random() * diceSideCount + 1);
rolls[i] = roll;
}
return rolls; return rolls;
} }
@@ -1,60 +1,60 @@
package commands.dev; package commands.general;
import core.Command; import core.Command;
import core.DatabaseManager; import core.DatabaseManager;
import core.LocStrings; import core.LocStrings;
import core.Stats; import core.Stats;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.GlobalLog; import utils.GlobalLog;
import utils.LogFilter; import utils.LogFilter;
// NOTE(wisp): This is a sort of special command. // NOTE(wisp): This is a sort of special command.
public class CommandShutdown extends Command public class CommandShutdown extends Command
{ {
public CommandShutdown(KittyRole level, KittyRating rating) { super(level, rating); } public CommandShutdown(KittyRole level, KittyRating rating) { super(level, rating); }
@Override @Override
public String getHelpText() { return LocStrings.stub("ShutdownInfo"); } public String getHelpText() { return LocStrings.stub("ShutdownInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
// Flag the shutdown immediately. // Flag the shutdown immediately.
Stats.instance.indicateShutdown(); Stats.instance.indicateShutdown();
boolean isSafe = false; boolean isSafe = false;
switch(input.args.toLowerCase().trim()) switch(input.args.toLowerCase().trim())
{ {
case "s": case "s":
case "safe": case "safe":
case "-s": case "-s":
case "-safe": case "-safe":
case "snafe": case "snafe":
isSafe = true; isSafe = true;
break; break;
} }
if(isSafe) if(isSafe)
{ {
// Force upkeep, this works so long as upkeep is on the main thread. // Force upkeep, this works so long as upkeep is on the main thread.
res.sendImmediate(LocStrings.stub("ShutdownSafe")); res.sendImmediate(LocStrings.stub("ShutdownSafe"));
DatabaseManager.instance.upkeep(); DatabaseManager.instance.upkeep();
GlobalLog.warn(LogFilter.Command, LocStrings.lookup("ShutdownSafe")); GlobalLog.warn(LogFilter.Command, LocStrings.lookup("ShutdownSafe"));
System.exit(0); System.exit(0);
} }
else else
{ {
res.sendImmediate(LocStrings.stub("ShutdownUnsafe"));// "``"); res.sendImmediate(LocStrings.stub("ShutdownUnsafe"));// "``");
GlobalLog.warn(LogFilter.Command, LocStrings.lookup("ShutdownSafe")); GlobalLog.warn(LogFilter.Command, LocStrings.lookup("ShutdownSafe"));
System.exit(0); System.exit(0);
} }
} }
} }
@@ -1,4 +1,4 @@
package commands.images; package commands.general;
import java.awt.Color; import java.awt.Color;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
@@ -1,89 +1,89 @@
package commands.dev; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import core.CommandManager.ThreadData; import core.CommandManager.ThreadData;
import core.Constants; import core.Constants;
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 core.Stats; import core.Stats;
public class CommandStats extends Command public class CommandStats extends Command
{ {
public CommandStats(KittyRole level, KittyRating rating) { super(level, rating); } public CommandStats(KittyRole level, KittyRating rating) { super(level, rating); }
@Override @Override
public String getHelpText() { return LocStrings.stub("StatsInfo"); } public String getHelpText() { return LocStrings.stub("StatsInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
// Variables // Variables
Stats stats = Stats.instance; Stats stats = Stats.instance;
String out = ""; String out = "";
long seen = stats.getMessagesSeen(); long seen = stats.getMessagesSeen();
long processed = stats.getCommandsProcessed(); long processed = stats.getCommandsProcessed();
// General // General
out += "General"; out += "General";
out += "```\n"; out += "```\n";
out += " Messages observed: " + seen + "\n"; out += " Messages observed: " + seen + "\n";
out += "Commands processed: " + processed + "\n"; out += "Commands processed: " + processed + "\n";
out += " Command invoke %: " + ((int)((processed / (float)seen) * 1000)) / 10.0f + "%\n"; out += " Command invoke %: " + ((int)((processed / (float)seen) * 1000)) / 10.0f + "%\n";
out += " Bot uptime: " + stats.getFormattedUptime() + "\n"; out += " Bot uptime: " + stats.getFormattedUptime() + "\n";
out += "```\n"; out += "```\n";
// Health // Health
out += "Health"; out += "Health";
out += "```\n"; out += "```\n";
out += " SMT cores: " + stats.getCPUAvailable() + "\n"; out += " SMT cores: " + stats.getCPUAvailable() + "\n";
// If CPU load works on this OS, list it. -1.0 is the error state // If CPU load works on this OS, list it. -1.0 is the error state
double CPULoad = stats.getSystemCPULoad(); double CPULoad = stats.getSystemCPULoad();
out += CPULoad > -0.9 out += CPULoad > -0.9
? " CPU Load: " + (CPULoad * 100) + "%\n" : ""; ? " CPU Load: " + (CPULoad * 100) + "%\n" : "";
ThreadData data = stats.getThreadData(); ThreadData data = stats.getThreadData();
Integer terminated = data.states.get(Thread.State.TERMINATED); Integer terminated = data.states.get(Thread.State.TERMINATED);
Integer runnable = data.states.get(Thread.State.RUNNABLE); Integer runnable = data.states.get(Thread.State.RUNNABLE);
Integer blocked = data.states.get(Thread.State.BLOCKED); Integer blocked = data.states.get(Thread.State.BLOCKED);
Integer timed_waiting = data.states.get(Thread.State.TIMED_WAITING); Integer timed_waiting = data.states.get(Thread.State.TIMED_WAITING);
Integer waiting = data.states.get(Thread.State.WAITING); Integer waiting = data.states.get(Thread.State.WAITING);
out += " Threads:" out += " Threads:"
+ " run-" + (runnable == null ? 0 : runnable) + " run-" + (runnable == null ? 0 : runnable)
+ " block-" + (blocked == null ? 0 : blocked) + " block-" + (blocked == null ? 0 : blocked)
+ " sleep-" + (timed_waiting == null ? 0 : timed_waiting) + " sleep-" + (timed_waiting == null ? 0 : timed_waiting)
+ " wait-" + (waiting == null ? 0 : waiting) + " wait-" + (waiting == null ? 0 : waiting)
+ " term-" + (terminated == null ? 0 : terminated) + " term-" + (terminated == null ? 0 : terminated)
+ "\n"; + "\n";
out += "```\n"; out += "```\n";
// Cache // Cache
Integer guildCount = stats.getGuildCount(); Integer guildCount = stats.getGuildCount();
Integer userCount = stats.getUserCount(); Integer userCount = stats.getUserCount();
out += "Cache"; out += "Cache";
out += "```\n" out += "```\n"
+ "Cached Guilds: " + guildCount + "\n" + "Cached Guilds: " + guildCount + "\n"
+ " Cached Users: " + userCount; + " Cached Users: " + userCount;
out += "\n```"; out += "\n```";
KittyEmbed embed = new KittyEmbed(); KittyEmbed embed = new KittyEmbed();
embed.title = "Bot Stats"; embed.title = "Bot Stats";
embed.descriptionText = out; embed.descriptionText = out;
embed.color = Constants.ColorDefault; embed.color = Constants.ColorDefault;
res.send(embed); res.send(embed);
} }
} }
@@ -1,72 +1,72 @@
package commands.images; package commands.general;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import core.Command; import core.Command;
import core.Constants; import core.Constants;
import core.LocStrings; import core.LocStrings;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.ImageOverlayBuilder; import utils.ImageOverlayBuilder;
import utils.ImageUtils; import utils.ImageUtils;
public class CommandTeey extends Command public class CommandTeey extends Command
{ {
// Required constructor // Required constructor
public CommandTeey(KittyRole level, KittyRating rating) { super(level, rating); } public CommandTeey(KittyRole level, KittyRating rating) { super(level, rating); }
private static Long num = 0l; private static Long num = 0l;
@Override @Override
public String getHelpText() { return LocStrings.stub("TeeyInfo"); } public String getHelpText() { return LocStrings.stub("TeeyInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
String name = null; String name = null;
File teeyFile = null; File teeyFile = null;
File teeyeeFile = null; File teeyeeFile = null;
synchronized(num) synchronized(num)
{ {
name = "teey_" + num + ".gif"; name = "teey_" + num + ".gif";
++num; ++num;
} }
try try
{ {
KittyUser person = null; KittyUser person = null;
if(input.mentions == null) if(input.mentions == null)
person = user; person = user;
else else
person = input.mentions[0]; person = input.mentions[0];
String yeeteeFilename = ImageUtils.downloadFromURL(person.avatarID, ".png"); String yeeteeFilename = ImageUtils.downloadFromURL(person.avatarID, ".png");
if(yeeteeFilename == null) if(yeeteeFilename == null)
return; return;
teeyeeFile = new File(yeeteeFilename); teeyeeFile = new File(yeeteeFilename);
ImageOverlayBuilder builder = new ImageOverlayBuilder(Constants.AssetDirectory + "teey/frames/", "teey ", 24, 18); ImageOverlayBuilder builder = new ImageOverlayBuilder(Constants.AssetDirectory + "teey/frames/", "teey ", 24, 18);
builder.overlay(ImageIO.read(teeyeeFile), name); builder.overlay(ImageIO.read(teeyeeFile), name);
} }
catch (IOException e) catch (IOException e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
teeyFile = new File (name); teeyFile = new File (name);
res.sendFile(teeyFile, "gif"); res.sendFile(teeyFile, "gif");
// Thread cleanup... // Thread cleanup...
ImageUtils.blockingFileDelete(teeyFile); ImageUtils.blockingFileDelete(teeyFile);
ImageUtils.blockingFileDelete(teeyeeFile); ImageUtils.blockingFileDelete(teeyeeFile);
} }
} }
@@ -1,4 +1,4 @@
package commands.beans; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
@@ -25,29 +25,15 @@ public class CommandTradeBeans extends Command
res.send(LocStrings.stub("TradeBeansNoTargetError")); res.send(LocStrings.stub("TradeBeansNoTargetError"));
return; return;
} }
if(input.mentions.length > 1)
{
res.send(LocStrings.stub("TradeBeansMultipleUsersTagged"));
return;
}
int beans = 0; int beans = 0;
try {
try
{
beans = Integer.parseInt(input.args.split(" ")[0]); beans = Integer.parseInt(input.args.split(" ")[0]);
} }
catch (NumberFormatException e) catch (NumberFormatException e)
{ {
try res.send(LocStrings.stub("TradeBeansIntParseError"));
{ return;
beans = Integer.parseInt(input.args.split(" ")[1]);
}
catch(Exception eInner)
{
res.send(LocStrings.stub("TradeBeansIntParseError"));
return;
}
} }
if(user.getBeans() < beans) if(user.getBeans() < beans)
@@ -1,4 +1,4 @@
package commands.dev; package commands.general;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
+29
View File
@@ -0,0 +1,29 @@
package commands.general;
import core.Command;
import core.LocStrings;
import dataStructures.KittyChannel;
import dataStructures.KittyGuild;
import dataStructures.KittyRating;
import dataStructures.KittyRole;
import dataStructures.KittyUser;
import dataStructures.Response;
import dataStructures.UserInput;
public class CommandWeh extends Command {
public String getHelpText() { return LocStrings.stub("WehInfo"); }
public CommandWeh(KittyRole roleLevel, KittyRating contentRating) {
super(roleLevel, contentRating);
// TODO Auto-generated constructor stub
}
@Override
// The format for reutrning an emoji is: <:name:ID#>
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
res.send("<:weh:548301646929723393>");
}
}
@@ -1,4 +1,4 @@
package commands.network; package commands.general;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -1,72 +1,72 @@
package commands.images; package commands.general;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import core.Command; import core.Command;
import core.Constants; import core.Constants;
import core.LocStrings; import core.LocStrings;
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.Response; import dataStructures.Response;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.ImageOverlayBuilder; import utils.ImageOverlayBuilder;
import utils.ImageUtils; import utils.ImageUtils;
public class CommandYeet extends Command public class CommandYeet extends Command
{ {
// Required constructor // Required constructor
public CommandYeet(KittyRole level, KittyRating rating) { super(level, rating); } public CommandYeet(KittyRole level, KittyRating rating) { super(level, rating); }
private static Long num = 0l; private static Long num = 0l;
@Override @Override
public String getHelpText() { return LocStrings.stub("YeetInfo"); } public String getHelpText() { return LocStrings.stub("YeetInfo"); }
// Called when the command is run! // Called when the command is run!
@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)
{ {
String name = null; String name = null;
File yeetFile = null; File yeetFile = null;
File yeeteeFile = null; File yeeteeFile = null;
synchronized(num) synchronized(num)
{ {
name = "yeet_" + num + ".gif"; name = "yeet_" + num + ".gif";
++num; ++num;
} }
try try
{ {
KittyUser person = null; KittyUser person = null;
if(input.mentions == null) if(input.mentions == null)
person = user; person = user;
else else
person = input.mentions[0]; person = input.mentions[0];
String yeeteeFilename = ImageUtils.downloadFromURL(person.avatarID, ".png"); String yeeteeFilename = ImageUtils.downloadFromURL(person.avatarID, ".png");
if(yeeteeFilename == null) if(yeeteeFilename == null)
return; return;
yeeteeFile = new File(yeeteeFilename); yeeteeFile = new File(yeeteeFilename);
ImageOverlayBuilder builder = new ImageOverlayBuilder(Constants.AssetDirectory + "yeet/frames/", "yeet ", 24, 18); ImageOverlayBuilder builder = new ImageOverlayBuilder(Constants.AssetDirectory + "yeet/frames/", "yeet ", 24, 18);
builder.overlay(ImageIO.read(yeeteeFile), name); builder.overlay(ImageIO.read(yeeteeFile), name);
} }
catch (IOException e) catch (IOException e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
yeetFile = new File (name); yeetFile = new File (name);
res.sendFile(yeetFile, "gif"); res.sendFile(yeetFile, "gif");
// Thread cleanup... // Thread cleanup...
ImageUtils.blockingFileDelete(yeetFile); ImageUtils.blockingFileDelete(yeetFile);
ImageUtils.blockingFileDelete(yeeteeFile); ImageUtils.blockingFileDelete(yeeteeFile);
} }
} }
+3 -10
View File
@@ -2,7 +2,6 @@ package commands.music;
import core.Command; import core.Command;
import core.LocStrings; import core.LocStrings;
import core.SubCommandFormattable;
import core.SubCommandFramework; import core.SubCommandFramework;
import dataStructures.*; import dataStructures.*;
@@ -10,24 +9,18 @@ public class CommandMusicMain extends Command
{ {
SubCommandFramework framework = new SubCommandFramework(); SubCommandFramework framework = new SubCommandFramework();
public CommandMusicMain(KittyRole level, KittyRating rating) public CommandMusicMain(KittyRole level, KittyRating rating)
{ {
super(level, rating); super(level, rating);
framework.addCommand("join", new SubCommandJoin(KittyRole.General, KittyRating.Safe)); framework.addCommand("join", new SubCommandJoin(KittyRole.General, KittyRating.Safe));
framework.addCommand("leave", new SubCommandLeave(KittyRole.General, KittyRating.Safe)); framework.addCommand("leave", new SubCommandLeave(KittyRole.General, KittyRating.Safe));
framework.addCommand("add", new SubCommandAddTrack(KittyRole.General, KittyRating.Safe));
framework.addCommand("skip", new SubCommandSkip(KittyRole.General, KittyRating.Safe));
framework.addCommand("stop", new SubCommandStop(KittyRole.General, KittyRating.Safe));
framework.addCommand("playlist", new SubCommandPlaylist(KittyRole.General, KittyRating.Safe));
framework.addCommand("volume", new SubCommandVolume(KittyRole.General, KittyRating.Safe));
} }
@Override @Override
public String getHelpText() {return LocStrings.stub("MusicInfo"); } public String getHelpText() { return LocStrings.stub("MusicInfo"); }
@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)
{ {
SubCommandFormattable scf = framework.run(guild, channel, user, input); framework.run(guild, channel, user, input).Call(res);
scf.Call(res);
} }
} }
+1 -13
View File
@@ -1,6 +1,5 @@
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;
@@ -9,25 +8,14 @@ import dataStructures.KittyRating;
import dataStructures.KittyRole; import dataStructures.KittyRole;
import dataStructures.KittyUser; import dataStructures.KittyUser;
import dataStructures.UserInput; import dataStructures.UserInput;
import network.NetworkYoutube;
public class SubCommandAddTrack extends SubCommand public class SubCommandAddTrack extends SubCommand
{ {
public SubCommandAddTrack(KittyRole level, KittyRating rating) { super(level, rating); } public SubCommandAddTrack(KittyRole level, KittyRating rating) { super(level, rating); }
NetworkYoutube YT = new NetworkYoutube();
@Override @Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input) public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{ {
//Get track from Youtube return null;
String video = input.args;
if(!(video.startsWith("https://www.youtube") || video.startsWith("https://www.youtu.be")))
{
video = YT.getYT(video);
}
guild.audio.playVideo(video);
return new SubCommandFormattable(String.format(LocStrings.stub("MusicAddTrack"), video));
} }
} }
@@ -1,38 +0,0 @@
package commands.music;
import java.util.ArrayList;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
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 SubCommandPlaylist extends SubCommand
{
public SubCommandPlaylist(KittyRole roleLevel, KittyRating contentRating) {super(roleLevel, contentRating); }
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
ArrayList <AudioTrack> playlist = guild.audio.getPlaylist();
String stringPlaylist = "";
for(AudioTrack track : playlist)
{
stringPlaylist += (playlist.indexOf(track) + 1) + ": " + track.getInfo().title + "\n";
}
if(stringPlaylist.equals(""))
{
return new SubCommandFormattable("Nothing Queued!");
}
return new SubCommandFormattable(stringPlaylist);
}
}
-23
View File
@@ -1,23 +0,0 @@
package commands.music;
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 SubCommandSkip extends SubCommand
{
public SubCommandSkip(KittyRole level, KittyRating rating) { super(level, rating); }
{
}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
return new SubCommandFormattable(guild.audio.skipVideo(guild.audio.player));
}
}
-23
View File
@@ -1,23 +0,0 @@
package commands.music;
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 SubCommandStop extends SubCommand
{
public SubCommandStop(KittyRole roleLevel, KittyRating contentRating) {super(roleLevel, contentRating);}
@Override
public SubCommandFormattable OnRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input)
{
return new SubCommandFormattable(guild.audio.stopPlayer(guild.audio.player));
}
}
-42
View File
@@ -1,42 +0,0 @@
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));
}
}
-72
View File
@@ -1,72 +0,0 @@
package commands.network;
import core.Command;
import core.LocStrings;
import dataStructures.KittyChannel;
import dataStructures.KittyEmbed;
import dataStructures.KittyGuild;
import dataStructures.KittyRating;
import dataStructures.KittyRole;
import dataStructures.KittyUser;
import dataStructures.Response;
import dataStructures.UserInput;
import network.NetworkDerpi;
public class CommandDerpi extends Command
{
NetworkDerpi searcher = new NetworkDerpi();
KittyEmbed response;
// Required constructor
public CommandDerpi(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
public String getHelpText() { return "Will search derpibooru for the tags entered, if KittyBot's content filter allows it"; }
@Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
if(guild.contentRating == KittyRating.Filtered)
{
try
{
response = searcher.getDerpi(input.args.replace(',', ' ') + " safe").output();
res.send(response);
}
catch(Exception e)
{
res.send(LocStrings.stub("DerpiError"));
}
}
else
{
if(input.args == null || input.args.length() == 0)
res.send("DerpiNoSearchError");
else
{
response = searcher.getDerpi(input.args).output();
try
{
res.send(response);
}
catch(Exception e)
{
res.send(LocStrings.stub("DerpiError"));
}
}
}
if(input.args.startsWith("ID:"))
{
response = searcher.getDerpiByID(input.args.substring(input.args.indexOf(':'))).output();
try
{
res.send(response);
}
catch(Exception e)
{
res.send(LocStrings.stub("DerpiError"));
}
}
}
}
-71
View File
@@ -1,71 +0,0 @@
package commands.network;
import core.Command;
import core.LocStrings;
import dataStructures.*;
import network.NetworkE6;
public class CommandE6 extends Command
{
NetworkE6 searcher = new NetworkE6();
KittyEmbed response;
GenericImage image;
public CommandE6(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
public String getHelpText()
{
String toRet = "Will search e6";
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)
{
if(guild.contentRating == KittyRating.Filtered)
{
image = searcher.getE6(input.args + " rating:safe", "");
try
{
response = image.output();
}
catch(Exception e)
{
res.send(LocStrings.stub("E6Blacklisted"));
return;
}
try
{
if(response.bodyImageURL == null)
{
Exception e = new Exception();
throw e;
}
res.send(response);
}
catch(Exception e)
{
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"));
}
}
}
}
}
-35
View File
@@ -1,35 +0,0 @@
package commands.network;
import core.Command;
import core.LocStrings;
import dataStructures.KittyChannel;
import dataStructures.KittyGuild;
import dataStructures.KittyRating;
import dataStructures.KittyRole;
import dataStructures.KittyUser;
import dataStructures.Response;
import dataStructures.UserInput;
import network.NetworkSauceNAO;
public class CommandGetSauce extends Command
{
NetworkSauceNAO sauce = new NetworkSauceNAO();
public CommandGetSauce(KittyRole level, KittyRating rating) { super(level, rating); }
@Override
public String getHelpText() { return LocStrings.stub("GetSauceInfo"); };
@Override
public void onRun(KittyGuild guild, KittyChannel channel, KittyUser user, UserInput input, Response res)
{
try
{
res.send(sauce.getSauce(input.args).output());
}
catch(Exception e)
{
res.send("Image not found");
}
}
}
+4 -31
View File
@@ -4,37 +4,13 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
import commands.beans.CommandBeansShow; import commands.benchmark.CommandBenchmark;
import commands.beans.CommandBetBeans;
import commands.beans.CommandBetHistory;
import commands.beans.CommandGiveBeans;
import commands.beans.CommandTradeBeans;
import commands.characters.CommandCharacterMain; import commands.characters.CommandCharacterMain;
import commands.dev.CommandDBFlush; import commands.dew.CommandDew;
import commands.dev.CommandDBStats;
import commands.dev.CommandDoWork;
import commands.dev.CommandHelpBuilder;
import commands.dev.CommandInvite;
import commands.dev.CommandShutdown;
import commands.dev.CommandStats;
import commands.dev.CommandTweet;
import commands.general.*; import commands.general.*;
import commands.guildrole.CommandGuildRoleMain; import commands.guildrole.CommandGuildRoleMain;
import commands.images.CommandBlurry;
import commands.images.CommandCatch;
import commands.images.CommandDefaultDance;
import commands.images.CommandPerish;
import commands.images.CommandStark;
import commands.images.CommandTeey;
import commands.images.CommandYeet;
import commands.mod.CommandModMain; import commands.mod.CommandModMain;
import commands.music.CommandMusicMain; import commands.music.CommandMusicMain;
import commands.network.CommandColiru;
import commands.network.CommandDerpi;
import commands.network.CommandE6;
import commands.network.CommandGetSauce;
import commands.network.CommandJDoodle;
import commands.network.CommandWolfram;
import commands.poll.CommandPollMain; import commands.poll.CommandPollMain;
import commands.raffle.CommandRaffleMain; import commands.raffle.CommandRaffleMain;
import dataStructures.*; import dataStructures.*;
@@ -88,6 +64,7 @@ public class CommandManager
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));
this.register(LocCommands.stub("dew"), new CommandDew(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));
@@ -133,11 +110,7 @@ public class CommandManager
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("weh"), new CommandWeh(KittyRole.General, KittyRating.Safe));
this.register(LocCommands.stub("tradebeans, trade"), 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));
} }
// Allows the command manager to keep track of a command. Takes a pair (the un-localized and localzied commands) // Allows the command manager to keep track of a command. Takes a pair (the un-localized and localzied commands)
+1 -1
View File
@@ -52,4 +52,4 @@ public class CommandThread extends Thread
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
-1
View File
@@ -28,7 +28,6 @@ public class Config
sections = new Vector<IConfigSection>(); sections = new Vector<IConfigSection>();
// Add all sections // Add all sections
sections.add(new ConfigGlobals());
sections.add(new LocCommands()); sections.add(new LocCommands());
sections.add(new LocStrings()); sections.add(new LocStrings());
sections.add(new CommandEnabler()); sections.add(new CommandEnabler());
-102
View File
@@ -1,102 +0,0 @@
package core;
import java.util.ArrayList;
import java.util.List;
import dataStructures.KittyStartupMode;
import utils.GlobalLog;
// Want to add a single item to the config file? This is where that lives.
public class ConfigGlobals implements IConfigSection
{
// Defined const variables
public static final String header = "Globals";
public static ConfigGlobals instance;
// A pile of variables being manually tracked/serialized to the config file
private static final String startupStyleKey = "mode (dev or release)";
private KittyStartupMode startupStyleValue = KittyStartupMode.Dev;
private static final String activityKey = "activity";
private String activityValue = "with a laser pointer"; // Appears as "Playing with a laser pointer"
// Singleton Constructor - explode if there's a problem.
public ConfigGlobals()
{
if(instance == null)
{
instance = this;
}
else
{
GlobalLog.error("Attempted to initialize a second config globals! Probably don't do this!");
}
}
@Override
public String getSectionTitle()
{
return header;
}
public static KittyStartupMode getStartupMode()
{
return instance.startupStyleValue;
}
public static String getActivity()
{
return instance.activityValue;
}
@Override
public void consume(List<ConfigItem> pairs)
{
for(int i = 0; i < pairs.size(); ++i)
{
String key = pairs.get(i).key;
String value = pairs.get(i).value;
// Parse startup style
if(key.equalsIgnoreCase(startupStyleKey))
{
startupStyleValue = KittyStartupMode.Dev;
if(value.equalsIgnoreCase(KittyStartupMode.Release.name()))
{
startupStyleValue = KittyStartupMode.Release;
}
if(value.equalsIgnoreCase(KittyStartupMode.PoguRelease.name()))
{
startupStyleValue = KittyStartupMode.PoguRelease;
}
continue;
}
// Parse text for 'playing'
if(key.equalsIgnoreCase(activityKey))
{
activityValue = value;
}
}
// If we change any globals, update anything we need to.
if(ObjectBuilder.getHasInitialized())
{
ObjectBuilder.updateActivity();
}
}
@Override
public List<ConfigItem> produce()
{
List<ConfigItem> items = new ArrayList<ConfigItem>();
items.add(new ConfigItem(getSectionTitle(), startupStyleKey, startupStyleValue.name().toLowerCase()));
items.add(new ConfigItem(getSectionTitle(), activityKey, activityValue));
return items;
}
}
+3 -3
View File
@@ -6,9 +6,9 @@ import utils.StringUtils;
// perform any parsing past naming columns, and just holds the raw data. // perform any parsing past naming columns, and just holds the raw data.
public class ConfigItem public class ConfigItem
{ {
public String type; // The section this specific key/value pair belongs to. This almost certainly will appear in multiple places. public String type;
public String key; // A unique key for a given lookup value for the specified section. Keys, within sections, are unique. public String key;
public String value; // The value assocaited with the key. public String value;
public static final int items = 3; public static final int items = 3;
public static final String[] header = {"Type","Key","Value"}; public static final String[] header = {"Type","Key","Value"};
+2 -2
View File
@@ -11,7 +11,7 @@ import dataStructures.Pair;
public class LocCommands extends BaseLocFile implements IConfigSection public class LocCommands extends BaseLocFile implements IConfigSection
{ {
// Defined const variables // Defined const variables
public static final String header = "Localized Commands"; public static final String HeaderName = "Localized Commands";
public static final String function = "LocCommands.stub"; public static final String function = "LocCommands.stub";
// Instance // Instance
@@ -20,7 +20,7 @@ public class LocCommands extends BaseLocFile implements IConfigSection
// Constructor // Constructor
public LocCommands() public LocCommands()
{ {
super(header, function); super(HeaderName, function);
GlobalLog.log(LogFilter.Core, "Initializing " + this.getClass().getSimpleName()); GlobalLog.log(LogFilter.Core, "Initializing " + this.getClass().getSimpleName());
@@ -1,512 +1,453 @@
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 core.lua.PluginManager;
//import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; import dataStructures.*;
//import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; import main.Main;
import net.dv8tion.jda.core.AccountType;
import core.lua.PluginManager; import net.dv8tion.jda.core.JDA;
import dataStructures.KittyChannel; import net.dv8tion.jda.core.JDABuilder;
import dataStructures.KittyCore; import net.dv8tion.jda.core.entities.*;
import dataStructures.KittyGuild; import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import dataStructures.KittyRating; import offline.Ref;
import dataStructures.KittyRole; import utils.AdminControl;
import dataStructures.KittyStartupMode; //import utils.AudioUtils;
import dataStructures.KittyUser; import utils.GlobalLog;
import main.Main; import utils.LogFilter;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA; // NOTE(wisp): Isolated factory to assist with storage and caching if needed.
import net.dv8tion.jda.api.JDABuilder; // This also minimizes the number of places JDA interacts with our codebase.
import net.dv8tion.jda.api.entities.Activity; // As it stands, if the object name begins with Kitty, it's constructed here.
import net.dv8tion.jda.api.entities.Emote; // TODO: Make all methods ID based instead of event based
import net.dv8tion.jda.api.entities.Guild; public class ObjectBuilderFactory
import net.dv8tion.jda.api.entities.Member; {
import net.dv8tion.jda.api.entities.User; // Key: guild string id, Value: guild information
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; private static HashMap<String, KittyGuild> guildCache;
import offline.Ref;
import utils.AdminControl; // Key: channel string id, Value: channel information
//import utils.AudioUtils; private static HashMap<String, KittyChannel> channelCache;
import utils.GlobalLog;
import utils.LogFilter; // Key: guild string id + user string id, Value: user information
import utils.audio.AudioUtils; private static HashMap<String, KittyUser> userCache;
// NOTE: Isolated factory to assist with storage and caching if needed. // For tracking and managing object sync
// This also minimizes the number of places JDA interacts with our codebase. private static DatabaseManager database;
// As it stands, if the object name begins with Kitty, it's constructed here.
// TODO: Make all methods ID based instead of event based // Stats tracking and whatnot... for setting stats too internally potentially
public class ObjectBuilder private static Stats stats;
{
// Key: guild string id, Value: guild information // RPManger for tracking RP system
private static HashMap<String, KittyGuild> guildCache; private static RPManager rpManager;
// Key: channel string id, Value: channel information // Plugin manager
private static HashMap<String, KittyChannel> channelCache; private static PluginManager pluginManager;
// Key: guild string id + user string id, Value: user information // Command manager
private static HashMap<String, KittyUser> userCache; private static CommandManager commandManager;
// For tracking and managing object sync //Audio track manager
private static DatabaseManager database; // private static AudioPlayerManager audioPlayer = new DefaultAudioPlayerManager();
// Stats tracking and whatnot... for setting stats too internally potentially // Localization classes - these are singletons, but should be initialized before almost all other
private static Stats stats; // things so their inclusion in the factory is to ensure they're started at the correct time.
@SuppressWarnings("unused") private static LocStrings locStrings;
// RPManger for tracking RP system @SuppressWarnings("unused") private static LocCommands locCommands;
private static RPManager rpManager;
// Config
// Plugin manager @SuppressWarnings("unused") private static Config config;
private static PluginManager pluginManager;
// Lazy initialization multithreaded mutex stuff to prevent explosions.
// Command manager // TODO: Investigate using 'synchronized' instead potentially
private static CommandManager commandManager; private static boolean hasInitialized;
private static Semaphore initMutex = new Semaphore(1);
//Audio track manager private static JDA kitty;
private static AudioPlayerManager playerManager = new DefaultAudioPlayerManager();
// This is it, this is how the lazy init starts!
// Localization classes - these are singletons, but should be initialized before almost all other private static void lazyInit()
// things so their inclusion in the factory is to ensure they're started at the correct time. {
@SuppressWarnings("unused") private static LocStrings locStrings; if(hasInitialized)
@SuppressWarnings("unused") private static LocCommands locCommands; return;
// Config try
@SuppressWarnings("unused") private static Config config; {
initMutex.acquire();
// Lazy initialization multithreaded mutex stuff to prevent explosions. try
// TODO: Investigate using 'synchronized' instead potentially {
private static Boolean hasInitialized = false; // structure initialization
private static Semaphore initMutex = new Semaphore(1); // Construct necessary data structures.
private static JDA kitty; guildCache = new HashMap<String, KittyGuild>();
userCache = new HashMap<String, KittyUser>();
// This is it, this is how the lazy init starts! channelCache = new HashMap<String, KittyChannel>();
private static void lazyInit() database = null;
{ stats = null;
synchronized(hasInitialized)
{ // Start by reading from things that are external. Because
if(hasInitialized) // we require these things to be resolved before the rest of the application,
{ // we place them here.
return; config = new Config();
} }
} finally
{
try initMutex.release();
{ hasInitialized = true;
initMutex.acquire(); }
try }
{ catch(InterruptedException ie)
// structure initialization {
// Construct necessary data structures. GlobalLog.error(LogFilter.Core, "Issue during object builder lazy initialization."
guildCache = new HashMap<String, KittyGuild>(); + " The factory was not initialized, and kitty will not be able to continue functionally.");
userCache = new HashMap<String, KittyUser>(); }
channelCache = new HashMap<String, KittyChannel>(); }
database = null;
stats = null; ////////////////////////
// Extraction Methods //
AudioSourceManagers.registerRemoteSources(playerManager); ////////////////////////
AudioSourceManagers.registerLocalSource(playerManager);
// Explicitly locks: guildCache
// Start by reading from things that are external. Because public static KittyGuild extractGuild(GuildMessageReceivedEvent event)
// we require these things to be resolved before the rest of {
// the application, we place them here. lazyInit();
config = new Config();
} // Look up the guild. This process can only happen in a single-threaded way
finally // because of the nature of the cache. We wait until the last second to
{ // look up the guild.
initMutex.release(); String uid = event.getGuild().getId();
synchronized(hasInitialized)
{ List<Emote> emotes = event.getGuild().getEmotes();
hasInitialized = true; ArrayList<String> emotesString = new ArrayList<String>();
} String emote;
} String emoteFix;
} for(int i = 0; i < emotes.size(); i++)
catch(InterruptedException ie) {
{ emote = emotes.get(i).toString();
GlobalLog.error(LogFilter.Core, "Issue during object builder lazy initialization." emoteFix = "<:" + emote.substring(2, emote.indexOf("("));
+ " The factory was not initialized, and kitty will not be able to continue functionally."); emoteFix += ":" + emote.substring(emote.indexOf("(")+1, emote.length()-1) + ">";
} emotesString.add(emoteFix);
} }
public static boolean getHasInitialized() // once we're lazily initialized, we can synchronize w/ the
{ // guildCache object now instead of having to use a mutex.
synchronized(hasInitialized) KittyGuild guild = null;
{ synchronized (guildCache)
return hasInitialized; {
} KittyGuild cachedGuild = guildCache.get(uid);
} if(cachedGuild != null)
{
//////////////////////// guild = cachedGuild;
// Extraction Methods // }
//////////////////////// else
{
// Explicitly locks: guildCache // Construct a new guild with defaults
public static KittyGuild extractGuild(GuildMessageReceivedEvent event) guild = new KittyGuild(uid, new AdminControl(event.getGuild()), emotesString);
{ DatabaseManager.instance.globalRegister(guild);
lazyInit(); guildCache.put(uid, guild);
}
// 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
// look up the guild. return guild;
String uid = event.getGuild().getId(); }
List<Emote> emotes = event.getGuild().getEmotes(); // Explicitly locks: guildCache
ArrayList<String> emotesString = new ArrayList<String>(); public static KittyRole extractRole(GuildMessageReceivedEvent event)
HashMap<Long, KittyChannel> channels = new HashMap<Long, KittyChannel>(); {
String emote; lazyInit();
String emoteFix;
channels.put(Long.getLong(uid), extractChannel(event)); // Looks up the user role. If none is found we check to see if they own
for(int i = 0; i < emotes.size(); i++) // the guild if not, they're assumed to be
{ // allowed to use the bot at a general level.
emote = emotes.get(i).toString(); KittyRole role = KittyRole.General;
emoteFix = "<:" + emote.substring(2, emote.indexOf("("));
emoteFix += ":" + emote.substring(emote.indexOf("(")+1, emote.length()-1) + ">"; if(event.getAuthor().getId() == event.getGuild().getOwner().getUser().getId())
emotesString.add(emoteFix); {
} role = KittyRole.Admin;
}
// once we're lazily initialized, we can synchronize w/ the
// guildCache object now instead of having to use a mutex. String uid = event.getGuild().getId() + event.getAuthor().getId();
KittyGuild guild = null; synchronized(userCache)
synchronized (guildCache) {
{ KittyUser cachedUser = userCache.get(uid);
KittyGuild cachedGuild = guildCache.get(uid); if(cachedUser != null)
if(cachedGuild != null) role = cachedUser.getRole();
{ }
guild = cachedGuild;
} return role;
else }
{
// Construct a new guild with defaults // Explicitly locks: guildCache
guild = new KittyGuild(uid, new AdminControl(event.getGuild()), emotesString, // Extracts the content rating information it can from the provided event.
new AudioUtils(event.getGuild(), playerManager), channels); public static KittyRating extractContentRating(GuildMessageReceivedEvent event)
DatabaseManager.instance.globalRegister(guild); {
guildCache.put(uid, guild); lazyInit();
}
} // Look up content rating of the guild, returns a safe content rating.
KittyRating contentRating = KittyRating.Safe;
return guild; String uid = event.getGuild().getId();
} synchronized(guildCache)
{
KittyGuild cachedGuild = guildCache.get(uid);
if(cachedGuild != null)
// Explicitly locks: guildCache contentRating = cachedGuild.contentRating;
public static KittyRole extractRole(GuildMessageReceivedEvent event) }
{
lazyInit(); return contentRating;
}
// 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 // Implicitly locks guild cache by calling ExtractGuild
// allowed to use the bot at a general level. public static KittyChannel extractChannel(GuildMessageReceivedEvent event)
KittyRole role = KittyRole.General; {
lazyInit();
if(event.getAuthor().getId() == event.getGuild().getOwnerId())
{ String channelID = event.getChannel().getId();
role = KittyRole.Admin; String guildID = event.getGuild().getId();
} KittyChannel channel = null;
String uid = event.getGuild().getId() + event.getAuthor().getId(); synchronized(channelCache)
synchronized(userCache) {
{ KittyChannel cachedChannel = channelCache.get(channelID);
KittyUser cachedUser = userCache.get(uid);
if(cachedUser != null) if(cachedChannel != null)
role = cachedUser.getRole(); {
} channel = cachedChannel;
}
return role; else
} {
KittyGuild cachedGuild = guildCache.get(guildID);
// Explicitly locks: guildCache channel = new KittyChannel(channelID, cachedGuild);
// Extracts the content rating information it can from the provided event. channelCache.put(channelID, channel);
public static KittyRating extractContentRating(GuildMessageReceivedEvent event) }
{ }
lazyInit();
return channel;
// Look up content rating of the guild, returns a safe content rating. }
KittyRating contentRating = KittyRating.Safe;
String uid = event.getGuild().getId(); // Implicitly locks guild cache by calling ExtractRole and ExtractGuild
synchronized(guildCache) public static KittyUser extractUser(GuildMessageReceivedEvent event)
{ {
KittyGuild cachedGuild = guildCache.get(uid); lazyInit();
if(cachedGuild != null)
contentRating = cachedGuild.contentRating; String uid = event.getGuild().getId() + event.getAuthor().getId();
} KittyUser user = null;
synchronized(userCache)
return contentRating; {
} KittyUser cachedUser = userCache.get(uid);
if(cachedUser != null)
// Implicitly locks guild cache by calling ExtractGuild {
public static KittyChannel extractChannel(GuildMessageReceivedEvent event) updateUser(cachedUser, event.getMember());
{ user = cachedUser;
lazyInit(); }
String channelID = event.getChannel().getId(); else
KittyChannel channel = null; {
KittyRole role = extractRole(event);
synchronized(channelCache) KittyGuild guild = extractGuild(event);
{
KittyChannel cachedChannel = channelCache.get(channelID); String name;
boolean mature; if(event.getMember().getNickname() == null)
name = event.getAuthor().getName();
if(cachedChannel != null) else
{ name = event.getMember().getNickname();
channel = cachedChannel;
} String discordID = event.getMember().getUser().getId();
else String avatarID = event.getAuthor().getAvatarUrl();
{ user = new KittyUser(name, guild, role, uid, avatarID, discordID);
mature = event.getChannel().isNSFW(); DatabaseManager.instance.globalRegister(user);
channel = new KittyChannel(channelID, mature); userCache.put(uid, user);
channelCache.put(channelID, channel); }
} }
}
if(event.getMessage().getMentionedMembers().isEmpty())
return channel; return user;
}
Member mentioned;
// Implicitly locks guild cache by calling ExtractRole and ExtractGuild for(int i = 0; i < event.getMessage().getMentionedMembers().size(); i++)
public static KittyUser extractUser(GuildMessageReceivedEvent event) {
{ mentioned = event.getMessage().getMentionedMembers().get(i);
lazyInit(); if(mentioned.getNickname() != null)
extractUserByJDAUser(event.getGuild().getId(), mentioned.getNickname(),
String uid = event.getGuild().getId() + event.getAuthor().getId(); mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId());
KittyUser user = null; else
synchronized(userCache) extractUserByJDAUser(event.getGuild().getId(), mentioned.getUser().getName(),
{ mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId());
KittyUser cachedUser = userCache.get(uid); }
if(cachedUser != null)
{ return user;
updateUser(cachedUser, event.getMember()); }
user = cachedUser;
} // TODO: Clean up
else public static KittyUser extractUserByJDAUser(String guildID, String name, String userID, String avatarID, String discordID)
{ {
KittyRole role = extractRole(event); lazyInit();
KittyGuild guild = extractGuild(event);
String uid = guildID + userID;
String name; KittyUser user = null;
if(event.getMember().getNickname() == null) synchronized(userCache)
name = event.getAuthor().getName(); {
else KittyUser cachedUser = userCache.get(uid);
name = event.getMember().getNickname(); if(cachedUser != null)
{
String discordID = event.getMember().getUser().getId(); if(name != null)
String avatarID = event.getAuthor().getAvatarUrl(); cachedUser.name = name;
user = new KittyUser(name, guild, role, uid, avatarID, discordID);
DatabaseManager.instance.globalRegister(user); cachedUser.avatarID = avatarID;
userCache.put(uid, user); user = cachedUser;
} }
} else
{
if(event.getMessage().getMentionedMembers().isEmpty()) KittyRole role = KittyRole.General;
return user; KittyGuild guild = guildCache.get(guildID);
user = new KittyUser(name, guild, role, uid, avatarID, discordID);
Member mentioned; DatabaseManager.instance.globalRegister(user);
for(int i = 0; i < event.getMessage().getMentionedMembers().size(); i++) userCache.put(uid, user);
{ }
mentioned = event.getMessage().getMentionedMembers().get(i); }
if(mentioned.getNickname() != null)
extractUserByJDAUser(event.getGuild().getId(), mentioned.getNickname(), return user;
mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId()); }
else
extractUserByJDAUser(event.getGuild().getId(), mentioned.getUser().getName(), // There is some redundant lookup occurring. If the user isn't cached yet, then we construct them and cache them.
mentioned.getUser().getId(), mentioned.getUser().getAvatarUrl(), mentioned.getUser().getId()); // The assumption is made that the user does, in fact, exist.
} public static KittyUser getKittyUser(String guildID, String userID)
{
return user; String uid = guildID + userID;
} KittyUser user = null;
synchronized(userCache)
// TODO: Clean up {
public static KittyUser extractUserByJDAUser(String guildID, String name, String userID, String avatarID, String discordID) user = userCache.get(uid);
{ }
lazyInit();
if(user == null)
String uid = guildID + userID; {
KittyUser user = null; Guild jdaGuild = kitty.getGuildById(guildID);
synchronized(userCache) if(jdaGuild == null) return null;
{
KittyUser cachedUser = userCache.get(uid); Member jdaMember = jdaGuild.getMemberById(userID);
if(cachedUser != null) if(jdaMember == null) return null;
{
if(name != null) User jdaUser = jdaMember.getUser();
cachedUser.name = name; if(jdaUser == null) return null;
cachedUser.avatarID = avatarID; user = extractUserByJDAUser(guildID, jdaMember.getNickname(), jdaUser.getId(), jdaUser.getAvatarUrl(), jdaUser.getId());
user = cachedUser; updateUser(user, jdaMember);
} }
else
{ return user;
KittyRole role = KittyRole.General; }
KittyGuild guild = guildCache.get(guildID);
user = new KittyUser(name, guild, role, uid, avatarID, discordID); // Updates a user's name appropriately based on nickname if available
DatabaseManager.instance.globalRegister(user); public static void updateUser(KittyUser user, Member member)
userCache.put(uid, user); {
} if(member.getNickname() == null)
} {
user.name = member.getUser().getName();
return user; }
} else
{
// There is some redundant lookup occurring. If the user isn't cached yet, then we construct them and cache them. user.name = member.getNickname();
// The assumption is made that the user does, in fact, exist. }
public static KittyUser getKittyUser(String guildID, String userID)
{ user.avatarID = member.getUser().getAvatarUrl();
String uid = guildID + userID; }
KittyUser user = null;
synchronized(userCache)
{ //////////////////////////
user = userCache.get(uid); // Construction Methods //
} //////////////////////////
// Builds the core of the bot
if(user == null) public static KittyCore constructKittyCore() throws LoginException, InterruptedException
{ {
Guild jdaGuild = kitty.getGuildById(guildID); lazyInit();
if(jdaGuild == null) return null;
kitty = new JDABuilder(AccountType.BOT).setToken(Ref.TestToken).buildBlocking();
Member jdaMember = jdaGuild.getMemberById(userID); kitty.getPresence().setGame(Game.playing("with digital yarn"));
if(jdaMember == null) return null; kitty.addEventListener(new Main());
User jdaUser = jdaMember.getUser(); return new KittyCore(kitty);
if(jdaUser == null) return null; }
user = extractUserByJDAUser(guildID, jdaMember.getNickname(), jdaUser.getId(), jdaUser.getAvatarUrl(), jdaUser.getId()); // Default construction of the command manager. In order to remotely resolve command enabling
updateUser(user, jdaMember); // 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
// only have one CommandEnabler.
return user; public static CommandManager constructCommandManager(CommandEnabler commandEnabler)
} {
lazyInit();
// Updates a user's name appropriately based on nickname if available
public static void updateUser(KittyUser user, Member member) if(commandManager == null)
{ commandManager = new CommandManager(commandEnabler);
if(member.getNickname() == null)
{ return commandManager;
user.name = member.getUser().getName(); }
}
else // Default database manager construction. It can be constructed
{ // in different ways, and so we construct it outside of the constructor for
user.name = member.getNickname(); // the factory since it doesn't have to be present / can be elsewhere.
} // Effectively we cache the database here.
public static DatabaseManager constructDatabaseManager()
user.avatarID = member.getUser().getAvatarUrl(); {
} lazyInit();
if(database == null)
////////////////////////// database = new DatabaseManager();
// Construction Methods //
////////////////////////// return database;
// Builds the core of the bot }
public static KittyCore constructKittyCore() throws LoginException, InterruptedException
{ public static Stats constructStats(CommandManager manager)
lazyInit(); {
lazyInit();
// Determine token based on config. Default to test token.
String tokenToUse = Ref.TestToken; if(stats == null)
switch(ConfigGlobals.getStartupMode()) stats = new Stats(manager);
{
case Release: tokenToUse = Ref.Token; break; return stats;
case PoguRelease: tokenToUse = Ref.PoguToken; break; }
default: tokenToUse = Ref.TestToken; break;
} public static RPManager constructRPManager()
{
// Construct bot based on token using the JDA Builder lazyInit();
JDABuilder builder = JDABuilder.createDefault(tokenToUse);
kitty = builder.build(); if(rpManager == null)
rpManager = new RPManager();
// Set activity, and add primariy event listener.
updateActivity(); return rpManager;
kitty.addEventListener(new Main()); }
return new KittyCore(kitty); public static PluginManager constructPluginManager()
} {
lazyInit();
// Updates the bots current activity based on the globals value.
public static void updateActivity() if(pluginManager == null)
{ pluginManager = new PluginManager(Constants.AssetDirectory + "plugins/");
String activity = ConfigGlobals.getActivity();
GlobalLog.log(LogFilter.Core, "Updating activity to " + activity); return pluginManager;
kitty.getPresence().setActivity(Activity.playing(activity)); }
}
// 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 // Utility Methods //
// the CommandEnabler object passed in. In theory, we could have multiple CommandManagers, tho we can /////////////////////
// only have one CommandEnabler.
public static CommandManager constructCommandManager(CommandEnabler commandEnabler) // Returns number of cached guilds (does not equal total users in the database, only what's in memory)
{ public static Integer getGuildCount()
lazyInit(); { synchronized(guildCache)
{
if(commandManager == null) return guildCache.size();
commandManager = new CommandManager(commandEnabler); }
}
return commandManager;
} // Returns number of cached users (does not equal total users in the database, only what's in memory)
public static Integer getUserCount()
// Default database manager construction. It can be constructed { synchronized(userCache)
// 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. return userCache.size();
// Effectively we cache the database here. }
public static DatabaseManager constructDatabaseManager() }
{
lazyInit();
if(database == null)
database = new DatabaseManager();
return database;
}
public static Stats constructStats(CommandManager manager)
{
lazyInit();
if(stats == null)
stats = new Stats(manager);
return stats;
}
public static RPManager constructRPManager()
{
lazyInit();
if(rpManager == null)
rpManager = new RPManager();
return rpManager;
}
public static PluginManager constructPluginManager()
{
lazyInit();
if(pluginManager == null)
pluginManager = new PluginManager(Constants.AssetDirectory + "plugins/");
return pluginManager;
}
/////////////////////
// Utility Methods //
/////////////////////
// Returns number of cached guilds (does not equal total users in the database, only what's in memory)
public static Integer getGuildCount()
{ synchronized(guildCache)
{
return guildCache.size();
}
}
// Returns number of cached users (does not equal total users in the database, only what's in memory)
public static Integer getUserCount()
{ synchronized(userCache)
{
return userCache.size();
}
}
} }
+2 -2
View File
@@ -107,12 +107,12 @@ public class Stats
public int getGuildCount() public int getGuildCount()
{ {
return ObjectBuilder.getGuildCount(); return ObjectBuilderFactory.getGuildCount();
} }
public int getUserCount() public int getUserCount()
{ {
return ObjectBuilder.getUserCount(); return ObjectBuilderFactory.getUserCount();
} }
public ArrayList<Command> getAllCommands() public ArrayList<Command> getAllCommands()
+6 -1
View File
@@ -7,6 +7,7 @@ import dataStructures.KittyGuild;
import dataStructures.KittyUser; import dataStructures.KittyUser;
import dataStructures.UserInput; import dataStructures.UserInput;
import utils.GlobalLog; import utils.GlobalLog;
import utils.LogFilter;
public class SubCommandFramework public class SubCommandFramework
{ {
@@ -41,10 +42,14 @@ public class SubCommandFramework
} }
catch(Exception e) catch(Exception e)
{ {
GlobalLog.error(LogFilter.Command, e);
String help = Stats.instance.getHelpText(input.key); String help = Stats.instance.getHelpText(input.key);
if(help != null) if(help != null)
return new SubCommandFormattable(help); return new SubCommandFormattable(help);
return new SubCommandFormattable("Something has gone very wrong.");
return new SubCommandFormattable("Whoops! Internal subcommand error!");
} }
} }
} }
+16 -33
View File
@@ -1,57 +1,40 @@
package dataStructures; package dataStructures;
import java.awt.Color; // This is a structure representing an image reponse for handing around.
// This is a structure representing an image response for handing around.
public class GenericImage public class GenericImage
{ {
private KittyEmbed response= new KittyEmbed(); private String artist;
private String postURL;
private String imageURL;
public GenericImage(String artist, String postURL, String imageURL) public GenericImage(String artist, String postURL, String imageURL)
{ {
response.authorText = null; this.artist = artist;
response.color = new Color(0,0,0); this.postURL = postURL;
this.imageURL = imageURL;
} }
public void editArtist(String artist) public void editArtist(String artist)
{ {
response.authorText = artist; this.artist = artist;
}
public void editAuthorImage(String URL)
{
response.authorImage = URL;
} }
public void editPostURL(String postURL) public void editPostURL(String postURL)
{ {
response.authorLink = postURL; this.postURL = postURL;
} }
public void editImageURL(String imageURL) public void editImageURL(String imageURL)
{ {
response.imageURL = imageURL; this.imageURL = imageURL;
} }
public void editDescriptionText(String score) public String toString()
{ {
response.descriptionText = score; if(imageURL.isEmpty())
} {
return "I couldn't find anything! Please try again!";
public void editFooterText(String tags) }
{ return "Artist: " + artist + "\n<" + postURL.trim() + ">\n" + imageURL;
response.footerText = tags;
}
public KittyEmbed output()
{
return response;
}
public boolean isValid()
{
if(response.title != null)
return true;
return false;
} }
} }
+31 -15
View File
@@ -1,15 +1,31 @@
package dataStructures; package dataStructures;
//import core.DatabaseTrackedObject;
public class KittyChannel
{ public class KittyChannel //extends DatabaseTrackedObject
public String uniqueID; {
public boolean mature; public String uniqueID;
public KittyGuild guild;
public KittyChannel(String uniqueID, boolean mature)
{ //public KittyRating rating;
//super(uniqueID); //public bool isVoice;
this.uniqueID = uniqueID;
this.mature = false; public KittyChannel(String uniqueID, KittyGuild guild)
} {
} //super(uniqueID);
this.uniqueID = uniqueID;
this.guild = guild;
}
// @Override
// public String serialize()
// {
// return "";
// }
//
// @Override
// public void deSerialzie(String string)
// {
//
// }
}
+13 -13
View File
@@ -1,13 +1,13 @@
package dataStructures; package dataStructures;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.core.JDA;
public class KittyCore public class KittyCore
{ {
public final JDA jda; public final JDA jda;
public KittyCore(JDA kitty) public KittyCore(JDA kitty)
{ {
this.jda = kitty; this.jda = kitty;
} }
} }
+173 -182
View File
@@ -1,182 +1,173 @@
package dataStructures; package dataStructures;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import core.DatabaseManager;
import core.DatabaseManager; import core.DatabaseTrackedObject;
import core.DatabaseTrackedObject; import utils.AdminControl;
import utils.AdminControl; import utils.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 AdminControl control;
public HashMap <Long, KittyChannel> channels; public AudioUtils audio;
public AdminControl control; public ArrayList <KittyUser> raffleUsersUnchosen = new ArrayList<KittyUser>();
public AudioUtils audio; public ArrayList <KittyUser> raffleUsersChosen = new ArrayList<KittyUser>();
public ArrayList <KittyUser> raffleUsersUnchosen = new ArrayList<KittyUser>();
public ArrayList <KittyUser> raffleUsersChosen = new ArrayList<KittyUser>(); // Database synced info
private final String roleListName = "guildRoles";
// Database synced info public final KittyTrackedVector roleList;
private final String roleListName = "guildRoles";
public final KittyTrackedVector roleList; private final String beansName = "guildBeans";
public final KittyTrackedLong beans;
private final String beansName = "guildBeans";
public final KittyTrackedLong beans; private String commandIndicator;
private String commandIndicator; private void registerTrackedObjects()
{
private void registerTrackedObjects() DatabaseManager.instance.globalRegister(roleList);
{ DatabaseManager.instance.globalRegister(beans);
DatabaseManager.instance.globalRegister(roleList); }
DatabaseManager.instance.globalRegister(beans);
} // Default content for a guild
public KittyGuild(String uniqueID, AdminControl adminControl, ArrayList <String> emoji)
// Default content for a guild {
public KittyGuild(String uniqueID, AdminControl adminControl, ArrayList <String> emoji, super(uniqueID);
AudioUtils audio, HashMap<Long, KittyChannel> channels) this.uniqueID = uniqueID;
{ roleList = new KittyTrackedVector(roleListName, uniqueID);
beans = new KittyTrackedLong(beansName, uniqueID);
super(uniqueID); registerTrackedObjects();
this.uniqueID = uniqueID;
roleList = new KittyTrackedVector(roleListName, uniqueID); control = adminControl;
beans = new KittyTrackedLong(beansName, uniqueID); this.contentRating = KittyRating.Safe;
registerTrackedObjects(); this.polling = false;
this.emoji = emoji;
control = adminControl; setCommandIndicator("!");
this.contentRating = KittyRating.Safe; }
this.polling = false;
this.emoji = emoji; // Explicit constructor
this.audio = audio; public KittyGuild(String commandIndicator, KittyRating contentRating, KittyUser guildOwner, String uniqueID)
this.channels = channels; {
setCommandIndicator("!"); super(uniqueID);
} this.uniqueID = uniqueID;
roleList = new KittyTrackedVector(roleListName, uniqueID);
// Explicit constructor beans = new KittyTrackedLong(beansName, uniqueID);
public KittyGuild(String commandIndicator, KittyRating contentRating, KittyUser guildOwner, registerTrackedObjects();
String uniqueID, AudioUtils audio, HashMap<Long, KittyChannel> channels)
{ setCommandIndicator(commandIndicator);
super(uniqueID); this.contentRating = contentRating;
this.uniqueID = uniqueID; this.polling = false;
roleList = new KittyTrackedVector(roleListName, uniqueID); this.guildOwner = guildOwner;
beans = new KittyTrackedLong(beansName, uniqueID); }
registerTrackedObjects();
public String startPoll(String poll)
setCommandIndicator(commandIndicator); {
this.contentRating = contentRating; polling = true;
this.polling = false; this.poll = poll;
this.guildOwner = guildOwner; return "Poll `" + poll + "` started! Don't forget to add choices with `!poll choice`~";
this.audio = audio; }
this.channels = channels;
} public String addChoiceToPoll(String choice)
{
public String startPoll(String poll) choices.add(new KittyPoll(choice));
{ return "Added `" + choice + "` to poll!";
polling = true; }
this.poll = poll;
return "Poll `" + poll + "` started! Don't forget to add choices with `!poll choice`~"; public String endPoll()
} {
choices.clear();
public String addChoiceToPoll(String choice) hasVoted.clear();
{ this.polling = false;
choices.add(new KittyPoll(choice)); poll = null;
return "Added `" + choice + "` to poll!"; return "Poll ended!";
} }
public String endPoll() //Raffle methods
{ public boolean startRaffle(int beanCost)
choices.clear(); {
hasVoted.clear(); if(raffling)
this.polling = false; {
poll = null; return false;
return "Poll ended!"; }
} raffleCost = beanCost;
raffling = true;
//Raffle methods return true;
public boolean startRaffle(int beanCost) }
{
if(raffling) public boolean endRaffle()
{ {
return false; if(raffling)
} {
raffleCost = beanCost; raffleCost = 0;
raffling = true; raffling = false;
return true; raffleUsersChosen.removeAll(raffleUsersChosen);
} raffleUsersUnchosen.removeAll(raffleUsersUnchosen);
return true;
public boolean endRaffle() }
{ return false;
if(raffling) }
{
raffleCost = 0; public boolean joinRaffle(KittyUser user)
raffling = false; {
raffleUsersChosen.removeAll(raffleUsersChosen); if(!raffleUsersChosen.contains(user) && !raffleUsersUnchosen.contains(user) && user.getBeans() > raffleCost && raffling)
raffleUsersUnchosen.removeAll(raffleUsersUnchosen); {
return true; user.changeBeans(raffleCost);
} raffleUsersUnchosen.add(user);
return false; return true;
} }
return false;
public boolean joinRaffle(KittyUser user) }
{
if(!raffleUsersChosen.contains(user) && !raffleUsersUnchosen.contains(user) && user.getBeans() > raffleCost && raffling) public KittyUser chooseRaffleWinner()
{ {
user.changeBeans(-raffleCost); if(!raffleUsersUnchosen.isEmpty())
raffleUsersUnchosen.add(user); {
return true; KittyUser chosen = raffleUsersUnchosen.get((int) (Math.random() * raffleUsersUnchosen.size()));
} raffleUsersUnchosen.remove(chosen);
return false; raffleUsersChosen.add(chosen);
} return chosen;
}
public KittyUser chooseRaffleWinner() return null;
{ }
if(!raffleUsersUnchosen.isEmpty())
{ @Override
KittyUser chosen = raffleUsersUnchosen.get((int) (Math.random() * raffleUsersUnchosen.size())); public String serialize()
raffleUsersUnchosen.remove(chosen); {
raffleUsersChosen.add(chosen); return commandIndicator;
return chosen; }
}
return null; @Override
} public void deSerialzie(String string)
{
@Override if(string == null || string.length() == 0)
public String serialize() setCommandIndicator("!");
{ else
return commandIndicator; setCommandIndicator(string);
} }
@Override public String getCommandIndicator()
public void deSerialzie(String string) {
{ return commandIndicator;
if(string == null || string.length() == 0) }
setCommandIndicator("!");
else public void setCommandIndicator(String newIndicator)
setCommandIndicator(string); {
} if(newIndicator != commandIndicator)
{
public String getCommandIndicator() commandIndicator = newIndicator;
{ markDirty();
return commandIndicator; }
} }
}
public void setCommandIndicator(String newIndicator)
{
if(newIndicator != commandIndicator)
{
commandIndicator = newIndicator;
markDirty();
}
}
}
-18
View File
@@ -1,18 +0,0 @@
package dataStructures;
public enum KittyStartupMode
{
Dev(1), Release(2), PoguRelease(3);
private final int value;
private KittyStartupMode(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
}
@@ -0,0 +1,6 @@
package dataStructures;
public class KittyTrackedResponse
{
// TODO: Fill this out!
}

Some files were not shown because too many files have changed in this diff Show More