quizz.js 26 KB

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