quizz.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. const
  2. fs = require("fs"),
  3. readline = require("readline"),
  4. arrayPad = require('./strpad.js').arrayPad,
  5. Cache = require('./cache.js');
  6. Object.assign(global, require("./config.js"));
  7. const MySQL = USE_MYSQL ? (function() { return require("mysql2").createConnection({host: MySQL_HOST, user: MySQL_USER, database: MySQL_DB, password: MySQL_PASS}); }) : null;
  8. const HOSTNAME = require('os').hostname(); // For Mysql bot identification
  9. function Question(id, obj) {
  10. this.id = id;
  11. this.question = obj.question;
  12. this.response = obj.response;
  13. this.normalizedResponse = "";
  14. if (Array.isArray(obj.response))
  15. this.normalizedResponse = this.response.map(i => Question.normalize(i));
  16. else
  17. this.normalizedResponse = Question.normalize(this.response);
  18. }
  19. Question.normalize = function(str) {
  20. return str.normalize('NFD').replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
  21. }
  22. const QuestionType = { bool: {}, number: {}, string: {} };
  23. Question.prototype.booleanValue = function(str) {
  24. str = str || (Array.isArray(this.normalizedResponse) ? this.normalizedResponse[0] : this.normalizedResponse);
  25. var index = ["non", "oui", "faux", "vrai"].indexOf(str);
  26. if (index >= 0)
  27. return index % 2 === 1;
  28. return undefined;
  29. }
  30. Question.prototype.isBoolean = function(str) {
  31. return this.booleanValue(str) !== undefined;
  32. }
  33. String.prototype.isWord = function() {
  34. return (/\W/).exec(this) === null;
  35. }
  36. Question.prototype.getQuestionType = function() {
  37. if (this.isBoolean())
  38. return QuestionType.bool;
  39. if ((/^-?[0-9]+$/).exec(this.response))
  40. return QuestionType.number;
  41. return QuestionType.string;
  42. }
  43. Question.toHint = function(response, normalizedResponse, boundaries, responseIndex, questionType, hintLevel) {
  44. if (questionType === QuestionType.string) {
  45. if (hintLevel == 0)
  46. return normalizedResponse.replace(/[\w]/g, '*');
  47. else if (hintLevel == 1)
  48. return normalizedResponse.replace(/[\w]/g, (a, b) => b ? '*' : response.charAt(b));
  49. else if (normalizedResponse.isWord() && !responseIndex) {
  50. var displayed = [];
  51. const revealPercent = 0.1;
  52. displayed[normalizedResponse.length -2] = 1;
  53. displayed.fill(1, 0, normalizedResponse.length-1).fill(0, Math.ceil(normalizedResponse.length * revealPercent), normalizedResponse.length);
  54. displayed.sort(()=>Math.random() > 0.5?-1:1)
  55. return normalizedResponse.replace(/./g, (a, b) => b && !displayed[b -1] ? '*':response.charAt(b));
  56. }
  57. else
  58. return normalizedResponse.replace(/[\w]+/g, (a, wordIndex) => a.replace(/./g, (a, b) => b ? '*':response.charAt(wordIndex)));
  59. }
  60. else if (questionType === QuestionType.number) {
  61. const responseInt = Number(normalizedResponse),
  62. randomMin = ([ 30, 10, 3 ])[hintLevel],
  63. randomSpread = 5 * (5 -hintLevel);
  64. boundaries[0] = Math.max(
  65. Math.floor(responseInt -(Math.random() *randomSpread) -randomMin),
  66. boundaries[0]);
  67. boundaries[1] = Math.min(
  68. Math.ceil(responseInt +(Math.random() *randomSpread) +randomMin),
  69. boundaries[1]);
  70. return "Un nombre entre " +boundaries[0] +" et " +boundaries[1];
  71. }
  72. else
  73. console.error("ERROR: Unknown response type !");
  74. };
  75. Question.prototype.getHint = function(hintLevel) {
  76. var type = this.getQuestionType();
  77. if (type === QuestionType.bool)
  78. return "Vrai / Faux ?";
  79. else if (type === QuestionType.number && !this.boundaries)
  80. this.boundaries = (Number(this.response) >= 0 ? [ 0, Infinity] : [ -Infinity, 0 ]);
  81. if (!Array.isArray(this.response))
  82. return Question.toHint(this.response, this.normalizedResponse, this.boundaries, 0, type, hintLevel);
  83. var hints = [];
  84. for (var i =0, len = this.response.length; i < len; ++i)
  85. hints.push(Question.toHint(this.response[i], this.normalizedResponse[i], this.boundaries, i, type, hintLevel));
  86. return hints.length > 1 ? ("Plusieures reponses acceptees: " +hints.join(" ou ")) : hints[0];
  87. return hints.join(" ou ");
  88. }
  89. Question.prototype.check = function(response) {
  90. response = Question.normalize(response);
  91. var boolValue = this.booleanValue();
  92. if (boolValue !== undefined)
  93. return boolValue === this.booleanValue(response);
  94. if (Array.isArray(this.normalizedResponse))
  95. return this.normalizedResponse.indexOf(response) >= 0;
  96. return response === this.normalizedResponse;
  97. }
  98. Question.prototype.end = function() {
  99. if (this.boundaries)
  100. delete this.boundaries;
  101. }
  102. const ScoreUtils = (function() {
  103. const getRank = function(pseudo) {
  104. pseudo = pseudo.toLowerCase();
  105. for (var i =0, len = this.length; i < len; ++i)
  106. if (this[i].name.toLowerCase() === pseudo)
  107. return i +1;
  108. return null;
  109. };
  110. const withScore = function(score) {
  111. return this.filter(i => i.score === score);
  112. };
  113. const diff = function(pseudo, pointIncrement) {
  114. var oldIndex = this.getRank(pseudo) -1,
  115. score = pointIncrement;
  116. if (oldIndex < 0) {
  117. oldIndex = this.length;
  118. this.push({name: pseudo, score: pointIncrement});
  119. } else {
  120. this[oldIndex].score += pointIncrement;
  121. score = this[oldIndex].score;
  122. }
  123. scores = this.sort((a, b) => b.score - a.score);
  124. var newIndex = this.getRank(pseudo) -1;
  125. var result = { newRank: newIndex +1, oldRank: oldIndex +1 };
  126. result.exaequo = this.filter(i => i.score === score && i.name !== pseudo);
  127. if (newIndex < 0 || newIndex === oldIndex)
  128. return result;
  129. result.users = this.slice(newIndex +1, oldIndex +1);
  130. return result;
  131. };
  132. return {
  133. buildScoreArray: function(quizzBot, filter, limit) {
  134. var scores = [];
  135. for (var i in quizzBot.users)
  136. if (!filter || filter(i))
  137. scores.push({name: quizzBot.users[i].name, score: quizzBot.users[i].score});
  138. scores = scores.sort((a, b) => b.score - a.score);
  139. if (limit !== undefined)
  140. scores = scores.slice(0, limit);
  141. scores.getRank = getRank.bind(scores);
  142. scores.usersWithScore = withScore.bind(scores);
  143. scores.diff = diff.bind(scores);
  144. return scores;
  145. }
  146. };
  147. })();
  148. function initQuestionList(filename) {
  149. return new Promise((ok, ko) => {
  150. console.info("INFO: Reloading question db");
  151. var stream = fs.createReadStream(filename),
  152. reader = readline.createInterface({input: stream}),
  153. questions = [],
  154. lineNo = 0,
  155. borken = false;
  156. reader.on("line", line => {
  157. if (borken) return;
  158. try {
  159. const firstChar = line.charAt(0);
  160. if ([';', '#'].indexOf(firstChar) >= 0) {
  161. ++lineNo;
  162. return;
  163. }
  164. var question = new Question(++lineNo, JSON.parse(line));
  165. if (question.question && question.response)
  166. questions.push(question);
  167. } catch (e) {
  168. console.error("ERROR: Failed to load Database: ", e, "on line", lineNo);
  169. borken = true;
  170. reader.close();
  171. stream.destroy();
  172. ko("Failed to load database: syntax error on question #" +lineNo);
  173. }
  174. });
  175. reader.on("close", () => {
  176. if (!borken)
  177. ok(questions);
  178. });
  179. });
  180. }
  181. function QuizzBot(config) {
  182. this.config = config;
  183. }
  184. QuizzBot.prototype.init = function(bot, chanName) {
  185. const previousData = Cache.GetData();
  186. this.room = chanName;
  187. this.bot = bot;
  188. this.init = false;
  189. this.users = {};
  190. this.activeUsers = {};
  191. if (previousData) {
  192. for (var i in previousData.scores) {
  193. this.users[i.toLowerCase()] = bot.createUser(i);
  194. this.users[i.toLowerCase()].score = previousData.scores[i];
  195. }
  196. }
  197. this.mySQLExportWrapper();
  198. }
  199. QuizzBot.prototype.onSelfJoin = function() {
  200. this.init = true;
  201. this.reloadDb();
  202. }
  203. QuizzBot.prototype.onJoin = function(nick) {
  204. this.users[nick.toLowerCase()] = this.users[nick.toLowerCase()] || this.bot.createUser(nick);
  205. this.activeUsers[nick.toLowerCase()] = true;
  206. if (this.currentQuestion)
  207. this.bot.sendNotice(nick, this.currentQuestion.question);
  208. }
  209. QuizzBot.prototype.onNameList = function(nicks) {
  210. this.activeUsers = {};
  211. for (var i in nicks) {
  212. var u = this.users[i.toLowerCase()] = (this.users[i.toLowerCase()] || this.bot.createUser(i));
  213. u.setModeChar(nicks[i]);
  214. this.activeUsers[i.toLowerCase()] = true;
  215. }
  216. }
  217. QuizzBot.prototype.onNickPart = function(nick) {
  218. delete this.activeUsers[nick.toLowerCase()];
  219. }
  220. QuizzBot.prototype.onRename = function(oldNick, newNick) {
  221. this.users[newNick.toLowerCase()] = this.users[newNick.toLowerCase()] || this.bot.createUser(newNick);
  222. this.users[newNick.toLowerCase()].isAdmin = this.users[oldNick.toLowerCase()] && this.users[oldNick.toLowerCase()].isAdmin;
  223. this.activeUsers[newNick.toLowerCase()] = true;
  224. delete this.activeUsers[oldNick.toLowerCase()];
  225. }
  226. QuizzBot.prototype.onMessage = function(user, text) {
  227. this.users[user.toLowerCase()] && this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
  228. }
  229. QuizzBot.prototype.onRemMode = function(user, mode) {
  230. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].unsetMode(mode);
  231. }
  232. QuizzBot.prototype.onAddMode = function(user, mode) {
  233. if (user === this.name) {
  234. usersToVoice = [];
  235. for (var i in this.users) {
  236. if (this.users[i].score && this.activeUsers[i])
  237. usersToVoice.push(i);
  238. }
  239. this.bot.voice(this.room, usersToVoice);
  240. } else {
  241. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].setMode(mode);
  242. }
  243. }
  244. QuizzBot.prototype.stop = function() {
  245. this.timer && clearTimeout(this.timer);
  246. this.timer = null;
  247. this.currentQuestion = null;
  248. this.currentHint = 0;
  249. }
  250. QuizzBot.prototype.onTick = function() {
  251. if (!this.currentQuestion)
  252. return;
  253. if (this.currentHint < 3)
  254. this.sendNextHint(false);
  255. else {
  256. var response = Array.isArray(this.currentQuestion.response) ?
  257. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  258. this.currentQuestion.response;
  259. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +response);
  260. this.nextQuestionWrapper();
  261. }
  262. }
  263. QuizzBot.prototype.resetTimer = function() {
  264. this.timer && clearTimeout(this.timer);
  265. this.timer = setInterval(this.onTick.bind(this), this.config.AUTO_HINT_DELAY);
  266. }
  267. QuizzBot.prototype.sendNextHint = function(resetTimer) {
  268. this.bot.sendMsg(this.room, this.currentQuestion.getHint(this.currentHint));
  269. ++this.currentHint;
  270. this.lastHint = Date.now();
  271. resetTimer !== false && this.resetTimer();
  272. }
  273. QuizzBot.prototype.nextQuestionWrapper = function() {
  274. this.previousQuestion = this.currentQuestion ? this.currentQuestion.id : null;
  275. this.currentQuestion.end();
  276. this.currentQuestion = null;
  277. setTimeout(this.nextQuestion.bind(this), this.config.NEXT_QUESTION_DELAY);
  278. }
  279. QuizzBot.prototype.nextQuestion = function() {
  280. this.currentQuestion = this.questions[Math.floor(Math.random() * this.questions.length)];
  281. console.debug("DEBUG: " +JSON.stringify(this.currentQuestion));
  282. this.currentHint = 0;
  283. this.questionDate = Date.now();
  284. this.bot.sendMsg(this.room, "#" +this.currentQuestion.id +" " +this.currentQuestion.question);
  285. this.sendNextHint();
  286. }
  287. QuizzBot.prototype.start = function() {
  288. if (this.reloading) {
  289. this.bot.sendMsg(this.room, "Error: database still reloading");
  290. return;
  291. }
  292. if (!this.currentQuestion) {
  293. this.nextQuestion();
  294. }
  295. }
  296. QuizzBot.prototype.reloadDb = function() {
  297. var _this = this;
  298. this.stop();
  299. this.reloading = true;
  300. initQuestionList(this.config.QUESTIONS_PATH).then(questions => {
  301. _this.reloading = false;
  302. _this.questions = questions;
  303. _this.bot.sendMsg(this.room, questions.length +" questions loaded from database");
  304. _this.start();
  305. }).catch(err => {
  306. console.error(err);
  307. _this.bot.sendMsg(this.room, err);
  308. });
  309. }
  310. QuizzBot.prototype.delScore = function(user) {
  311. var data = this.users[user.toLowerCase()];
  312. if (!data) {
  313. this.bot.sendMsg(this.room, "User not found...");
  314. return;
  315. }
  316. if (!data.score) {
  317. this.bot.sendMsg(this.room, "Score for user already null");
  318. return;
  319. }
  320. data.score = 0;
  321. this.bot.sendMsg(this.room, "Removed score");
  322. Cache.SetScores(this.users);
  323. }
  324. QuizzBot.prototype.sumScores = function(onlyPresent) {
  325. var score = 0;
  326. for (var i in this.users)
  327. score += (this.users[i].score && (this.activeUsers[i] || !onlyPresent)) ? this.users[i].score : 0;
  328. return score;
  329. }
  330. QuizzBot.prototype.sendScore = function(onlyPresent) {
  331. var scores = ScoreUtils.buildScoreArray(this, user => this.users[user].score && (this.activeUsers[user] || !onlyPresent), 10);
  332. if (scores.length == 0) {
  333. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  334. return;
  335. }
  336. var index = 0;
  337. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  338. if (scoreLines[0].length < 30) {
  339. // merge score lines 2 by 2
  340. var tmp = [];
  341. for (var i =0, len = scoreLines.length; i < len; i += 2)
  342. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  343. scoreLines = tmp;
  344. }
  345. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  346. }
  347. QuizzBot.prototype.computeScore = function(username) {
  348. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response,
  349. responseMsg = "Réponse `" +rep +"` trouvée en " +Math.floor((Date.now() -this.questionDate) / 1000) +" secondes ";
  350. if (this.currentHint <= 1)
  351. responseMsg += "sans indice";
  352. else if (this.currentHint === 2)
  353. responseMsg += "avec 1 seul indice";
  354. else
  355. responseMsg += "avec " +this.currentHint +" indices";
  356. var score = 4 - this.currentHint;
  357. this.bot.sendMsg(this.room, responseMsg);
  358. return score;
  359. }
  360. QuizzBot.prototype.findQuestionById = function(qId) {
  361. for (var i =0, len = this.questions.length; i < len; ++i) {
  362. if (this.questions[i].id === qId)
  363. return this.questions[i];
  364. if (this.questions[i].id > qId)
  365. break;
  366. }
  367. }
  368. QuizzBot.prototype.resetScores = function() {
  369. if (this.sumScores(false) > 0) {
  370. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  371. this.sendScore(false);
  372. }
  373. for (var i in this.users)
  374. this.users[i].score = 0;
  375. Cache.SetScores({});
  376. }
  377. /**
  378. * This function is called when a user answer right,
  379. * @param diff an object containing the new rank, the previous rank, and an
  380. * array containing all the users having been overpassed
  381. * @return a string with a message to be displayed or null if nothing to say
  382. **/
  383. QuizzBot.prototype.buildOverpassedMessage = function(username, diff) {
  384. var exaequo = null;
  385. if (diff.exaequo.length)
  386. exaequo = " est aux coude a coude avec " +diff.exaequo.map(i => i.name).join(", ");
  387. if (!diff.users || !diff.users.length)
  388. return exaequo ? (username +exaequo) : null;
  389. exaequo = exaequo ? (" et" +exaequo) : null;
  390. const rankStr = diff.newRank == 1 ? "1ere" : `${diff.newRank}eme`;
  391. if (diff.users.length > 1) // Advanced too much rank at once ! Only display new position
  392. return `${username} prend la ${rankStr} place ` +(exaequo || "!");
  393. const looser = diff.users[0].name,
  394. insults = [
  395. () => `${username} prend la ${rankStr} place en doublant allegrement ${looser}`,
  396. () => `${username} fait un gros pied de nez a ${looser} en prennant la ${rankStr} place`,
  397. () => `${username} prends la ${rankStr} place et fait mordre la poussière à ${looser}`,
  398. () => `${looser} est maintenant dans le sillage de ${username} qui lui a piqué la ${rankStr} place`,
  399. () => `${username} envoie ${looser} dans les méandres de la loose en lui prenant la ${rankStr} place`,
  400. () => `${looser} est maintenant visible en tout petit dans le rétroviseur de ${username} qui lui a piqué la ${rankStr} place`,
  401. () => `La ${rankStr} place est maintenant la propriété de ${username} qui a envoyé ${looser} au tapis`,
  402. () => `${username} tatoue un gros L de la loose sur le front de ${looser} qui vient de perdre la ${rankStr} place`
  403. ];
  404. var insultStr = insults[Math.floor(Math.random() * insults.length)]();
  405. return insultStr +(exaequo || "!");
  406. }
  407. QuizzBot.prototype.onMessageInternal = function(username, user, msg) {
  408. const lmsg = msg.toLowerCase();
  409. if (lmsg.startsWith("!reload")) {
  410. if (user.admin)
  411. this.reloadDb();
  412. else
  413. this.bot.sendMsg(this.room, "Must be channel operator");
  414. }
  415. else if (lmsg.startsWith("!help")) {
  416. this.bot.sendMsg(this.room, "Besoin d'aide ? La liste des commandes utiles est sur ce site : https://git.knacki.info/irc.knacki.info/ircbot-quizz/src/master/quizz.md");
  417. }
  418. else if (lmsg === "!indice" || lmsg === "!conseil") {
  419. if (this.currentQuestion) {
  420. if (this.currentHint < 3) {
  421. if (Date.now() -this.lastHint > this.config.MIN_HINT_DELAY)
  422. this.sendNextHint();
  423. }
  424. else
  425. this.bot.sendMsg(this.room, "Pas plus d'indice...");
  426. }
  427. }
  428. else if (lmsg === "!next") {
  429. if (user.admin) {
  430. if (!this.currentQuestion)
  431. return;
  432. var response = Array.isArray(this.currentQuestion.response) ?
  433. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  434. this.currentQuestion.response;
  435. this.bot.sendMsg(this.room, "La réponse était: " +response);
  436. this.nextQuestionWrapper();
  437. } else {
  438. this.bot.sendMsg(this.room, "Must be channel operator");
  439. }
  440. }
  441. else if (lmsg.startsWith("!report list")) {
  442. if (user.admin) {
  443. var questions = Cache.getReportedQuestions(),
  444. questionObj = {};
  445. for (var questionId in questions) {
  446. questionObj[questionId] = {};
  447. for (var _username in questions[questionId])
  448. questionObj[questionId][_username] = new Date(questions[questionId][_username]).toLocaleString();
  449. }
  450. this.bot.sendNotice(username, JSON.stringify(questionObj));
  451. }
  452. else
  453. this.bot.sendMsg(this.room, "Must be channel operator");
  454. }
  455. else if (lmsg == ("!report clear")) {
  456. if (user.admin) {
  457. Cache.clearReports();
  458. this.bot.sendMsg(this.room, "Toutes les questions sont marquées comme restaurées");
  459. }
  460. else
  461. this.bot.sendMsg(this.room, "Must be channel operator");
  462. }
  463. else if (lmsg.startsWith("!report del ")) {
  464. var questionId = msg.substr("!report del ".length).trim();
  465. if (questionId.startsWith('#'))
  466. questionId = questionId.substr(1);
  467. questionId = Number(questionId);
  468. if (isNaN(questionId)) {
  469. this.bot.sendMsg(this.room, "Erreur: Usage: !report del #1234");
  470. return;
  471. }
  472. if (user.admin) {
  473. Cache.unreportQuestion(questionId);
  474. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  475. } else if (Cache.isReportedBy(questionId, username)) {
  476. Cache.unreportQuestion(questionId, username);
  477. this.bot.sendMsg(this.room, "Question #" +questionId +" n'est plus marquée comme défectueuse par " +username);
  478. } else {
  479. this.bot.sendMsg(this.room, "Must be channel operator");
  480. }
  481. }
  482. else if (lmsg === "!report prev") {
  483. if (!this.previousQuestion) {
  484. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  485. } else {
  486. Cache.reportQuestion(this.previousQuestion, username);
  487. this.bot.sendMsg(this.room, "Question #" +this.previousQuestion +" marquée comme défectueuse par " +username);
  488. }
  489. }
  490. else if (lmsg === "!report current") {
  491. if (!this.currentQuestion) {
  492. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  493. } else {
  494. Cache.reportQuestion(this.currentQuestion.id, username);
  495. this.bot.sendMsg(this.room, "Question #" +this.currentQuestion.id +" marquée comme défectueuse par " +username);
  496. }
  497. }
  498. else if (lmsg.startsWith("!report ")) {
  499. var questionId = msg.substr("!report ".length).trim();
  500. if (questionId.startsWith('#'))
  501. questionId = questionId.substr(1);
  502. questionId = Number(questionId);
  503. if (isNaN(questionId)) {
  504. this.bot.sendMsg(this.room, "Erreur: Usage: !report #1234");
  505. return;
  506. }
  507. if (!this.findQuestionById(questionId))
  508. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  509. else {
  510. Cache.reportQuestion(questionId, username);
  511. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme défectueuse par " +username);
  512. }
  513. }
  514. else if (lmsg.startsWith("!rename ")) {
  515. if (!user.admin) {
  516. this.bot.sendMsg(this.room, "Must be channel operator");
  517. return;
  518. }
  519. var args = (msg.split(/\s+/)).splice(1);
  520. if (args.length < 2) {
  521. this.bot.sendNotice(username, "Usage: !rename nouveau_pseudo ancien_pseudo [ancien_pseudo...]");
  522. return;
  523. }
  524. var sum = 0,
  525. users = [],
  526. target = args[0];
  527. args = args.map(username => username.toLowerCase());
  528. var userToMod = null;
  529. for (var i in this.users) {
  530. var userIndex = args.indexOf(i.toLowerCase());
  531. if (userIndex > 0) {
  532. sum += this.users[i].score;
  533. this.users[i].score = 0;
  534. if (!this.activeUsers[i])
  535. delete this.users[i];
  536. }
  537. else if (userIndex == 0)
  538. userToMod = this.users[i];
  539. }
  540. if (!userToMod) {
  541. userToMod = this.users[target] = this.bot.createUser(target);
  542. this.bot.sendMsg(this.room, "Created user " +target +" with " +sum +" points");
  543. } else if (sum) {
  544. this.bot.sendMsg(this.room, "Added " +sum +" points to " +target);
  545. }
  546. userToMod.score += sum;
  547. Cache.SetScores(this.users);
  548. }
  549. else if (lmsg === "!score all") {
  550. if (!user.admin) {
  551. this.bot.sendMsg(this.room, "Must be channel operator");
  552. return;
  553. }
  554. var scores = [];
  555. for (var i in this.users)
  556. this.users[i].score && scores.push({name: this.users[i].name, score: this.users[i].score});
  557. if (scores.length == 0) {
  558. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  559. return;
  560. }
  561. scores = scores.sort((a, b) => b.score - a.score);
  562. this.bot.sendNotice(username, scores.map(i => i.name+":"+i.score).join(", "));
  563. }
  564. else if (lmsg.startsWith("!points")) {
  565. var who = lmsg.substr("!points".length).trim().split(/\s+/)[0];
  566. if (!who || !who.length) {
  567. this.bot.sendMsg(this.room, "Usage: !points <pseudo>");
  568. return;
  569. }
  570. who = who.trim().toLowerCase();
  571. if (!this.users[who] || !this.users[who].score) {
  572. this.bot.sendMsg(this.room, "Pas de points pour " +who);
  573. return;
  574. }
  575. var arr = ScoreUtils.buildScoreArray(this),
  576. rank = arr.getRank(who);
  577. var exaequo = arr.usersWithScore(arr[rank-1].score).filter(i => i.name.toLowerCase() !== who).map(i => i.name).join(", ");
  578. exaequo = exaequo.length ? (", exaequo avec " +exaequo) : ".";
  579. if (rank === 0)
  580. this.bot.sendMsg(this.room, `${arr[rank-1].name} est en tête avec ${arr[rank-1].score} points${exaequo}`);
  581. else
  582. this.bot.sendMsg(this.room, `${arr[rank-1].name} est en ${rank}eme position avec ${arr[rank-1].score} points${exaequo}`);
  583. }
  584. else if (lmsg === "!score" || lmsg === "!top") {
  585. this.sendScore(false);
  586. }
  587. else if (this.currentQuestion) {
  588. var dieOnFailure = this.currentQuestion.isBoolean() && this.currentQuestion.isBoolean(Question.normalize(msg));
  589. if (this.currentQuestion.check(msg)) {
  590. const nbPts = this.computeScore(username);
  591. var overpassedMessage = this.buildOverpassedMessage(username, ScoreUtils.buildScoreArray(this, i => this.users[i].score).diff(username, nbPts));
  592. user.score += nbPts;
  593. Cache.SetScores(this.users);
  594. this.bot.sendMsg(this.room, nbPts +" points pour " +username +", qui cumule un total de " +user.score +" points !");
  595. overpassedMessage && this.bot.sendMsg(this.room, overpassedMessage);
  596. this.bot.voice(this.room, username);
  597. this.nextQuestionWrapper();
  598. }
  599. else if (dieOnFailure) {
  600. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response;
  601. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +rep);
  602. this.nextQuestionWrapper();
  603. }
  604. }
  605. };
  606. QuizzBot.prototype.mySQLExportWrapper = function() {
  607. if (!USE_MYSQL)
  608. return;
  609. var msRemaining = 0,
  610. lastMySQLExport = Cache.getLastMysqlSave();
  611. if (lastMySQLExport)
  612. msRemaining = this.config.GAME_DURATION -(Date.now() -lastMySQLExport);
  613. if (msRemaining <= 0)
  614. this.mySQLExport();
  615. else
  616. this.exportScoresTimer = setTimeout(this.mySQLExportWrapper.bind(this), Math.min(2147483000, msRemaining));
  617. }
  618. QuizzBot.prototype.mySQLExport = function() {
  619. this.exportScores().then(() => {
  620. Cache.setExportTs();
  621. this.resetScores();
  622. console.info("INFO: Successfully exported scores to MySQL");
  623. this.mySQLExportWrapper();
  624. }).catch((errString) => {
  625. console.error("ERROR: mySQL Export error saving to database: ", errString);
  626. });
  627. }
  628. QuizzBot.prototype.exportScores = function() {
  629. console.info("INFO: Start exporting scores");
  630. return new Promise((ok, ko) => {
  631. if (!MySQL)
  632. return ko();
  633. var ts = Cache.getLastMysqlSave() || this.config.START_TIME;
  634. mySQL = MySQL();
  635. ts = Math.floor(ts / 1000) *1000;
  636. ts = mySQL.escape(new Date(ts));
  637. ts = ts.substr(1, ts.length -2);
  638. var sep = ts.lastIndexOf('.');
  639. if (sep > 12) ts = ts.substr(0, sep);
  640. var toSave = [];
  641. for (var i in this.users)
  642. if (this.users[i].score) {
  643. toSave.push(this.users[i].name);
  644. toSave.push(this.users[i].score);
  645. }
  646. if (toSave.length == 0) {
  647. mySQL.end();
  648. return ok();
  649. }
  650. mySQL.execute("INSERT INTO " +this.config.MySQL_PERIOD_TABLE +" (start, host) VALUES(?, ?)", [ts, HOSTNAME], (err, result) => {
  651. if (err || !result.insertId) {
  652. mySQL.end();
  653. return ko(err || "Cannot get last inserted id");
  654. }
  655. mySQL.execute("INSERT INTO " +this.config.MySQL_SCORES_TABLE +"(period_id, pseudo, score) VALUES " +(",("+result.insertId+",?,?)").repeat(toSave.length /2).substr(1), toSave, (err) => {
  656. mySQL.end();
  657. if (err)
  658. ko(err);
  659. else
  660. ok();
  661. });
  662. });
  663. });
  664. }
  665. module.exports = QuizzBot;