Java IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InputHandler.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.md87.charliebravo;
  6. import com.dmdirc.parser.irc.ChannelClientInfo;
  7. import com.dmdirc.parser.irc.ChannelInfo;
  8. import com.dmdirc.parser.irc.ClientInfo;
  9. import com.dmdirc.parser.irc.IRCParser;
  10. import com.dmdirc.parser.irc.callbacks.interfaces.IChannelMessage;
  11. import com.dmdirc.parser.irc.callbacks.interfaces.IPrivateMessage;
  12. import com.md87.charliebravo.commands.AuthenticateCommand;
  13. import com.md87.charliebravo.commands.CalcCommand;
  14. import com.md87.charliebravo.commands.FollowupsCommand;
  15. import com.md87.charliebravo.commands.GitCommand;
  16. import com.md87.charliebravo.commands.GoogleCommand;
  17. import com.md87.charliebravo.commands.HelpCommand;
  18. import com.md87.charliebravo.commands.IssueCommand;
  19. import com.md87.charliebravo.commands.NewzbinCommand;
  20. import com.md87.charliebravo.commands.QuitCommand;
  21. import com.md87.charliebravo.commands.SetCommand;
  22. import com.md87.charliebravo.commands.SkillCommand;
  23. import com.md87.charliebravo.commands.TranslateCommand;
  24. import com.md87.charliebravo.commands.WhoisCommand;
  25. import java.util.ArrayList;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.regex.Matcher;
  30. /**
  31. *
  32. * @author chris
  33. */
  34. public class InputHandler implements IChannelMessage, IPrivateMessage {
  35. protected IRCParser parser;
  36. protected final Config config;
  37. protected final List<Command> commands = new ArrayList<Command>();
  38. protected final Map<String, Response> responses = new HashMap<String, Response>();
  39. protected final Map<String, String> snippets = new HashMap<String, String>();
  40. public InputHandler(final Config config) {
  41. this.config = config;
  42. commands.add(new GoogleCommand());
  43. commands.add(new QuitCommand());
  44. commands.add(new HelpCommand());
  45. commands.add(new FollowupsCommand());
  46. commands.add(new AuthenticateCommand());
  47. commands.add(new CalcCommand());
  48. commands.add(new WhoisCommand());
  49. commands.add(new TranslateCommand());
  50. commands.add(new IssueCommand());
  51. commands.add(new GitCommand());
  52. commands.add(new SetCommand());
  53. commands.add(new SkillCommand());
  54. commands.add(new NewzbinCommand());
  55. }
  56. public Config getConfig() {
  57. return config;
  58. }
  59. public List<Command> getCommands() {
  60. return new ArrayList<Command>(commands);
  61. }
  62. public Response getLastResponse(final String target) {
  63. return responses.get(target);
  64. }
  65. public IRCParser getParser() {
  66. return parser;
  67. }
  68. public void setParser(final IRCParser parser) {
  69. this.parser = parser;
  70. parser.getCallbackManager().addCallback("OnChannelMessage", this);
  71. parser.getCallbackManager().addCallback("OnPrivateMessage", this);
  72. }
  73. public void onChannelMessage(final IRCParser tParser, final ChannelInfo cChannel,
  74. final ChannelClientInfo cChannelClient, final String sMessage, final String sHost) {
  75. for (String nick : getNicknames()) {
  76. if (sMessage.matches("^(?i)" + Matcher.quoteReplacement(nick) + "[,:!] .*")) {
  77. handleInput(ClientInfo.parseHost(sHost), cChannel.getName(),
  78. sMessage.substring(nick.length() + 2));
  79. break;
  80. } else if (sMessage.matches("^(?i)" + Matcher.quoteReplacement(nick) + "\\?")
  81. && snippets.containsKey(cChannel.getName())) {
  82. handleInput(ClientInfo.parseHost(sHost), cChannel.getName(),
  83. snippets.get(cChannel.getName()));
  84. break;
  85. }
  86. }
  87. for (Map.Entry<String, String> snippet : config.getConfigfile()
  88. .getKeyDomain("snippets").entrySet()) {
  89. System.out.println("Snippet test: " + snippet.getKey());
  90. if (sMessage.matches(snippet.getKey())) {
  91. snippets.put(cChannel.getName(), sMessage.replaceFirst(snippet.getKey(),
  92. snippet.getValue()));
  93. System.out.println("Snippet: " + snippets.get(cChannel.getName()));
  94. break;
  95. }
  96. }
  97. }
  98. protected String[] getNicknames() {
  99. return new String[] {
  100. parser.getMyNickname(),
  101. parser.getMyNickname().replaceAll("[a-z]", ""),
  102. parser.getMyNickname().replaceAll("[^a-zA-Z]", ""),
  103. parser.getMyNickname().replaceAll("[^A-Z]", ""),
  104. };
  105. }
  106. public void onPrivateMessage(final IRCParser tParser, final String sMessage, final String sHost) {
  107. handleInput(ClientInfo.parseHost(sHost), ClientInfo.parseHost(sHost), sMessage);
  108. }
  109. protected void handleInput(final String source, final String target, final String text) {
  110. new Thread(new Runnable() {
  111. public void run() {
  112. handleInputImpl(source, target, text);
  113. }
  114. }).start();
  115. }
  116. protected void handleInputImpl(final String source, final String target, final String text) {
  117. final Response response = new Response(parser, source, target);
  118. Command command = null;
  119. int index = 0;
  120. try {
  121. if (responses.containsKey(target)) {
  122. for (Followup followup : responses.get(target).getFollowups()) {
  123. if (followup.matches(text)) {
  124. command = followup;
  125. }
  126. }
  127. }
  128. if (command == null) {
  129. for (Command pcommand : commands) {
  130. if (text.toLowerCase().startsWith(pcommand.getClass()
  131. .getSimpleName().replace("Command", "").toLowerCase())) {
  132. command = pcommand;
  133. index = pcommand.getClass().getSimpleName().length() - 6;
  134. }
  135. }
  136. }
  137. if (command != null) {
  138. boolean cont = true;
  139. if (command.getClass().isAnnotationPresent(CommandOptions.class)) {
  140. final CommandOptions opts = command.getClass()
  141. .getAnnotation(CommandOptions.class);
  142. final String id = (String) parser.getClientInfoOrFake(source)
  143. .getMap().get("OpenID");
  144. if (opts.requireAuthorisation() && id == null) {
  145. response.sendMessage("You must be authorised to use that command", true);
  146. cont = false;
  147. } else if (opts.requireLevel() > -1 &&
  148. (!config.hasOption(id, "admin.level")
  149. || (Integer.valueOf(config.getOption(id, "admin.level"))
  150. < opts.requireLevel()))) {
  151. response.sendMessage("You have insufficient access to " +
  152. "use that command", true);
  153. response.addFollowup(new LevelErrorFollowup(response.getSource(),
  154. opts.requireLevel(),
  155. config.hasOption(id, "admin.level")
  156. ? Integer.valueOf(config.getOption(id, "admin.level")) : -1));
  157. cont = false;
  158. } else {
  159. int count = 0;
  160. final StringBuilder missing = new StringBuilder();
  161. for (String setting : opts.requiredSettings()) {
  162. if (!config.hasOption(id, setting)) {
  163. if (missing.length() > 0) {
  164. missing.append(", ");
  165. }
  166. count++;
  167. missing.append(setting);
  168. }
  169. }
  170. if (count > 0) {
  171. cont = false;
  172. response.sendRawMessage("You must have the following setting"
  173. + (count == 1 ? "" : "s")
  174. + " in order to use that command, " + response.getSource()
  175. + ": " + missing.toString()
  176. .replaceAll("^(.*), (.*?)$", "$1 and $2") + ".");
  177. }
  178. }
  179. }
  180. if (cont) {
  181. command.execute(this, response, text.substring(Math.min(text.length(), index)));
  182. }
  183. }
  184. } catch (Throwable ex) {
  185. response.sendMessage("an error has occured: " + ex.getMessage());
  186. response.addFollowup(new StacktraceFollowup(ex));
  187. }
  188. if (command != null) {
  189. if (response.isInheritFollows() && responses.containsKey(target)) {
  190. response.addFollowups(responses.get(target).getFollowups());
  191. }
  192. responses.put(target, response);
  193. }
  194. }
  195. protected static class LevelErrorFollowup implements Followup {
  196. private final String source;
  197. private final int required, desired;
  198. public LevelErrorFollowup(String source, int required, int desired) {
  199. this.source = source;
  200. this.required = required;
  201. this.desired = desired;
  202. }
  203. public boolean matches(String line) {
  204. return line.equalsIgnoreCase("details");
  205. }
  206. public void execute(InputHandler handler, Response response, String line) throws Exception {
  207. final boolean you = response.getSource().equals(source);
  208. response.sendMessage("that command requires level " + required
  209. + " access, but " + (you ? "you" : source) + " "
  210. + (desired == -1 ? "do" + (you ? "" : "es") + " not have any assigned level"
  211. : "only ha" + (you ? "ve" : "s") + " level " + desired));
  212. }
  213. }
  214. protected static class StacktraceFollowup implements Followup {
  215. private final Throwable ex;
  216. private final int index;
  217. public StacktraceFollowup(Throwable ex) {
  218. this(ex, 0);
  219. }
  220. public StacktraceFollowup(Throwable ex, int index) {
  221. this.ex = ex;
  222. this.index = index;
  223. }
  224. public boolean matches(String line) {
  225. return index == 0 ? line.equals("stacktrace") : line.equals("more");
  226. }
  227. public void execute(final InputHandler handler, Response response, String line) throws Exception {
  228. StringBuilder trace = new StringBuilder();
  229. int i;
  230. for (i = index; i < ex.getStackTrace().length; i++) {
  231. if (trace.length() > 0) {
  232. int next = ex.getStackTrace()[i].toString().length() + 2;
  233. if (trace.length() + next + 33 + (index == 0 ? 5 : 4)
  234. + String.valueOf(i - index).length() > response.getMaxLength()) {
  235. break;
  236. }
  237. trace.append("; ");
  238. }
  239. trace.append(ex.getStackTrace()[i].toString());
  240. }
  241. response.sendMessage("the " + (index == 0 ? "first" :
  242. i < ex.getStackTrace().length ? "next" : "last")
  243. + " " + (i - index) + " elements of the trace are: " + trace);
  244. if (i < ex.getStackTrace().length) {
  245. response.addFollowup(new StacktraceFollowup(ex, i));
  246. }
  247. }
  248. }
  249. }