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

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