PageRenderTime 34ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/TrivialBot/src/trivialbot/MyTriviaBot.java

http://trivialbot.googlecode.com/
Java | 289 lines | 233 code | 36 blank | 20 comment | 39 complexity | 73e3362693209773c439c51e21b0b54f MD5 | raw file
  1. /*
  2. * TrivialBot
  3. *
  4. * http://code.google.com/p/trivialbot/
  5. *
  6. * Copyright (C) 2011 - TrivialBot
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package trivialbot;
  22. import java.io.IOException;
  23. import java.util.ArrayList;
  24. import java.util.HashMap;
  25. import java.util.Map.Entry;
  26. import java.util.Random;
  27. import java.util.Set;
  28. import java.util.Timer;
  29. import java.util.TimerTask;
  30. import java.util.logging.Level;
  31. import java.util.logging.Logger;
  32. import org.jibble.pircbot.Colors;
  33. import org.jibble.pircbot.IrcException;
  34. import org.jibble.pircbot.PircBot;
  35. import org.jibble.pircbot.User;
  36. public class MyTriviaBot extends PircBot {
  37. private String channel;
  38. private String adminName;
  39. private boolean gameInProgress = false;
  40. private ArrayList<Question> questions = null;
  41. private HashMap<String, Integer> scores = new HashMap<String, Integer>();
  42. private Random rand = new Random(System.currentTimeMillis());
  43. private String expectedAnswer = "";
  44. private final int warningStep;
  45. private final int questionTimeout;
  46. private long questionAskedAt;
  47. private int allowedConsecutiveTimeouts;
  48. private long currentConsecutiveTimeouts = 0;
  49. private Timer timer = new Timer();
  50. public MyTriviaBot(String hostname, String channelName, String channelPassword,
  51. String name, String adminName, ArrayList<Question> questions,
  52. int questionTimeout,
  53. int warningStep, int allowedConsecutiveTimeouts) throws IOException, IrcException {
  54. setAutoNickChange(true);
  55. setName(name);
  56. this.adminName = adminName;
  57. this.questions = questions;
  58. this.questionTimeout = questionTimeout;
  59. this.warningStep = warningStep;
  60. this.channel = channelName;
  61. this.allowedConsecutiveTimeouts = allowedConsecutiveTimeouts;
  62. connect(hostname);
  63. if (channelPassword == null) {
  64. joinChannel(channelName);
  65. } else {
  66. joinChannel(channelName, channelPassword);
  67. }
  68. System.out.println("Connected to: " + getServer());
  69. }
  70. @Override
  71. protected void onJoin(String channel, String sender, String login,
  72. String hostname) {
  73. super.onJoin(channel, sender, login, hostname);
  74. if (sender.equals(getNick())) {
  75. System.out.println("Joined channel: " + getChannels()[0]);
  76. sendMessage(channel, Colors.BOLD + "Hello World !");
  77. sendMessage(channel, Colors.BOLD + "My name is TrivialBot, i am apparently a trivial bot !");
  78. sendMessage(channel, Colors.BOLD + "Type !help for a list of available commands");
  79. final String f = channel;
  80. }
  81. }
  82. @Override
  83. protected void onMessage(String channel, String sender, String login, String hostname, String message) {
  84. super.onMessage(channel, sender, login, hostname, message);
  85. if (!gameInProgress) {
  86. if (!sender.equals(adminName)) {
  87. if (message.equals("!start")
  88. || message.equals("!stop")
  89. || message.equals("!skip")
  90. || message.equals("!stat")
  91. || message.equals("!disconnect")
  92. || message.equals("!help")) {
  93. sendMessage(channel, Colors.BOLD + "Sorry " + sender + ", only admin can issue commands");
  94. }
  95. return;
  96. }
  97. if (message.equals("!stop")) {
  98. currentConsecutiveTimeouts = 0;
  99. sendMessage(channel, Colors.BOLD + "huh? Stop what?! start a game first !");
  100. return;
  101. }
  102. if (message.equals("!skip")) {
  103. currentConsecutiveTimeouts = 0;
  104. sendMessage(channel, Colors.BOLD + "huh? Skip what?! start a game first !");
  105. return;
  106. }
  107. if (message.equals("!start")) {
  108. currentConsecutiveTimeouts = 0;
  109. sendMessage(channel, Colors.BOLD + "Game started !");
  110. sendMessage(channel, Colors.BOLD + "--> Play fair, don't cheat ! <--");
  111. gameInProgress = true;
  112. User[] users = getUsers(channel);
  113. for (int i = 0; i < users.length; i++) {
  114. if (!users[i].getNick().equals(getNick())) {
  115. scores.put(users[i].getNick(), 0);
  116. }
  117. }
  118. sendRandomQuestion();
  119. return;
  120. }
  121. } else {
  122. if (message.equals("!start")) {
  123. if (!sender.equals(adminName)) {
  124. sendMessage(channel, Colors.BOLD + "Sorry " + sender + ", only admin can issue commands");
  125. return;
  126. }
  127. currentConsecutiveTimeouts = 0;
  128. sendMessage(channel, Colors.BOLD + "A game is already in progress");
  129. gameInProgress = false;
  130. return;
  131. }
  132. if (message.equals("!stop")) {
  133. if (!sender.equals(adminName)) {
  134. sendMessage(channel, Colors.BOLD + "Sorry " + sender + ", only admin can issue commands");
  135. return;
  136. }
  137. currentConsecutiveTimeouts = 0;
  138. sendMessage(channel, Colors.BOLD + "Game ended !");
  139. gameInProgress = false;
  140. timer.cancel();
  141. return;
  142. }
  143. if (message.equals("!skip")) {
  144. if (!sender.equals(adminName)) {
  145. sendMessage(channel, Colors.BOLD + "Sorry " + sender + ", only admin can issue commands");
  146. return;
  147. }
  148. currentConsecutiveTimeouts = 0;
  149. sendMessage(channel, Colors.BOLD + "Skipping this question");
  150. sendRandomQuestion();
  151. return;
  152. }
  153. if (!message.startsWith("!")) {
  154. if (message.equalsIgnoreCase(expectedAnswer)) {
  155. Integer score = scores.get(sender);
  156. if (score != null) {
  157. currentConsecutiveTimeouts = 0;
  158. expectedAnswer = null;
  159. sendMessage(channel, Colors.BOLD + sender + ", Correct answer ! Your current score: " + (score.intValue() + 1));
  160. scores.put(sender, score.intValue() + 1);
  161. sendRandomQuestion();
  162. }
  163. }
  164. return;
  165. }
  166. }
  167. if (!sender.equals(adminName)) {
  168. sendMessage(channel, Colors.BOLD + "Sorry " + sender + ", only admin can issue commands");
  169. return;
  170. } else {
  171. if (message.equals("!help")) {
  172. currentConsecutiveTimeouts = 0;
  173. sendMessage(channel, Colors.BOLD + "~~~~ List of my trivial commands ~~~~");
  174. sendMessage(channel, Colors.BOLD + "!help: shows this list of commands ... obviously");
  175. sendMessage(channel, Colors.BOLD + "!start: starts a trivia game with current users in channel");
  176. sendMessage(channel, Colors.BOLD + "!stop: stops the current game");
  177. sendMessage(channel, Colors.BOLD + "!skip: skips the current question");
  178. sendMessage(channel, Colors.BOLD + "!stat: shows the scoreboard");
  179. sendMessage(channel, Colors.BOLD + "!disconnect: kills me !");
  180. sendMessage(channel, Colors.BOLD + "~~~~ List of my trivial commands ~~~~");
  181. return;
  182. }
  183. if (message.equals("!disconnect")) {
  184. sendMessage(channel, Colors.BOLD + "gtg .. see you around, bye !");
  185. timer.cancel();
  186. try {
  187. Thread.sleep(1000);
  188. } catch (InterruptedException ex) {
  189. Logger.getLogger(MyTriviaBot.class.getName()).log(Level.SEVERE, null, ex);
  190. }
  191. disconnect();
  192. System.out.println("Disconnected");
  193. System.out.println("Quitting .. bye !");
  194. System.exit(0);
  195. }
  196. if (message.equals("!stat")) {
  197. currentConsecutiveTimeouts = 0;
  198. sendMessage(channel, Colors.BOLD + "~~~~ Scoreboard ~~~~");
  199. Set<Entry<String, Integer>> scoresSet = scores.entrySet();
  200. if (scores.isEmpty()) {
  201. sendMessage(channel, Colors.BOLD + "No scores ..");
  202. } else {
  203. for (Entry<String, Integer> score : scoresSet) {
  204. if (score.getValue() != 0) {
  205. sendMessage(channel, Colors.BOLD + score.getKey() + ": " + score.getValue());
  206. }
  207. }
  208. }
  209. sendMessage(channel, Colors.BOLD + "~~~~ Scoreboard ~~~~");
  210. return;
  211. }
  212. }
  213. }
  214. @Override
  215. protected void onNickChange(String oldNick, String login, String hostname, String newNick) {
  216. scores.put(newNick, scores.get(oldNick));
  217. scores.remove(oldNick);
  218. }
  219. private void sendRandomQuestion() {
  220. Question question = questions.get(rand.nextInt(questions.size()));
  221. expectedAnswer = question.getAnswer();
  222. sendMessage(channel, Colors.BOLD + question.getQuestion());
  223. questionAskedAt = System.currentTimeMillis();
  224. timer.cancel();
  225. timer = new Timer();
  226. timer.schedule(new TimerTask() {
  227. @Override
  228. public void run() {
  229. sendMessage(channel, Colors.BOLD + "Timeout! The correct answer was: " + expectedAnswer);
  230. currentConsecutiveTimeouts++;
  231. if (currentConsecutiveTimeouts >= allowedConsecutiveTimeouts) {
  232. sendMessage(channel, Colors.BOLD
  233. + "Too many timeouts, TrivialBot will disconnect");
  234. try {
  235. Thread.sleep(1000);
  236. } catch (InterruptedException ex) {
  237. Logger.getLogger(MyTriviaBot.class.getName()).log(Level.SEVERE, null, ex);
  238. }
  239. disconnect();
  240. System.out.println("Reached maximum consecutive timeouts, TrivialBot will exit");
  241. System.exit(0);
  242. }
  243. sendRandomQuestion();
  244. }
  245. }, questionTimeout * 1000, questionTimeout * 1000);
  246. timer.schedule(new TimerTask() {
  247. @Override
  248. public void run() {
  249. sendMessage(channel, Colors.BOLD + (questionTimeout - ((System.currentTimeMillis() - questionAskedAt)) / 1000) + " seconds remaining");
  250. }
  251. }, warningStep * 1000, warningStep * 1000);
  252. }
  253. }