quizz.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  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.currentQuestion.end();
  270. this.currentQuestion = null;
  271. setTimeout(this.nextQuestion.bind(this), this.config.NEXT_QUESTION_DELAY);
  272. }
  273. QuizzBot.prototype.nextQuestion = function() {
  274. this.currentQuestion = this.questions[Math.floor(Math.random() * this.questions.length)];
  275. console.log(this.currentQuestion);
  276. this.currentHint = 0;
  277. this.questionDate = Date.now();
  278. this.bot.sendMsg(this.room, "#" +this.currentQuestion.id +" " +this.currentQuestion.question);
  279. this.sendNextHint();
  280. }
  281. QuizzBot.prototype.start = function() {
  282. if (this.reloading) {
  283. this.bot.sendMsg(this.room, "Error: database still reloading");
  284. return;
  285. }
  286. if (!this.currentQuestion) {
  287. this.nextQuestion();
  288. }
  289. }
  290. QuizzBot.prototype.reloadDb = function() {
  291. var _this = this;
  292. this.stop();
  293. this.reloading = true;
  294. initQuestionList(this.config.QUESTIONS_PATH).then(questions => {
  295. _this.reloading = false;
  296. _this.questions = questions;
  297. _this.bot.sendMsg(this.room, questions.length +" questions loaded from database");
  298. _this.start();
  299. }).catch(err => {
  300. console.error(err);
  301. _this.bot.sendMsg(this.room, err);
  302. });
  303. }
  304. QuizzBot.prototype.delScore = function(user) {
  305. var data = this.users[user.toLowerCase()];
  306. if (!data) {
  307. this.bot.sendMsg(this.room, "User not found...");
  308. return;
  309. }
  310. if (!data.score) {
  311. this.bot.sendMsg(this.room, "Score for user already null");
  312. return;
  313. }
  314. data.score = 0;
  315. this.bot.sendMsg(this.room, "Removed score");
  316. Cache.SetScores(this.users);
  317. }
  318. QuizzBot.prototype.sumScores = function(onlyPresent) {
  319. var score = 0;
  320. for (var i in this.users)
  321. score += (this.users[i].score && (this.activeUsers[i] || !onlyPresent)) ? this.users[i].score : 0;
  322. return score;
  323. }
  324. QuizzBot.prototype.sendScore = function(onlyPresent) {
  325. var scores = ScoreUtils.buildScoreArray(this, user => this.users[user].score && (this.activeUsers[user] || !onlyPresent), 10);
  326. if (scores.length == 0) {
  327. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  328. return;
  329. }
  330. var index = 0;
  331. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  332. if (scoreLines[0].length < 30) {
  333. // merge score lines 2 by 2
  334. var tmp = [];
  335. for (var i =0, len = scoreLines.length; i < len; i += 2)
  336. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  337. scoreLines = tmp;
  338. }
  339. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  340. }
  341. QuizzBot.prototype.computeScore = function(username) {
  342. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response,
  343. responseMsg = "Réponse `" +rep +"` trouvée en " +Math.floor((Date.now() -this.questionDate) / 1000) +" secondes ";
  344. if (this.currentHint <= 1)
  345. responseMsg += "sans indice";
  346. else if (this.currentHint === 2)
  347. responseMsg += "avec 1 seul indice";
  348. else
  349. responseMsg += "avec " +this.currentHint +" indices";
  350. var score = 4 - this.currentHint;
  351. this.bot.sendMsg(this.room, responseMsg);
  352. return score;
  353. }
  354. QuizzBot.prototype.findQuestionById = function(qId) {
  355. for (var i =0, len = this.questions.length; i < len; ++i) {
  356. if (this.questions[i].id === qId)
  357. return this.questions[i];
  358. if (this.questions[i].id > qId)
  359. break;
  360. }
  361. }
  362. QuizzBot.prototype.resetScores = function() {
  363. if (this.sumScores(false) > 0) {
  364. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  365. this.sendScore(false);
  366. }
  367. for (var i in this.users)
  368. this.users[i].score = 0;
  369. Cache.SetScores({});
  370. }
  371. /**
  372. * This function is called when a user answer right,
  373. * @param diff an object containing the new rank, the previous rank, and an
  374. * array containing all the users having been overpassed
  375. * @return a string with a message to be displayed or null if nothing to say
  376. **/
  377. QuizzBot.prototype.buildOverpassedMessage = function(username, diff) {
  378. var exaequo = null;
  379. if (diff.exaequo.length)
  380. exaequo = " est aux coude a coude avec " +diff.exaequo.map(i => i.name).join(", ");
  381. if (!diff.users || !diff.users.length)
  382. return exaequo ? (username +exaequo) : null;
  383. exaequo = exaequo ? (" et" +exaequo) : null;
  384. const rankStr = diff.newRank == 1 ? "1ere" : `${diff.newRank}eme`;
  385. if (diff.users.length > 1) // Advanced too much rank at once ! Only display new position
  386. return `${username} prend la ${rankStr} place ` +(exaequo || "!");
  387. const looser = diff.users[0].name,
  388. insults = [
  389. () => `${username} prend la ${rankStr} place en doublant allegrement ${looser}`,
  390. () => `${username} fait un gros pied de nez a ${looser} en prennant la ${rankStr} place`,
  391. () => `${username} prends la ${rankStr} place et fait mordre la poussière à ${looser}`,
  392. () => `${looser} est maintenant dans le sillage de ${username} qui lui a piqué la ${rankStr} place`,
  393. () => `${username} envoie ${looser} dans les méandres de la loose en lui prenant la ${rankStr} place`,
  394. () => `${looser} est maintenant visible en tout petit dans le rétroviseur de ${username} qui lui a piqué la ${rankStr} place`,
  395. () => `La ${rankStr} place est maintenant la propriété de ${username} qui a envoyé ${looser} au tapis`,
  396. () => `${username} tatoue un gros L de la loose sur le front de ${looser} qui vient de perdre la ${rankStr} place`
  397. ];
  398. var insultStr = insults[Math.floor(Math.random() * insults.length)]();
  399. return insultStr +(exaequo || "!");
  400. }
  401. QuizzBot.prototype.onMessageInternal = function(username, user, msg) {
  402. const lmsg = msg.toLowerCase();
  403. if (lmsg.startsWith("!reload")) {
  404. if (user.admin)
  405. this.reloadDb();
  406. else
  407. this.bot.sendMsg(this.room, "Must be channel operator");
  408. }
  409. else if (lmsg.startsWith("!help")) {
  410. 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");
  411. }
  412. else if (lmsg === "!indice" || lmsg === "!conseil") {
  413. if (this.currentQuestion) {
  414. if (this.currentHint < 3) {
  415. if (Date.now() -this.lastHint > this.config.MIN_HINT_DELAY)
  416. this.sendNextHint();
  417. }
  418. else
  419. this.bot.sendMsg(this.room, "Pas plus d'indice...");
  420. }
  421. }
  422. else if (lmsg === "!next") {
  423. if (user.admin) {
  424. if (!this.currentQuestion)
  425. return;
  426. var response = Array.isArray(this.currentQuestion.response) ?
  427. this.currentQuestion.response.map(i => "\""+i+"\"").join(" ou ") :
  428. this.currentQuestion.response;
  429. this.bot.sendMsg(this.room, "La réponse était: " +response);
  430. this.nextQuestionWrapper();
  431. } else {
  432. this.bot.sendMsg(this.room, "Must be channel operator");
  433. }
  434. }
  435. else if (lmsg.startsWith("!report list")) {
  436. if (user.admin) {
  437. var questions = Cache.getReportedQuestions();
  438. for (var i in questions)
  439. for (var j in questions[i])
  440. questions[i][j] = (new Date(questions[i][j])).toLocaleString();
  441. this.bot.sendNotice(username, JSON.stringify(questions));
  442. }
  443. else
  444. this.bot.sendMsg(this.room, "Must be channel operator");
  445. }
  446. else if (lmsg == ("!report clear")) {
  447. if (user.admin) {
  448. Cache.clearReports();
  449. this.bot.sendMsg(this.room, "Toutes les questions sont marquées comme restaurées");
  450. }
  451. else
  452. this.bot.sendMsg(this.room, "Must be channel operator");
  453. }
  454. else if (lmsg.startsWith("!report del ")) {
  455. var questionId = msg.substr("!report del ".length).trim();
  456. if (questionId.startsWith('#'))
  457. questionId = questionId.substr(1);
  458. questionId = Number(questionId);
  459. if (isNaN(questionId)) {
  460. this.bot.sendMsg(this.room, "Erreur: Usage: !report del #1234");
  461. return;
  462. }
  463. if (user.admin) {
  464. Cache.unreportQuestion(questionId);
  465. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme restaurée");
  466. } else if (Cache.isReportedBy(questionId, username)) {
  467. Cache.unreportQuestion(questionId, username);
  468. this.bot.sendMsg(this.room, "Question #" +questionId +" n'est plus marquée comme défectueuse par " +username);
  469. } else {
  470. this.bot.sendMsg(this.room, "Must be channel operator");
  471. }
  472. }
  473. else if (lmsg.startsWith("!report ")) {
  474. var questionId = msg.substr("!report ".length).trim();
  475. if (questionId.startsWith('#'))
  476. questionId = questionId.substr(1);
  477. questionId = Number(questionId);
  478. if (isNaN(questionId)) {
  479. this.bot.sendMsg(this.room, "Erreur: Usage: !report #1234");
  480. return;
  481. }
  482. if (!this.findQuestionById(questionId))
  483. this.bot.sendMsg(this.room, "Erreur: question non trouvée");
  484. else {
  485. Cache.reportQuestion(questionId, username);
  486. this.bot.sendMsg(this.room, "Question #" +questionId +" marquée comme défectueuse par " +username);
  487. }
  488. }
  489. else if (lmsg.startsWith("!rename ")) {
  490. if (!user.admin) {
  491. this.bot.sendMsg(this.room, "Must be channel operator");
  492. return;
  493. }
  494. var args = (msg.split(/\s+/)).splice(1);
  495. if (args.length < 2) {
  496. this.bot.sendNotice(username, "Usage: !rename nouveau_pseudo ancien_pseudo [ancien_pseudo...]");
  497. return;
  498. }
  499. var sum = 0,
  500. users = [],
  501. target = args[0];
  502. args = args.map(username => username.toLowerCase());
  503. var userToMod = null;
  504. for (var i in this.users) {
  505. var userIndex = args.indexOf(i.toLowerCase());
  506. if (userIndex > 0) {
  507. sum += this.users[i].score;
  508. this.users[i].score = 0;
  509. if (!this.activeUsers[i])
  510. delete this.users[i];
  511. }
  512. else if (userIndex == 0)
  513. userToMod = this.users[i];
  514. }
  515. if (!userToMod) {
  516. userToMod = this.users[target] = this.bot.createUser(target);
  517. this.bot.sendMsg(this.room, "Created user " +target +" with " +sum +" points");
  518. } else if (sum) {
  519. this.bot.sendMsg(this.room, "Added " +sum +" points to " +target);
  520. }
  521. userToMod.score += sum;
  522. Cache.SetScores(this.users);
  523. }
  524. else if (lmsg === "!score all") {
  525. if (!user.admin) {
  526. this.bot.sendMsg(this.room, "Must be channel operator");
  527. return;
  528. }
  529. var scores = [];
  530. for (var i in this.users)
  531. this.users[i].score && scores.push({name: this.users[i].name, score: this.users[i].score});
  532. if (scores.length == 0) {
  533. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  534. return;
  535. }
  536. scores = scores.sort((a, b) => b.score - a.score);
  537. this.bot.sendNotice(username, scores.map(i => i.name+":"+i.score).join(", "));
  538. }
  539. else if (lmsg === "!score") {
  540. this.sendScore(true);
  541. }
  542. else if (lmsg === "!top") {
  543. this.sendScore(false);
  544. }
  545. else if (this.currentQuestion) {
  546. var dieOnFailure = this.currentQuestion.isBoolean() && this.currentQuestion.isBoolean(Question.normalize(msg));
  547. if (this.currentQuestion.check(msg)) {
  548. const nbPts = this.computeScore(username);
  549. var overpassedMessage = this.buildOverpassedMessage(username, ScoreUtils.buildScoreArray(this, i => this.users[i].score).diff(username, nbPts));
  550. user.score += nbPts;
  551. Cache.SetScores(this.users);
  552. this.bot.sendMsg(this.room, nbPts +" points pour " +username +", qui cumule un total de " +user.score +" points !");
  553. overpassedMessage && this.bot.sendMsg(this.room, overpassedMessage);
  554. this.bot.voice(this.room, username);
  555. this.nextQuestionWrapper();
  556. }
  557. else if (dieOnFailure) {
  558. var rep = Array.isArray(this.currentQuestion.response) ? this.currentQuestion.response.map(i => '"'+i+'"').join(" ou ") : this.currentQuestion.response;
  559. this.bot.sendMsg(this.room, "Perdu, la réponse était: " +rep);
  560. this.nextQuestionWrapper();
  561. }
  562. }
  563. };
  564. QuizzBot.prototype.mySQLExportWrapper = function() {
  565. if (!USE_MYSQL)
  566. return;
  567. var msRemaining = 0,
  568. lastMySQLExport = Cache.getLastMysqlSave();
  569. if (lastMySQLExport)
  570. msRemaining = this.config.GAME_DURATION -(Date.now() -lastMySQLExport);
  571. if (msRemaining <= 0)
  572. this.mySQLExport();
  573. else
  574. this.exportScoresTimer = setTimeout(this.mySQLExportWrapper.bind(this), Math.min(2147483000, msRemaining));
  575. }
  576. QuizzBot.prototype.mySQLExport = function() {
  577. this.exportScores().then(() => {
  578. Cache.setExportTs();
  579. this.resetScores();
  580. console.log("Successfully exported scores to MySQL");
  581. this.mySQLExportWrapper();
  582. }).catch((errString) => {
  583. console.error("mySQL Export error saving to database: ", errString);
  584. });
  585. }
  586. QuizzBot.prototype.exportScores = function() {
  587. console.log("Start exporting scores");
  588. return new Promise((ok, ko) => {
  589. if (!MySQL)
  590. return ko();
  591. var ts = Cache.getLastMysqlSave() || this.config.START_TIME;
  592. mySQL = MySQL();
  593. ts = Math.floor(ts / 1000) *1000;
  594. ts = mySQL.escape(new Date(ts));
  595. ts = ts.substr(1, ts.length -2);
  596. var sep = ts.lastIndexOf('.');
  597. if (sep > 12) ts = ts.substr(0, sep);
  598. var toSave = [];
  599. for (var i in this.users)
  600. if (this.users[i].score) {
  601. toSave.push(this.users[i].name);
  602. toSave.push(this.users[i].score);
  603. }
  604. if (toSave.length == 0) {
  605. mySQL.end();
  606. return ok();
  607. }
  608. mySQL.execute("INSERT INTO " +this.config.MySQL_PERIOD_TABLE +" (start, host) VALUES(?, ?)", [ts, HOSTNAME], (err, result) => {
  609. if (err || !result.insertId) {
  610. mySQL.end();
  611. return ko(err || "Cannot get last inserted id");
  612. }
  613. mySQL.execute("INSERT INTO " +this.config.MySQL_SCORES_TABLE +"(period_id, pseudo, score) VALUES " +(",("+result.insertId+",?,?)").repeat(toSave.length /2).substr(1), toSave, (err) => {
  614. mySQL.end();
  615. if (err)
  616. ko(err);
  617. else
  618. ok();
  619. });
  620. });
  621. });
  622. }
  623. module.exports = QuizzBot;