Java IRC bot
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

InputHandler.java 10KB

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