quizz.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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("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. for (var i =0, len = this.length; i < len; ++i)
  105. if (this[i].name === pseudo)
  106. return i +1;
  107. return null;
  108. };
  109. const diff = function(pseudo, pointIncrement) {
  110. var oldIndex = this.getRank(pseudo) -1,
  111. score = pointIncrement;
  112. if (oldIndex < 0) {
  113. oldIndex = this.length;
  114. this.push({name: pseudo, score: pointIncrement});
  115. } else {
  116. this[oldIndex].score += pointIncrement;
  117. score = this[oldIndex].score;
  118. }
  119. scores = this.sort((a, b) => b.score - a.score);
  120. var newIndex = this.getRank(pseudo) -1;
  121. var result = { newRank: newIndex +1, oldRank: oldIndex +1 };
  122. if (newIndex < 0 || newIndex === oldIndex)
  123. return result;
  124. result.users = this.slice(newIndex +1, oldIndex +1);
  125. return result;
  126. };
  127. return {
  128. buildScoreArray: function(quizzBot, filter, limit) {
  129. var scores = [];
  130. for (var i in quizzBot.users)
  131. if (filter(i))
  132. scores.push({name: quizzBot.users[i].name, score: quizzBot.users[i].score});
  133. scores = scores.sort((a, b) => b.score - a.score);
  134. if (limit !== undefined)
  135. scores = scores.slice(0, limit);
  136. scores.getRank = getRank.bind(scores);
  137. scores.diff = diff.bind(scores);
  138. return scores;
  139. }
  140. };
  141. })();
  142. function initQuestionList(filename) {
  143. return new Promise((ok, ko) => {
  144. console.log("Reloading question db");
  145. var stream = fs.createReadStream(filename),
  146. reader = readline.createInterface({input: stream}),
  147. questions = [],
  148. lineNo = 0,
  149. borken = false;
  150. reader.on("line", line => {
  151. if (borken) return;
  152. try {
  153. const firstChar = line.charAt(0);
  154. if ([';', '#'].indexOf(firstChar) >= 0) {
  155. ++lineNo;
  156. return;
  157. }
  158. var question = new Question(++lineNo, JSON.parse(line));
  159. if (question.question && question.response)
  160. questions.push(question);
  161. } catch (e) {
  162. console.error("Failed to load Database: ", e, "on line", lineNo);
  163. borken = true;
  164. reader.close();
  165. stream.destroy();
  166. ko("Failed to load database: syntax error on question #" +lineNo);
  167. }
  168. });
  169. reader.on("close", () => {
  170. if (!borken)
  171. ok(questions);
  172. });
  173. });
  174. }
  175. function QuizzBot(config) {
  176. this.config = config;
  177. }
  178. QuizzBot.prototype.init = function(bot, chanName) {
  179. const previousData = Cache.GetData();
  180. this.room = chanName;
  181. this.bot = bot;
  182. this.init = false;
  183. this.users = {};
  184. this.activeUsers = {};
  185. if (previousData) {
  186. for (var i in previousData.scores) {
  187. this.users[i.toLowerCase()] = bot.createUser(i);
  188. this.users[i.toLowerCase()].score = previousData.scores[i];
  189. }
  190. }
  191. this.mySQLExportWrapper();
  192. }
  193. QuizzBot.prototype.onSelfJoin = function() {
  194. this.init = true;
  195. this.reloadDb();
  196. }
  197. QuizzBot.prototype.onJoin = function(nick) {
  198. this.users[nick.toLowerCase()] = this.users[nick.toLowerCase()] || this.bot.createUser(nick);
  199. this.activeUsers[nick.toLowerCase()] = true;
  200. if (this.currentQuestion)
  201. this.bot.sendNotice(nick, this.currentQuestion.question);
  202. }
  203. QuizzBot.prototype.onNameList = function(nicks) {
  204. this.activeUsers = {};
  205. for (var i in nicks) {
  206. var u = this.users[i.toLowerCase()] = (this.users[i.toLowerCase()] || this.bot.createUser(i));
  207. u.setModeChar(nicks[i]);
  208. this.activeUsers[i.toLowerCase()] = true;
  209. }
  210. }
  211. QuizzBot.prototype.onNickPart = function(nick) {
  212. delete this.activeUsers[nick.toLowerCase()];
  213. }
  214. QuizzBot.prototype.onRename = function(oldNick, newNick) {
  215. this.users[newNick.toLowerCase()] = this.users[newNick.toLowerCase()] || this.bot.createUser(newNick);
  216. this.users[newNick.toLowerCase()].isAdmin = this.users[oldNick.toLowerCase()] && this.users[oldNick.toLowerCase()].isAdmin;
  217. this.activeUsers[newNick.toLowerCase()] = true;
  218. delete this.activeUsers[oldNick.toLowerCase()];
  219. }
  220. QuizzBot.prototype.onMessage = function(user, text) {
  221. this.users[user.toLowerCase()] && this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
  222. }
  223. QuizzBot.prototype.onRemMode = function(user, mode) {
  224. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].unsetMode(mode);
  225. }
  226. QuizzBot.prototype.onAddMode = function(user, mode) {
  227. if (user === this.name) {
  228. usersToVoice = [];
  229. for (var i in this.users) {
  230. if (this.users[i].score && this.activeUsers[i])
  231. usersToVoice.push(i);
  232. }
  233. this.bot.voice(this.room, usersToVoice);
  234. } else {
  235. this.users[user.toLowerCase()] && this.users[user.toLowerCase()].setMode(mode);
  236. }
  237. }
  238. QuizzBot.prototype.stop = function() {
  239. this.timer && clearTimeout(this.timer);
  240. this.timer = null;
  241. this.currentQuestion = null;
  242. this.currentHint = 0;
  243. }
  244. QuizzBot.prototype.onTick = function() {
  245. if (!this.currentQuestion)
  246. return;
  247. if (this.currentHint < 3)
  248. this.sendNextHint(false);
  249. else {
  250. var response = Array.isArray(this.currentQuestion.response) ?
  251. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  252. this.currentQuestion.response;
  253. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +response);
  254. this.nextQuestionWrapper();
  255. }
  256. }
  257. QuizzBot.prototype.resetTimer = function() {
  258. this.timer && clearTimeout(this.timer);
  259. this.timer = setInterval(this.onTick.bind(this), this.config.AUTO_HINT_DELAY);
  260. }
  261. QuizzBot.prototype.sendNextHint = function(resetTimer) {
  262. this.bot.sendMsg(this.room, this.currentQuestion.getHint(this.currentHint));
  263. ++this.currentHint;
  264. this.lastHint = Date.now();
  265. resetTimer !== false && this.resetTimer();
  266. }
  267. QuizzBot.prototype.nextQuestionWrapper = function() {
  268. this.currentQuestion.end();
  269. this.currentQuestion = null;
  270. setTimeout(this.nextQuestion.bind(this), this.config.NEXT_QUESTION_DELAY);
  271. }
  272. QuizzBot.prototype.nextQuestion = function() {
  273. this.currentQuestion = this.questions[Math.floor(Math.random() * this.questions.length)];
  274. console.log(this.currentQuestion);
  275. this.currentHint = 0;
  276. this.questionDate = Date.now();
  277. this.bot.sendMsg(this.room, "#" +this.currentQuestion.id +" " +this.currentQuestion.question);
  278. this.sendNextHint();
  279. }
  280. QuizzBot.prototype.start = function() {
  281. if (this.reloading) {
  282. this.bot.sendMsg(this.room, "Error: database still reloading");
  283. return;
  284. }
  285. if (!this.currentQuestion) {
  286. this.nextQuestion();
  287. }
  288. }
  289. QuizzBot.prototype.reloadDb = function() {
  290. var _this = this;
  291. this.stop();
  292. this.reloading = true;
  293. initQuestionList(this.config.QUESTIONS_PATH).then(questions => {
  294. _this.reloading = false;
  295. _this.questions = questions;
  296. _this.bot.sendMsg(this.room, questions.length +" questions loaded from database");
  297. _this.start();
  298. }).catch(err => {
  299. console.error(err);
  300. _this.bot.sendMsg(this.room, err);
  301. });
  302. }
  303. QuizzBot.prototype.delScore = function(user) {
  304. var data = this.users[user.toLowerCase()];
  305. if (!data) {
  306. this.bot.sendMsg(this.room, "User not found...");
  307. return;
  308. }
  309. if (!data.score) {
  310. this.bot.sendMsg(this.room, "Score for user already null");
  311. return;
  312. }
  313. data.score = 0;
  314. this.bot.sendMsg(this.room, "Removed score");
  315. Cache.SetScores(this.users);
  316. }
  317. QuizzBot.prototype.sumScores = function(onlyPresent) {
  318. var score = 0;
  319. for (var i in this.users)
  320. score += (this.users[i].score && (this.activeUsers[i] || !onlyPresent)) ? this.users[i].score : 0;
  321. return score;
  322. }
  323. QuizzBot.prototype.sendScore = function(onlyPresent) {
  324. var scores = ScoreUtils.buildScoreArray(this, user => this.users[user].score && (this.activeUsers[user] || !onlyPresent), 10);
  325. if (scores.length == 0) {
  326. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  327. return;
  328. }
  329. var index = 0;
  330. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  331. if (scoreLines[0].length < 30) {
  332. // merge score lines 2 by 2
  333. var tmp = [];
  334. for (var i =0, len = scoreLines.length; i < len; i += 2)
  335. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  336. scoreLines = tmp;
  337. }
  338. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  339. }
  340. QuizzBot.prototype.computeScore = function(username) {
  341. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response,
  342. responseMsg = "Réponse `" +rep +"` trouvée en " +Math.floor((Date.now() -this.questionDate) / 1000) +" secondes ";
  343. if (this.currentHint <= 1)
  344. responseMsg += "sans indice";
  345. else if (this.currentHint === 2)
  346. responseMsg += "avec 1 seul indice";
  347. else
  348. responseMsg += "avec " +this.currentHint +" indices";
  349. var score = 4 - this.currentHint;
  350. this.bot.sendMsg(this.room, responseMsg);
  351. return score;
  352. }
  353. QuizzBot.prototype.findQuestionById = function(qId) {
  354. for (var i =0, len = this.questions.length; i < len; ++i) {
  355. if (this.questions[i].id === qId)
  356. return this.questions[i];
  357. if (this.questions[i].id > qId)
  358. break;
  359. }
  360. }
  361. QuizzBot.prototype.resetScores = function() {
  362. if (this.sumScores(false) > 0) {
  363. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  364. this.sendScore(false);
  365. }
  366. for (var i in this.users)
  367. this.users[i].score = 0;
  368. Cache.SetScores({});
  369. }
  370. /**
  371. * This function is called when a user answer right,
  372. * @param diff an object containing the new rank, the previous rank, and an
  373. * array containing all the users having been overpassed
  374. * @return a string with a message to be displayed or null if nothing to say
  375. **/
  376. QuizzBot.prototype.buildOverpassedMessage = function(username, diff) {
  377. if (!diff.users || !diff.users.length)
  378. return null;
  379. const rankStr = diff.newRank == 1 ? "1ere" : `${diff.newRank}eme`;
  380. if (diff.users.length > 2) // Advanced too much rank at once ! Only display new position
  381. return `${username} prend la ${rankStr} place !`;
  382. const looser = diff.users.map(i => i.name).join(" et "),
  383. insults = [
  384. () => `${username} prend la ${rankStr} place en doublant allegrement ${looser}`,
  385. () => `${username} fait un gros pied de nez a ${looser} en prennant la ${rankStr} place`
  386. ];
  387. return insults[Math.floor(Math.random() * insults.length)]();
  388. }
  389. QuizzBot.prototype.onMessageInternal = function(username, user, msg) {
  390. const lmsg = msg.toLowerCase();
  391. if (lmsg.startsWith("!reload")) {
  392. if (user.admin)
  393. this.reloadDb();
  394. else
  395. this.bot.sendMsg(this.room, "Must be channel operator");
  396. }
  397. else if (lmsg.startsWith("!help")) {
  398. 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");
  399. }
  400. else if (lmsg === "!indice" || lmsg === "!conseil") {
  401. if (this.currentQuestion) {
  402. if (this.currentHint < 3) {
  403. if (Date.now() -this.lastHint > this.config.MIN_HINT_DELAY)
  404. this.sendNextHint();
  405. }
  406. else
  407. this.bot.sendMsg(this.room, "Pas plus d'indice...");
  408. }
  409. }
  410. else if (lmsg === "!next") {
  411. if (user.admin) {
  412. if (!this.currentQuestion)
  413. return;
  414. var response = Array.isArray(this.currentQuestion.response) ?
  415. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  416. this.currentQuestion.response;
  417. this.bot.sendMsg(this.room, "La réponse était: " +response);
  418. this.nextQuestionWrapper();
  419. } else {
  420. this.bot.sendMsg(this.room, "Must be channel operator");
  421. }
  422. }
  423. else if (lmsg.startsWith("!report list")) {
  424. if (user.admin) {
  425. var questions = Cache.getReportedQuestions();
  426. for (var i in questions)
  427. for (var j in questions[i])
  428. questions[i][j] = (new Date(questions[i][j])).toLocaleString();
  429. this.bot.sendNotice(username, JSON.stringify(questions));
  430. }
  431. else
  432. this.bot.sendMsg(this.room, "Must be channel operator");
  433. }
  434. else if (lmsg == ("!report clear")) {
  435. if (user.admin) {
  436. Cache.clearReports();
  437. this.bot.sendMsg(this.room, "Toutes les questions sont marquées comme restaurées");
  438. }
  439. else
  440. this.bot.sendMsg(this.room, "Must be channel operator");
  441. }
  442. else if (lmsg.startsWith("!report del ")) {
  443. var questionId = msg.substr("!report del ".length).trim();
  444. if (questionId.startsWith('#'))
  445. questionId = questionId.substr(1);
  446. questionId = Number(questionId);
  447. if (isNaN(questionId)) {
  448. this.bot.sendMsg(this.room, "Erreur: Usage: !report del #1234");
  449. return;
  450. }
  451. if (user.admin) {
  452. Cache.unreportQuestion(questionId);
  453. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  454. } else if (Cache.isReportedBy(questionId, username)) {
  455. Cache.unreportQuestion(questionId, username);
  456. this.bot.sendMsg(this.room, "Question #" +questionId +" n'est plus marquée comme défectueuse par " +username);
  457. } else {
  458. this.bot.sendMsg(this.room, "Must be channel operator");
  459. }
  460. }
  461. else if (lmsg.startsWith("!report ")) {
  462. var questionId = msg.substr("!report ".length).trim();
  463. if (questionId.startsWith('#'))
  464. questionId = questionId.substr(1);
  465. questionId = Number(questionId);
  466. if (isNaN(questionId)) {
  467. this.bot.sendMsg(this.room, "Erreur: Usage: !report #1234");
  468. return;
  469. }
  470. if (!this.findQuestionById(questionId))
  471. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  472. else {
  473. Cache.reportQuestion(questionId, username);
  474. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme défectueuse par " +username);
  475. }
  476. }
  477. else if (lmsg.startsWith("!rename ")) {
  478. if (!user.admin) {
  479. this.bot.sendMsg(this.room, "Must be channel operator");
  480. return;
  481. }
  482. var args = (msg.split(/\s+/)).splice(1);
  483. if (args.length < 2) {
  484. this.bot.sendNotice(username, "Usage: !rename nouveau_pseudo ancien_pseudo [ancien_pseudo...]");
  485. return;
  486. }
  487. var sum = 0,
  488. users = [],
  489. target = args[0];
  490. args = args.map(username => username.toLowerCase());
  491. var userToMod = null;
  492. for (var i in this.users) {
  493. var userIndex = args.indexOf(i.toLowerCase());
  494. if (userIndex > 0) {
  495. sum += this.users[i].score;
  496. this.users[i].score = 0;
  497. if (!this.activeUsers[i])
  498. delete this.users[i];
  499. }
  500. else if (userIndex == 0)
  501. userToMod = this.users[i];
  502. }
  503. if (!userToMod) {
  504. userToMod = this.users[target] = this.bot.createUser(target);
  505. this.bot.sendMsg(this.room, "Created user " +target +" with " +sum +" points");
  506. } else if (sum) {
  507. this.bot.sendMsg(this.room, "Added " +sum +" points to " +target);
  508. }
  509. userToMod.score += sum;
  510. Cache.SetScores(this.users);
  511. }
  512. else if (lmsg === "!score all") {
  513. if (!user.admin) {
  514. this.bot.sendMsg(this.room, "Must be channel operator");
  515. return;
  516. }
  517. var scores = [];
  518. for (var i in this.users)
  519. this.users[i].score && scores.push({name: this.users[i].name, score: this.users[i].score});
  520. if (scores.length == 0) {
  521. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  522. return;
  523. }
  524. scores = scores.sort((a, b) => b.score - a.score);
  525. this.bot.sendNotice(username, scores.map(i => i.name+":"+i.score).join(", "));
  526. }
  527. else if (lmsg === "!score") {
  528. this.sendScore(true);
  529. }
  530. else if (lmsg === "!top") {
  531. this.sendScore(false);
  532. }
  533. else if (this.currentQuestion) {
  534. var dieOnFailure = this.currentQuestion.isBoolean() && this.currentQuestion.isBoolean(Question.normalize(msg));
  535. if (this.currentQuestion.check(msg)) {
  536. const nbPts = this.computeScore(username);
  537. var overpassedMessage = this.buildOverpassedMessage(username, ScoreUtils.buildScoreArray(this, i => this.users[i].score).diff(username, nbPts));
  538. user.score += nbPts;
  539. Cache.SetScores(this.users);
  540. this.bot.sendMsg(this.room, nbPts +" points pour " +username +", qui cumule un total de " +user.score +" points !");
  541. overpassedMessage && this.bot.sendMsg(this.room, overpassedMessage);
  542. this.bot.voice(this.room, username);
  543. this.nextQuestionWrapper();
  544. }
  545. else if (dieOnFailure) {
  546. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response;
  547. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +rep);
  548. this.nextQuestionWrapper();
  549. }
  550. }
  551. };
  552. QuizzBot.prototype.mySQLExportWrapper = function() {
  553. if (!USE_MYSQL)
  554. return;
  555. var msRemaining = 0,
  556. lastMySQLExport = Cache.getLastMysqlSave();
  557. if (lastMySQLExport)
  558. msRemaining = this.config.GAME_DURATION -(Date.now() -lastMySQLExport);
  559. if (msRemaining <= 0)
  560. this.mySQLExport();
  561. else
  562. this.exportScoresTimer = setTimeout(this.mySQLExportWrapper.bind(this), Math.min(2147483000, msRemaining));
  563. }
  564. QuizzBot.prototype.mySQLExport = function() {
  565. this.exportScores().then(() => {
  566. Cache.setExportTs();
  567. this.resetScores();
  568. console.log("Successfully exported scores to MySQL");
  569. this.mySQLExportWrapper();
  570. }).catch((errString) => {
  571. console.error("mySQL Export error saving to database: ", errString);
  572. });
  573. }
  574. QuizzBot.prototype.exportScores = function() {
  575. console.log("Start exporting scores");
  576. return new Promise((ok, ko) => {
  577. if (!MySQL)
  578. return ko();
  579. var ts = Cache.getLastMysqlSave() || this.config.START_TIME;
  580. mySQL = MySQL();
  581. ts = Math.floor(ts / 1000) *1000;
  582. ts = mySQL.escape(new Date(ts));
  583. ts = ts.substr(1, ts.length -2);
  584. var sep = ts.lastIndexOf('.');
  585. if (sep > 12) ts = ts.substr(0, sep);
  586. var toSave = [];
  587. for (var i in this.users)
  588. if (this.users[i].score) {
  589. toSave.push(this.users[i].name);
  590. toSave.push(this.users[i].score);
  591. }
  592. if (toSave.length == 0) {
  593. mySQL.end();
  594. return ok();
  595. }
  596. mySQL.execute("INSERT INTO " +this.config.MySQL_PERIOD_TABLE +" (start, host) VALUES(?, ?)", [ts, HOSTNAME], (err, result) => {
  597. if (err || !result.insertId) {
  598. mySQL.end();
  599. return ko(err || "Cannot get last inserted id");
  600. }
  601. mySQL.execute("INSERT INTO " +this.config.MySQL_SCORES_TABLE +"(period_id, pseudo, score) VALUES " +(",("+result.insertId+",?,?)").repeat(toSave.length /2).substr(1), toSave, (err) => {
  602. mySQL.end();
  603. if (err)
  604. ko(err);
  605. else
  606. ok();
  607. });
  608. });
  609. });
  610. }
  611. module.exports = QuizzBot;