A Twitch.tv viewer reward and games system.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2128 lines
88 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
12 years ago
12 years ago
12 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12 years ago
11 years ago
12 years ago
11 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. /**
  2. * api:
  3. * Currency(irc object, database object, [required options])
  4. *
  5. * example:
  6. * var Currency = require('./lib/plugins/currency.js')(irc, db, {
  7. * currency : 'currency name',
  8. * subscribers : 'google doc spreadsheet until it's available from twitch api'
  9. * });
  10. *
  11. * commands:
  12. * !<currency>
  13. * reply with currency amount
  14. *
  15. * !<currency> on/[off repeat on/off]
  16. * toggle currency request status,
  17. * repeat status only available when
  18. * turning off requests
  19. *
  20. * !<currency> auction open
  21. * open a new auction
  22. *
  23. * !<currency> auction close
  24. * close current auction
  25. *
  26. * !<currency> auction cancel
  27. * cancel current auction
  28. *
  29. * !<currency> auction draw
  30. * draw the next highest bidder
  31. *
  32. * !bid <amount>
  33. * place a bid on an open auction,
  34. * only valid amounts will be accepted
  35. *
  36. * !<currency> raffle open <price> <max>
  37. * open a new raffle
  38. * price and max is optional
  39. * default price: 10
  40. * default max: 10
  41. *
  42. * !<currency> raffle close
  43. * draw the another ticket from raffle
  44. *
  45. * !<currency> raffle cancel
  46. * cancel the open raffle
  47. *
  48. * !<currency> raffle draw
  49. * open a new auction
  50. *
  51. * !<currency> raffle restore
  52. * restores a previous raffle if a new
  53. * one is accidentally opened
  54. *
  55. * !ticket <amount>
  56. * place a bid on an open auction,
  57. * only valid amounts will be accepted
  58. */
  59. var https = require('https'),
  60. http = require('http'),
  61. file = require('fs'),
  62. utils = require('./utils.js');
  63. //-------- Construct ---------
  64. function Currency(irc, db, commands, options) {
  65. var __self = this;
  66. __self.irc = irc;
  67. __self.db = db;
  68. __self.custom_commands = commands;
  69. // config
  70. __self.config = options || {};
  71. __self.config.currency = options.currency || 'coins';
  72. __self.config.subscribers_json = options.subscribers || '';
  73. __self.config.website = options.website || '';
  74. __self.config.modpowers = options.modpowers || false;
  75. __self.config.ignorelist = options.ignorelist || ['jtv'];
  76. // general settings
  77. __self.pre_text = '> ' + __self.config.currency + ': ';
  78. __self.max_requests = 10;//response after 10 request
  79. __self.temp = {};
  80. // currency request settings
  81. __self.coin_flood = [];
  82. __self.coin_response = null;
  83. __self.coin_response_timer = 3000;
  84. __self.coin_response_reset = true;
  85. __self.coin_toggle = false;
  86. __self.coin_toggle_msg = null;
  87. __self.coin_toggle_timer = 180000;//milliseconds
  88. __self.top_flood = [];
  89. __self.top_response_reset = true;
  90. __self.rank_flood = [];
  91. __self.rank_response_reset = true;
  92. // auction settings
  93. __self.auction_status = false;
  94. __self.auction_bids = [];
  95. __self.auction_previous_bid = {};
  96. __self.auction_bid_response = null;
  97. __self.auction_bid_response_long = null;
  98. // handout coins settings
  99. __self.viewer_list = [];
  100. __self.streaming = false;
  101. __self.streaming_check = 4;//minutes
  102. __self.give_coins = false;
  103. __self.give_coins_timer = options.payrate || 30;//minutes
  104. __self.subscriber_check = 4;//minutes
  105. __self.subscribers = [];
  106. // raffle settings
  107. __self.raffle_status = false;
  108. __self.raffle_ticket_requests = [];
  109. __self.raffle_tickets = [];
  110. __self.raffle_ticket_cost = 10;//currency cost per ticket
  111. __self.raffle_max_tickets = 10;
  112. // raffle restoration
  113. __self.raffle_restore_ticket_requests = [];
  114. __self.raffle_restore_tickets = [];
  115. // gambling settings
  116. __self.bets_status = false;
  117. __self.bets_board = [];
  118. __self.bets_viewers = [];
  119. __self.bets_payout = false;
  120. __self.bets_total = 0;
  121. __self.bets_flood = [];
  122. __self.bets_response = null;
  123. __self.bets_response_timer = 3000;
  124. __self.bets_response_reset = true;
  125. // voting settings
  126. __self.votes_status = false;
  127. __self.votes_board = [];
  128. __self.votes_viewers = [];
  129. __self.votes_payout = false;
  130. __self.votes_total = 0;
  131. __self.votes_flood = [];
  132. __self.votes_response = null;
  133. __self.votes_response_timer = 3000;
  134. __self.votes_response_reset = true;
  135. // high score table
  136. __self.score_bet_pool = 0;
  137. __self.score_bet_single = 0;
  138. // commands add/rem settings
  139. __self.command_add_string = options.add_command || 'addcmd';
  140. __self.command_remove_string = options.remove_command || 'removecmd';
  141. }
  142. //-------- Methods ---------
  143. Currency.prototype.start = function () {
  144. var __self = this;
  145. // populate highscore holders
  146. __self.db.execute('SELECT * FROM highscores', function(rows) {
  147. rows.forEach(function(element, index, array){
  148. switch(element.name) {
  149. case 'bet_pool':
  150. __self.score_bet_pool = element.value;
  151. break;
  152. case 'bet_single':
  153. __self.score_bet_single = element.value;
  154. break;
  155. }
  156. });
  157. });
  158. __self.handout_coins();
  159. };
  160. Currency.prototype.commands = function (data) {
  161. var __self = this,
  162. broadcaster_bot_initiated = __self.irc.caller(data[0]).toLowerCase() === __self.irc.config.broadcaster.toLowerCase() || __self.irc.caller(data[0]).toLowerCase() === __self.irc.config.name.toLowerCase(),
  163. moderator_initiated = __self.irc.mods.indexOf(__self.irc.caller(data[0])) >= 0;
  164. // handle !<currency> commands
  165. if (data[3].slice(1) === '!' + __self.config.currency.toLowerCase()) {
  166. // public commands
  167. if (!__self.coin_toggle && data[4] === undefined) {
  168. __self.get_coins(__self.irc.caller(data[0]));
  169. }
  170. // broadcaster only commands
  171. if (broadcaster_bot_initiated || (__self.config.modpowers && moderator_initiated)) {
  172. //add / remove custom commands
  173. if (data[4] === __self.command_add_string && data[5] !== undefined && data[6] !== undefined) {
  174. var command = data[5];
  175. var text = data.slice(6);
  176. text = text.join(' ');
  177. __self.custom_commands.add(command, text);
  178. }
  179. if (data[4] === __self.command_remove_string && data[5] !== undefined) {
  180. var command = data[5];
  181. __self.custom_commands.remove(command);
  182. }
  183. //open / close auction system
  184. if (data[4] === 'auction') {
  185. switch (data[5]) {
  186. case 'open':
  187. __self.auction(true);
  188. break;
  189. case 'close':
  190. __self.auction(false);
  191. break;
  192. case 'draw':
  193. __self.next_auction_winner();
  194. break;
  195. case 'cancel':
  196. __self.auction('cancel');
  197. break;
  198. case 'help':
  199. __self.irc.emit('message', {message:__self.pre_text + '!' + __self.config.currency.toLowerCase() + ' auction open/close/cancel/draw'});
  200. break;
  201. }
  202. }
  203. // open / close raffle system
  204. if (data[4] === 'raffle') {
  205. switch (data[5]) {
  206. case 'open':
  207. if (data[6] && data[7] && !__self.raffle_status) {
  208. if(parseInt(data[6], 10) > 0 && parseInt(data[7], 10) > 0) {
  209. // save default values
  210. __self.temp.raffle_ticket_cost = __self.raffle_ticket_cost;
  211. __self.temp.raffle_max_tickets = __self.raffle_max_tickets;
  212. // set new raffle cost / amount
  213. __self.raffle_ticket_cost = data[6];
  214. __self.raffle_max_tickets = data[7];
  215. }
  216. } else if (__self.temp.raffle_ticket_cost && __self.temp.raffle_max_tickets && !__self.raffle_status){
  217. __self.raffle_ticket_cost = __self.temp.raffle_ticket_cost;
  218. __self.raffle_max_tickets = __self.temp.raffle_max_tickets;
  219. delete __self.temp.raffle_ticket_cost;
  220. delete __self.temp.raffle_max_tickets;
  221. }
  222. __self.raffle(true);
  223. break;
  224. case 'close':
  225. __self.raffle(false);
  226. break;
  227. case 'draw':
  228. __self.next_raffle_winner();
  229. break;
  230. case 'cancel':
  231. __self.raffle('cancel');
  232. break;
  233. case 'restore':
  234. __self.raffle('restore');
  235. break;
  236. case 'help':
  237. __self.irc.emit('message', {message:__self.pre_text + '!' + __self.config.currency.toLowerCase() + ' raffle open <ticket cost> <tickets per user>/close/cancel/draw/restore'});
  238. break;
  239. }
  240. }
  241. // open / close betting system
  242. if (data[4] === 'bet') {
  243. console.log("bet command found");
  244. switch (data[5]) {
  245. case 'open':
  246. console.log("bet open command found");
  247. if (data[6] && data[7]) {
  248. __self.bets(true, data);
  249. } else {
  250. __self.irc.emit('message', {message:__self.pre_text + 'Unable to open betting, need at least two items to bet against'});
  251. }
  252. break;
  253. case 'close':
  254. __self.bets(false, null);
  255. break;
  256. case 'pool':
  257. __self.bets('pool', null);
  258. break;
  259. case 'winner':
  260. __self.bets('winner', data[6]);
  261. break;
  262. case 'cancel':
  263. __self.bets('cancel');
  264. break;
  265. case 'help':
  266. __self.irc.emit('message', {message:__self.pre_text + '!' + __self.config.currency.toLowerCase() + ' bet open <option A> <option B> <etc>/close/pool/winner <option>/cancel'});
  267. break;
  268. }
  269. }
  270. // open / close voting system
  271. if (data[4] === 'vote') {
  272. console.log("vote command found");
  273. switch (data[5]) {
  274. case 'open':
  275. console.log("vote open command found");
  276. if (data[6] && data[7]) {
  277. __self.votes(true, data);
  278. } else {
  279. __self.irc.emit('message', {message:__self.pre_text + 'Unable to open voting, need at least two items to vote for'});
  280. }
  281. break;
  282. case 'close':
  283. __self.votes(false, null);
  284. break;
  285. case 'pool':
  286. __self.votes('pool', null);
  287. break;
  288. case 'winner':
  289. __self.votes('winner', data[6]);
  290. break;
  291. case 'cancel':
  292. __self.votes('cancel');
  293. break;
  294. }
  295. }
  296. // TODO: create a log file that monitors just add/remove/push - greedy mods :D
  297. // add currency
  298. if (data[4] === 'add') {
  299. if(parseInt(data[5], 10) > 0 && data[6]) {
  300. __self.adjust_currency('add', data[5], data[6]);
  301. }
  302. }
  303. // remove currency
  304. if (data[4] === 'remove') {
  305. if(parseInt(data[5], 10) > 0 && data[6]) {
  306. __self.adjust_currency('remove', data[5], data[6]);
  307. }
  308. }
  309. // push currency to new viewer
  310. if (data[4] === 'push') {
  311. if(parseInt(data[5], 10) > 0 && data[6]) {
  312. __self.adjust_currency('push', data[5], data[6]);
  313. }
  314. }
  315. }
  316. // moderator commands
  317. if (broadcaster_bot_initiated || moderator_initiated) {
  318. // enable/disable currency requests
  319. switch (data[4]) {
  320. case 'on':
  321. if (!__self.auction_status && !__self.raffle_status) {
  322. __self.coin_toggle = false;
  323. // output currency request status
  324. __self.irc.emit('message', {message:__self.pre_text + 'Currency requests are now enabled. Type !' + __self.config.currency.toLowerCase() + ' to view your total'});
  325. // stop periodic message
  326. clearInterval(__self.coin_toggle_msg);
  327. }
  328. break;
  329. case 'off':
  330. if (!__self.auction_status && !__self.raffle_status) {
  331. var msg;
  332. if (!__self.coin_toggle) {
  333. // output message depending on if an offsite is provided
  334. if (__self.config.website !== '') {
  335. msg = __self.pre_text + 'Currency requests have been disabled. To view your ' + __self.config.currency + ' please visit ' + __self.config.website;
  336. __self.irc.emit('message', {message:msg});
  337. } else {
  338. msg = __self.pre_text + 'Currency requests have been disabled';
  339. __self.irc.emit('message', {message:msg});
  340. }
  341. }
  342. // start the periodic message
  343. if (data[5] !== undefined && data[6] !== undefined) {
  344. // manually enable / disable repeat
  345. if (data[5] === 'repeat') {
  346. switch (data[6]) {
  347. case 'on':
  348. __self.irc.emit('message', {message:'+ Periodic notification enabled'});
  349. __self.coin_toggle_msg = setInterval(function () {
  350. if (__self.coin_toggle) {
  351. msg = __self.pre_text + 'To view your ' + __self.config.currency + ' please visit ' + __self.config.website;
  352. __self.irc.emit('message', {message:msg});
  353. }
  354. }, __self.coin_toggle_timer);
  355. break;
  356. case 'off':
  357. __self.irc.emit('message', {message:'+ Periodic notification disabled'});
  358. clearInterval(__self.coin_toggle_msg);
  359. }
  360. }
  361. }
  362. __self.coin_toggle = true;
  363. }
  364. break;
  365. }
  366. // adjust currency response rate
  367. if (data[4] === 'timer') {
  368. if (isNaN(parseInt(data[5], 10)) === false) {
  369. if (data[5] >= 3 && data[5] % 1 === 0) {
  370. __self.coin_response_timer = data[5] * 1000;
  371. __self.irc.emit('message', {message:__self.pre_text + 'Currency totals will now show ' + data[5] + ' seconds after request'});
  372. if (data[6] && data[7]) {
  373. if (data[6] === 'reset') {
  374. switch(data[7]) {
  375. case 'on':
  376. __self.irc.emit('message', {message:'+ Timer will now reset after each new request'});
  377. __self.coin_response_reset = true;
  378. break;
  379. case 'off':
  380. __self.irc.emit('message', {message:'+ Timer will not reset after each new request'});
  381. __self.coin_response_reset = false;
  382. break;
  383. }
  384. }
  385. }
  386. } else if (data[5] < 3) {
  387. __self.irc.emit('message', {message:__self.pre_text + 'Timer cannot be less than 2 seconds'});
  388. }
  389. }
  390. }
  391. }
  392. }
  393. // public commands related to !<currency>
  394. switch (data[3].slice(1)) {
  395. // submit bid for the auction
  396. case '!bid':
  397. if (isNaN(parseInt(data[4], 10)) === false) {
  398. if (data[4] > 0 && data[4] % 1 === 0) {
  399. __self.bid(__self.irc.caller(data[0]), parseInt(data[4], 10));
  400. }
  401. }
  402. break;
  403. // purchase a ticket for raffle
  404. case '!ticket':
  405. if (isNaN(parseInt(data[4], 10)) === false) {
  406. if (data[4] >= 0 && data[4] % 1 === 0) {
  407. __self.collect_tickets(__self.irc.caller(data[0]), parseInt(data[4], 10));
  408. }
  409. }
  410. break;
  411. // show top currency earners
  412. case '!top':
  413. __self.get_top(data[4]);
  414. break;
  415. // show a users ranking in the ladder
  416. case '!rank':
  417. __self.get_rank(__self.irc.caller(data[0]).toLowerCase());
  418. break;
  419. }
  420. // place a bet
  421. if (__self.bets_status === true) {
  422. for (var i = 0; i < __self.bets_board.length; i++) {
  423. if (data[3].slice(1) === '!' + __self.bets_board[i].name) {
  424. if (isNaN(parseInt(data[4], 10)) === false) {
  425. if (data[4] >= 0 && data[4] % 1 === 0) {
  426. __self.collect_bets(__self.irc.caller(data[0]), __self.bets_board[i], parseInt(data[4], 10));
  427. break;
  428. }
  429. }
  430. }
  431. }
  432. }
  433. // cast a vote
  434. if (__self.votes_status === true) {
  435. for (var i = 0; i < __self.votes_board.length; i++) {
  436. if (data[3].slice(1) === '!' + __self.votes_board[i].name) {
  437. if (isNaN(parseInt(data[4], 10)) === false) {
  438. if (data[4] >= 0 && data[4] % 1 === 0) {
  439. __self.collect_votes(__self.irc.caller(data[0]), __self.votes_board[i], parseInt(data[4], 10));
  440. break;
  441. }
  442. }
  443. }
  444. }
  445. }
  446. };
  447. /**
  448. * ============================================
  449. * CURRENCY REQUESTS
  450. * --------------------------------------------
  451. */
  452. Currency.prototype.get_coins = function (caller) {
  453. var __self = this;
  454. function fill_request(viewer, points) {
  455. var request = '(' + points + ')';
  456. if (__self.raffle_status) {
  457. for (var i = 0; i < __self.raffle_ticket_requests.length; i++){
  458. if (__self.raffle_ticket_requests[i].viewer.toLowerCase() === viewer.toLowerCase() && (__self.raffle_ticket_requests[i].tickets * __self.raffle_ticket_cost) <= points) {
  459. request = '(' + (points - (__self.raffle_ticket_requests[i].tickets * __self.raffle_ticket_cost)) + ') [' + __self.raffle_ticket_requests[i].tickets + ']';
  460. break;
  461. }
  462. }
  463. return request;
  464. } else {
  465. return request;
  466. }
  467. }
  468. function do_work() {
  469. var multi_response = '';
  470. if (__self.coin_flood.length > 1) {// send flood requests
  471. __self.query_coins(__self.coin_flood, function (rows) {
  472. for (var i = 0; i < rows.length; i++) {
  473. var currency_request = fill_request(rows[i].user, rows[i].points);
  474. // setup currency response
  475. if (i !== rows.length - 1) {
  476. multi_response += rows[i].user + ' ' + currency_request + ', ';
  477. } else {
  478. multi_response += rows[i].user + ' ' + currency_request;
  479. }
  480. }
  481. __self.irc.emit('message', {message:__self.pre_text + multi_response, timer: 1});
  482. });
  483. } else if (__self.coin_flood.length === 1) {// send single request
  484. __self.query_coins(caller, function (rows) {
  485. var currency_request = fill_request(rows[0].user, rows[0].points);
  486. __self.irc.emit('message', {message:__self.pre_text + caller + ' ' + currency_request, timer: 1});
  487. });
  488. }
  489. // clear flood requests
  490. __self.coin_flood = [];
  491. }
  492. // add flood users to array
  493. if (__self.coin_flood.indexOf(caller) < 0) {
  494. __self.coin_flood.push(caller);
  495. }
  496. // clear timer on flood
  497. if (__self.coin_response_reset) {
  498. clearTimeout(__self.coin_response);
  499. }
  500. // check if flood has a set amount of requests and output
  501. // if not, set the output timer
  502. if (__self.coin_flood.length === __self.max_requests) {
  503. do_work();
  504. } else {
  505. if (__self.coin_response_reset) {
  506. __self.coin_response = setTimeout(function () {do_work();}, __self.coin_response_timer);
  507. } else {
  508. setTimeout(function () {do_work();}, __self.coin_response_timer);
  509. }
  510. }
  511. };
  512. Currency.prototype.get_rank = function (data) {
  513. var __self = this;
  514. function do_work() {
  515. __self.query_rank(__self.rank_flood, function (ranks, total) {
  516. var response = '> Rank (of '+total+'): ';
  517. for(var i = 0; i < ranks.length; i++) {
  518. response += ranks[i]['user'] + ' ('+ranks[i]['@row_number:=@row_number+1']+') ['+ranks[i]['points']+'], ';
  519. }
  520. response = response.slice(1,-2);
  521. __self.irc.emit('message', {message: response, timer: 1});
  522. });
  523. __self.rank_flood = [];
  524. }
  525. // add flood users to array
  526. if (__self.rank_flood.indexOf(data) < 0) {
  527. __self.rank_flood.push(data);
  528. }
  529. // clear timer on flood
  530. if (__self.rank_response_reset) {
  531. clearTimeout(__self.rank_response);
  532. }
  533. // check if flood has hit max requests or set timer
  534. if (__self.rank_flood.length === __self.max_requests) {
  535. do_work();
  536. } else {
  537. if (__self.rank_response_reset) {
  538. __self.rank_response = setTimeout(function () {do_work();}, __self.coin_response_timer);
  539. } else {
  540. setTimeout(function () {do_work();}, __self.coin_response_timer);
  541. }
  542. }
  543. };
  544. Currency.prototype.get_top = function (data) {
  545. var __self = this;
  546. var limit = 0;
  547. function do_work() {
  548. var response = '';
  549. __self.query_top(__self.top_flood, function (rows) {
  550. for (var i = 0; i < rows.length; i++) {
  551. // setup response
  552. if (i !== rows.length - 1) {
  553. response += '#'+(i+1)+': ' + rows[i].user + '('+rows[i].points+'), ';
  554. } else {
  555. response += '#'+(i+1)+': ' + rows[i].user + '('+rows[i].points+')';
  556. }
  557. }
  558. __self.irc.emit('message', {message:'> Top Farmers: ' + response});
  559. });
  560. // clear flood requests
  561. __self.top_flood = [];
  562. }
  563. // check that we got a number
  564. ( isNaN(data) ) ? limit = 3 : limit = data;
  565. // limit the number
  566. if (limit > 6) limit = 3;
  567. // add flood users to array
  568. if (__self.top_flood.indexOf(limit) < 0) {
  569. __self.top_flood.push(limit);
  570. }
  571. // clear timer on flood
  572. if (__self.top_response_reset) {
  573. clearTimeout(__self.top_response);
  574. }
  575. // check if flood has hit max requests or set timer
  576. if (__self.top_flood.length === __self.max_requests) {
  577. do_work();
  578. } else {
  579. if (__self.top_response_reset) {
  580. __self.top_response = setTimeout(function () {do_work();}, __self.coin_response_timer);
  581. } else {
  582. setTimeout(function () {do_work();}, __self.coin_response_timer);
  583. }
  584. }
  585. };
  586. Currency.prototype.query_rank = function(data, callback) {
  587. var __self = this;
  588. var ranks = {}, total = 0;
  589. var inner_sql = '', sql = 'set @row_number:=0;';
  590. data.forEach(function(user) {
  591. inner_sql += "user='"+user+"' or ";
  592. });
  593. // remove last or
  594. inner_sql=inner_sql.slice(0,-4);
  595. sql += "select * from (select user, points, @row_number:=@row_number+1 from viewers order by points desc) as rank where ("+inner_sql+");select count(1) from viewers where points > 0;";
  596. __self.db.execute(sql, function(rows) {
  597. total = rows[2][0]['count(1)'];
  598. ranks = rows[1];
  599. callback(ranks, total);
  600. });
  601. };
  602. Currency.prototype.query_top = function (data, callback) {
  603. var __self = this, sql = '';
  604. // build sql conditions
  605. sql = 'SELECT * FROM viewers ORDER BY points DESC LIMIT ' + data + ';';
  606. __self.db.execute(sql, function(rows) {
  607. callback(rows);
  608. });
  609. };
  610. Currency.prototype.query_coins = function (data, callback) {
  611. var __self = this, sql = '';
  612. // build sql conditions
  613. if (typeof data === 'string') {
  614. sql = 'SELECT * FROM viewers WHERE ' + 'user = \'' + data.toLowerCase() + '\'';
  615. } else {
  616. for (var i = 0; i < data.length; i++) {
  617. if (i !== data.length - 1) {
  618. sql += 'SELECT * FROM viewers WHERE ' + 'user = \'' + data[i].toLowerCase() + '\'' + ';';
  619. } else {
  620. sql += 'SELECT * FROM viewers WHERE ' + 'user = \'' + data[i].toLowerCase() + '\'';
  621. }
  622. }
  623. }
  624. // execute query
  625. __self.db.execute(sql, function (rows) {
  626. var temp = [], newrows = [];
  627. if (typeof data !== 'string') {
  628. // get rid of the nested arrays
  629. for (var i = 0; i < rows.length; i++) {
  630. if (rows[i].length > 0) {
  631. newrows.push(rows[i][0]);
  632. }
  633. }
  634. // separate users into their own array
  635. for (var i = 0; i < newrows.length; i++) {
  636. temp.push(newrows[i].user.charAt(0).toUpperCase() + newrows[i].user.slice(1));
  637. }
  638. // compare the users in the data array against the temp array
  639. // if not found, push them to rows with 0 points
  640. for (var i = 0; i < data.length; i++) {
  641. if (temp.indexOf(data[i]) < 0) {
  642. newrows.push({'user' : data[i], 'points' : 0});
  643. }
  644. }
  645. // capitalize usernames on rows
  646. for (var key in newrows) {
  647. if (newrows.hasOwnProperty(key)) {
  648. newrows[key].user = newrows[key].user.charAt(0).toUpperCase() + newrows[key].user.slice(1);
  649. }
  650. }
  651. rows = newrows;
  652. } else {
  653. if (rows.length === 0) {
  654. rows = [{'user' : data, 'points' : 0}];
  655. } else {
  656. rows[0].user = rows[0].user.charAt(0).toUpperCase() + rows[0].user.slice(1);
  657. }
  658. }
  659. callback(rows);
  660. });
  661. };
  662. /**
  663. * ============================================
  664. * HANDOUT CURRENCY
  665. * --------------------------------------------
  666. */
  667. Currency.prototype.handout_coins = function () {
  668. var __self = this;
  669. // check stream status
  670. function stream_status() {
  671. var time = utils.make_interval(__self.streaming_check);
  672. if (time === 0) {
  673. // get stream status
  674. https.get('https://api.twitch.tv/kraken/streams/' + __self.irc.config.channel.slice(1), function (response) {
  675. var body = '';
  676. // put together response
  677. response.on('data', function (chunk) {
  678. body += chunk;
  679. });
  680. // start / stop handing out coins based on stream status
  681. response.on('end', function () {
  682. var json = JSON.parse(body);
  683. __self.streaming = json.stream !== null;
  684. if (__self.streaming && __self.give_coins === false) {
  685. insert_coins();
  686. }
  687. __self.irc.emit('data', 'DATA - Online Status Check - Returned: ' + __self.streaming);
  688. setTimeout(stream_status, 1000);
  689. });
  690. });
  691. } else {
  692. setTimeout(stream_status, time);
  693. }
  694. }
  695. // get subscribers
  696. function subscribers() {
  697. var time = utils.make_interval(__self.subscriber_check);
  698. if (time === 0) {
  699. // get stream status
  700. http.get(__self.config.subscribers_json, function (response) {
  701. var body = '';
  702. // put together response
  703. response.on('data', function (chunk) {
  704. body += chunk;
  705. });
  706. // start / stop handing out coins based on stream status
  707. response.on('end', function () {
  708. var json = JSON.parse(body);
  709. var entries = json.feed.entry, subs = '';
  710. __self.subscribers = [];
  711. for (var i = 0; i < entries.length; i++) {
  712. __self.subscribers.push(entries[i].title['$t']);
  713. subs += entries[i].title['$t'] + ' ';
  714. }
  715. __self.irc.emit('data', 'DATA - Subscriber Check - Returned: ' + subs);
  716. setTimeout(subscribers, 1000);
  717. });
  718. });
  719. } else {
  720. setTimeout(subscribers, time);
  721. }
  722. }
  723. // trigger coin handout
  724. function insert_coins() {
  725. __self.give_coins = __self.streaming;
  726. console.log('DATA - Inserting coins');
  727. if (__self.give_coins) {
  728. var time = utils.make_interval(__self.give_coins_timer);
  729. if (time === 0) {
  730. // build sql from the saved viewer list
  731. var sql = '';
  732. for (var i = 0; i < __self.viewer_list.length; i++) {
  733. var currency_amount = __self.subscribers.indexOf(__self.viewer_list[i]) >= 0 ? 2 : 1;
  734. if (__self.viewer_list[i] !== '') {
  735. if (i != __self.viewer_list.length - 1) {
  736. sql += 'INSERT INTO viewers (user, points) ';
  737. sql += 'VALUES (\'' + __self.viewer_list[i] + '\', ' + currency_amount + ') ';
  738. sql += 'ON DUPLICATE KEY UPDATE points = points + ' + currency_amount + '; ';
  739. } else {
  740. sql += 'INSERT INTO viewers (user, points) ';
  741. sql += 'VALUES (\'' + __self.viewer_list[i] + '\', ' + currency_amount + ') ';
  742. sql += 'ON DUPLICATE KEY UPDATE points = points + ' + currency_amount;
  743. }
  744. }
  745. }
  746. // execute query
  747. __self.db.execute(sql, function () {});
  748. setTimeout(insert_coins, 1000);
  749. } else {
  750. setTimeout(insert_coins, time);
  751. }
  752. }
  753. }
  754. // monitor viewers in irc
  755. __self.irc.on('data', function (data) {
  756. var data_split = data.split(' '), viewer = '';
  757. // viewers from \who
  758. // TODO: new twitch chat doesn't allow /who, remove this?
  759. if (data_split[3] == '352') {
  760. if (data_split[6] !== undefined) {
  761. viewer = data_split[6].toLowerCase();
  762. if (__self.viewer_list.indexOf(viewer) < 0 && __self.config.ignorelist.indexOf(viewer) < 0) {
  763. __self.viewer_list.push(viewer);
  764. }
  765. }
  766. }
  767. // Processing below replaces the now defunct who-calls above
  768. // handle /names
  769. if (data_split[3] == '353'){
  770. viewers = data_split.splice(7);
  771. viewers.forEach(function(name) {
  772. if(name.charAt(0) === ':') name = name.slice(1);
  773. if (__self.viewer_list.indexOf(name) < 0 && __self.config.ignorelist.indexOf(name) < 0) {
  774. __self.viewer_list.push(name);
  775. }
  776. });
  777. }
  778. // handle JOIN's
  779. if (data_split[3] == 'JOIN') {
  780. var servernick = data_split[2].toLowerCase().split('!');
  781. viewer = servernick[0];
  782. if (viewer != __self.irc.config.name.toLowerCase()) {
  783. viewer = viewer.slice(1);
  784. }
  785. if (__self.viewer_list.indexOf(viewer) < 0 && __self.config.ignorelist.indexOf(viewer) < 0) {
  786. __self.viewer_list.push(viewer);
  787. } else {
  788. }
  789. }
  790. // handle PART's
  791. if (data_split[3] == 'PART') {
  792. var servernick = data_split[2].toLowerCase().split('!');
  793. viewer = servernick[0];
  794. if (viewer != __self.irc.config.name.toLowerCase()) {
  795. viewer = viewer.slice(1);
  796. }
  797. var viewer_idx = __self.viewer_list.indexOf(viewer);
  798. if (viewer_idx >= 0) {
  799. __self.viewer_list.splice(viewer_idx,1);
  800. } else {
  801. console.log("[*ERROR*] User "+viewer+" PART'ed but was not in viewer_list.");
  802. }
  803. }
  804. // viewers chatting
  805. if (data_split[3] == 'PRIVMSG') {
  806. var servernick = data_split[2].toLowerCase().split('!');
  807. viewer = servernick[0];
  808. if (viewer != __self.irc.config.name.toLowerCase()) {
  809. viewer = viewer.slice(1);
  810. }
  811. // add missing chatters to viewer_list
  812. if (__self.viewer_list.indexOf(viewer) < 0 && __self.config.ignorelist.indexOf(viewer) < 0) {
  813. __self.viewer_list.push(viewer);
  814. console.log("[*ADD NAME*] "+viewer+" from CHAT");
  815. }
  816. // log chat if enabled
  817. if (__self.irc.store_chat && __self.config.ignorelist.indexOf(viewer) < 0) {
  818. file.exists(__self.irc.chat_log, function (exists) {
  819. if (exists) {
  820. // get a timestamp
  821. var date = new Date(),
  822. hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
  823. min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
  824. sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
  825. streaming_time = '';
  826. // create start time string
  827. streaming_time += hours.toString() + ':' + min.toString();
  828. // craft message
  829. data_split[5] = data_split[5].slice(1);
  830. var message = data_split.slice(5).join(' ');
  831. // put it all together
  832. var logline = '[' + streaming_time + '] <' + viewer + '> ' + message + '\r\n';
  833. file.appendFile(__self.irc.chat_log, logline, 'utf-8', function (err) {
  834. if (err) {
  835. throw err;
  836. }
  837. });
  838. }
  839. });
  840. }
  841. }
  842. });
  843. stream_status();
  844. // only start subscribers if gdoc is available
  845. if (__self.config.subscribers_json !== '') {
  846. subscribers();
  847. }
  848. };
  849. /**
  850. * ============================================
  851. * Adjust Currency
  852. * --------------------------------------------
  853. */
  854. Currency.prototype.adjust_currency = function (method, amount, viewer) {
  855. var __self = this;
  856. viewer = viewer.toLowerCase();
  857. __self.db.execute('SELECT * FROM viewers WHERE user=\'' + viewer + '\'', function(rows){
  858. if (rows.length > 0 || method === 'push') {
  859. var check = rows.length > 0 ? rows[0].user : rows.push({user: viewer});
  860. if (check === viewer || method === 'push') {
  861. var sql = '', settings = [];
  862. // push settings for message
  863. if (method === 'add' || method === 'push') {
  864. settings.push('+');
  865. settings.push('Added');
  866. settings.push('to');
  867. } else if (method === 'remove') {
  868. settings.push('-');
  869. settings.push('Removed');
  870. settings.push('from');
  871. }
  872. settings.push(rows[0].user.charAt(0).toUpperCase() + rows[0].user.slice(1));
  873. // create sql
  874. if (method === 'add' || method === 'remove') {
  875. sql += 'UPDATE viewers ';
  876. sql += 'SET points = points ' + settings[0] + ' ' + amount + ' ';
  877. sql += 'WHERE user = \'' + rows[0].user + '\'; ';
  878. } else if (method === 'push') {
  879. sql += 'INSERT INTO viewers (user, points) ';
  880. sql += 'VALUES (\'' + viewer + '\', ' + amount + ') ';
  881. sql += 'ON DUPLICATE KEY UPDATE points = points + ' + amount + '; ';
  882. }
  883. //execute adjustment
  884. __self.db.execute(sql, function(){
  885. __self.irc.emit('message', {message:__self.pre_text + settings[1] + ' ' + amount + ' ' + __self.config.currency + ' ' + settings[2] + ' ' + settings[3]});
  886. });
  887. }
  888. } else {
  889. __self.irc.emit('message', {message:__self.pre_text + 'User was not found, use the push command to add a new user'});
  890. }
  891. });
  892. };
  893. /**
  894. * ============================================
  895. * AUCTION SYSTEM
  896. * --------------------------------------------
  897. */
  898. Currency.prototype.auction = function (status) {
  899. var __self = this;
  900. switch (status) {
  901. case true:
  902. if (!__self.votes_status) {
  903. if (!__self.bets_status) {
  904. if (!__self.raffle_status) {
  905. if (!__self.auction_status) {
  906. // open up the auction
  907. __self.auction_status = true;
  908. // request toggle
  909. if (__self.temp.raffle_toggle) {
  910. __self.temp.auction_toggle = __self.temp.raffle_toggle;
  911. } else {
  912. __self.temp.auction_toggle = __self.coin_toggle;
  913. }
  914. __self.coin_toggle = false;
  915. // default request timer
  916. if (__self.temp.raffle_timer && __self.temp.raffle_timer_reset) {
  917. __self.temp.auction_timer = __self.temp.raffle_timer;
  918. __self.temp.auction_timer_reset = __self.temp.raffle_timer_reset;
  919. } else {
  920. __self.temp.auction_timer = __self.coin_response_timer;
  921. __self.temp.auction_timer_reset = __self.coin_response_reset;
  922. }
  923. __self.coin_response_timer = 3000;
  924. __self.coin_response_reset = true;
  925. // clear previous bids
  926. __self.auction_bids = [];
  927. __self.auction_previous_bid = {};
  928. // auction open response
  929. __self.irc.emit('message', {message:__self.pre_text + 'Auction opened, accepting bids'})
  930. } else {
  931. // auction is already open response
  932. __self.irc.emit('message', {message:__self.pre_text + 'Auction already in progress'});
  933. }
  934. } else {
  935. // raffle currently running
  936. __self.irc.emit('message', {message:__self.pre_text + 'You must close the raffle before you can open an auction'});
  937. }
  938. } else {
  939. // gambling currently running
  940. __self.irc.emit('message', {message:__self.pre_text + 'Betting must be closed before you can open an auction'});
  941. }
  942. }
  943. break;
  944. case false:
  945. if (__self.auction_status) {
  946. // close the auction
  947. __self.auction_status = false;
  948. // request toggle
  949. __self.coin_toggle = __self.temp.auction_toggle;
  950. delete __self.temp.auction_toggle;
  951. // default request timer
  952. __self.coin_response_timer = __self.temp.auction_timer;
  953. __self.coin_response_reset = __self.temp.auction_timer_reset;
  954. delete __self.temp.auction_timer;
  955. delete __self.temp.auction_timer_reset;
  956. // clear response timers
  957. clearTimeout(__self.auction_bid_response);
  958. clearInterval(__self.auction_bid_response_long);
  959. if (__self.auction_bids.length > 0) {
  960. // pick a winner response
  961. for (var i = 0; i < __self.auction_bids.length; i++) {
  962. if (__self.auction_bids[i].bid === utils.max(__self.auction_bids)) {
  963. __self.irc.emit('message', {message:__self.pre_text + 'Auction closed, Winner: ' + __self.auction_bids[i].viewer + ' @ ' + __self.auction_bids[i].bid});
  964. // save the winners info for draw refund
  965. __self.auction_previous_bid.viewer = __self.auction_bids[i].viewer;
  966. __self.auction_previous_bid.bid = __self.auction_bids[i].bid;
  967. // remove winners money
  968. var sql = '';
  969. sql += 'UPDATE viewers ';
  970. sql += 'SET points = points - ' + __self.auction_bids[i].bid + ' ';
  971. sql += 'WHERE user = \'' + __self.auction_bids[i].viewer + '\'';
  972. __self.db.execute(sql, function() {});
  973. // remove winner from main list
  974. __self.auction_bids.splice(i, 1);
  975. break;
  976. }
  977. }
  978. } else {
  979. // no bidders to pick from response
  980. __self.irc.emit('message', {message:__self.pre_text + 'Auction closed, no bidders to pick a winner'});
  981. }
  982. } else {
  983. // auction is already open response
  984. __self.irc.emit('message', {message:__self.pre_text + 'Auction is already closed'});
  985. }
  986. break;
  987. case 'cancel':
  988. if (__self.auction_status) {
  989. // close the auction
  990. __self.auction_status = false;
  991. // request toggle
  992. __self.coin_toggle = __self.temp.auction_toggle;
  993. delete __self.temp.auction_toggle;
  994. // default request timer
  995. __self.coin_response_timer = __self.temp.auction_timer;
  996. __self.coin_response_reset = __self.temp.auction_timer_reset;
  997. delete __self.temp.auction_timer;
  998. delete __self.temp.auction_timer_reset;
  999. // clear response timers
  1000. clearTimeout(__self.auction_bid_response);
  1001. clearInterval(__self.auction_bid_response_long);
  1002. // clear previous bids
  1003. __self.auction_bids = [];
  1004. __self.auction_previous_bid = {};
  1005. // auction cancelled notification
  1006. __self.irc.emit('message', {message:__self.pre_text + 'Auction has been cancelled'});
  1007. } else {
  1008. // auction cancelled notification
  1009. __self.irc.emit('message', {message:__self.pre_text + 'Auction is not opened'});
  1010. }
  1011. break;
  1012. }
  1013. };
  1014. Currency.prototype.bid = function (caller, amount) {
  1015. var __self = this;
  1016. function find_duplicate(amount) {
  1017. var duplicate = false;
  1018. for (var i = 0; i < __self.auction_bids.length; i++) {
  1019. if (__self.auction_bids[i].bid === amount) {
  1020. duplicate = true;
  1021. break;
  1022. }
  1023. }
  1024. return duplicate;
  1025. }
  1026. if (__self.auction_status) {
  1027. // verify that bidder has the coins for bidding
  1028. __self.query_coins(caller, function (rows) {
  1029. var has_tickets = false;
  1030. // only add bid if they have the enough to pay
  1031. if (rows[0].points >= amount) {
  1032. if (__self.auction_bids.length > 0) {
  1033. // check if an existing bid exists and modify it
  1034. for (var i = 0; i < __self.auction_bids.length; i++) {
  1035. if (__self.auction_bids[i].viewer === caller) {
  1036. has_tickets = true;
  1037. // check if bid is higher then original and not a duplicate
  1038. if (__self.auction_bids[i].bid < amount && !find_duplicate(amount)) {
  1039. __self.auction_bids[i].bid = amount;
  1040. }
  1041. break;
  1042. }
  1043. }
  1044. // add new bids to list if they are not a duplicate
  1045. if (!has_tickets && !find_duplicate(amount)) {
  1046. __self.auction_bids.push({viewer: caller, bid: amount});
  1047. }
  1048. } else {
  1049. // push first bid
  1050. __self.auction_bids.push({viewer: caller, bid: amount});
  1051. }
  1052. }
  1053. // clear timers on flood
  1054. clearTimeout(__self.auction_bid_response);
  1055. clearInterval(__self.auction_bid_response_long);
  1056. // reply after set amount of bids
  1057. if ((__self.auction_bids.length % __self.max_requests) === 0) {
  1058. // bulk flood response
  1059. for (var i = 0; i < __self.auction_bids.length; i++) {
  1060. if (__self.auction_bids[i].bid === utils.max(__self.auction_bids)) {
  1061. __self.irc.msg(__self.pre_text + 'Highest bid, ' + __self.auction_bids[i].viewer + ' @ ' + __self.auction_bids[i].bid);
  1062. }
  1063. }
  1064. } else {
  1065. // response after time without flood has passed
  1066. var viewer, bid;
  1067. for (var i = 0; i < __self.auction_bids.length; i++) {
  1068. if (__self.auction_bids[i].bid === utils.max(__self.auction_bids)) {
  1069. viewer = __self.auction_bids[i].viewer;
  1070. bid = __self.auction_bids[i].bid;
  1071. }
  1072. }
  1073. if (viewer !== undefined && bid !== undefined && __self.auction_status) {
  1074. var msg = __self.pre_text + 'Highest bid, ' + viewer + ' @ ' + bid;
  1075. __self.auction_bid_response = setTimeout(function () {__self.irc.emit('message', {message:msg, timer: 1});}, 5000);
  1076. __self.auction_bid_response_long = setInterval(function () {__self.irc.emit('message', {message:msg, timer: 1});}, 30000);
  1077. }
  1078. }
  1079. });
  1080. }
  1081. };
  1082. Currency.prototype.next_auction_winner = function () {
  1083. var __self = this, empty_list = [];
  1084. // custom dialog when the bidder list is empty
  1085. empty_list.push('Hey, I just met you and this is crazy, but there\'s no more bidders, so start an new auction maybe?');
  1086. empty_list.push('Are there more bidders? Well, to tell you the truth, in all this excitement I kind of lost track myself.');
  1087. empty_list.push('Heyyyyyy there\'s no more bidders, Op, op, op, op, Open Auction Style.');
  1088. empty_list.push('Da bids! Da bids! Where are all da bids, boss?');
  1089. if (!__self.auction_status) {
  1090. // get next highest bidder or prompt to open new auction
  1091. if (__self.auction_bids.length > 0) {
  1092. for (var i = 0; i < __self.auction_bids.length; i++) {
  1093. if (__self.auction_bids[i].bid === utils.max(__self.auction_bids)) {
  1094. __self.irc.emit('message',{message:__self.pre_text + 'Drawing the next highest bid: ' + __self.auction_bids[i].viewer + ' @ ' + __self.auction_bids[i].bid});
  1095. // refund previous winner's money
  1096. var sql = '';
  1097. sql += 'UPDATE viewers ';
  1098. sql += 'SET points = points + ' + __self.auction_previous_bid.bid + ' ';
  1099. sql += 'WHERE user = \'' + __self.auction_previous_bid.viewer + '\'';
  1100. __self.db.execute(sql, function() {});
  1101. // save the new winner's info for next draw
  1102. __self.auction_previous_bid.viewer = __self.auction_bids[i].viewer;
  1103. __self.auction_previous_bid.bid = __self.auction_bids[i].bid;
  1104. // remove winners money
  1105. sql = '';
  1106. sql += 'UPDATE viewers ';
  1107. sql += 'SET points = points - ' + __self.auction_bids[i].bid + ' ';
  1108. sql += 'WHERE user = \'' + __self.auction_bids[i].viewer + '\'';
  1109. __self.db.execute(sql, function() {});
  1110. // remove winner from main list
  1111. __self.auction_bids.splice(i, 1);
  1112. break;
  1113. }
  1114. }
  1115. } else {
  1116. // check if a previous viewer is saved
  1117. if (__self.auction_previous_bid.viewer !== null) {
  1118. // refund previous winner's money
  1119. var sql = '';
  1120. sql += 'UPDATE viewers ';
  1121. sql += 'SET points = points + ' + __self.auction_previous_bid.bid + ' ';
  1122. sql += 'WHERE user = \'' + __self.auction_previous_bid.viewer + '\'';
  1123. __self.db.execute(sql, function() {});
  1124. // clear previous bid
  1125. __self.auction_previous_bid = {};
  1126. }
  1127. // notify that there's no more bids
  1128. __self.irc.emit('message',{message:__self.pre_text + utils.selectRandomArrayItem(empty_list)});
  1129. }
  1130. }
  1131. };
  1132. /**
  1133. * ============================================
  1134. * RAFFLE SYSTEM
  1135. * --------------------------------------------
  1136. */
  1137. Currency.prototype.raffle = function (status) {
  1138. var __self = this;
  1139. switch (status) {
  1140. case true:
  1141. if (!__self.votes_status) {
  1142. if (!__self.bets_status) {
  1143. if (!__self.auction_status) {
  1144. if (!__self.raffle_status) {
  1145. // open up a raffle
  1146. __self.raffle_status = true;
  1147. // request toggle
  1148. if (__self.temp.auction_toggle) {
  1149. __self.temp.raffle_toggle = __self.temp.auction_toggle;
  1150. } else {
  1151. __self.temp.raffle_toggle = __self.coin_toggle;
  1152. }
  1153. __self.coin_toggle = false;
  1154. // default request timer
  1155. if (__self.temp.auction_timer && __self.temp.auction_timer_reset) {
  1156. __self.temp.raffle_timer = __self.temp.auction_timer;
  1157. __self.temp.raffle_timer_reset = __self.temp.auction_timer_reset;
  1158. } else {
  1159. __self.temp.raffle_timer = __self.coin_response_timer;
  1160. __self.temp.raffle_timer_reset = __self.coin_response_reset;
  1161. }
  1162. __self.coin_response_timer = 3000;
  1163. __self.coin_response_reset = true;
  1164. // save previous raffle settings in case
  1165. // a new one is opened on accident
  1166. __self.raffle_restore_ticket_requests = __self.raffle_ticket_requests;
  1167. __self.raffle_restore_tickets = __self.raffle_tickets;
  1168. // clear previous tickets
  1169. __self.raffle_ticket_requests = [];
  1170. __self.raffle_tickets = [];
  1171. // raffle open response
  1172. __self.irc.emit('message',{message:__self.pre_text + 'Raffle opened'});
  1173. __self.irc.emit('message',{message:'+ Tickets cost ' + __self.raffle_ticket_cost + ' ' + __self.config.currency.toLowerCase() + ' / Maximum of ' + __self.raffle_max_tickets + ' tickets per viewer'});
  1174. } else {
  1175. // raffle in progress response
  1176. __self.irc.emit('message',{message:__self.pre_text + 'Raffle already in progress'});
  1177. }
  1178. } else {
  1179. // auction in progress
  1180. __self.irc.emit('message', {message:__self.pre_text + 'You must close the auction before you can open an a raffle'});
  1181. }
  1182. } else {
  1183. // gambling currently running
  1184. __self.irc.emit('message', {message:__self.pre_text + 'Betting must be closed before you can open a raffle'});
  1185. }
  1186. }
  1187. break;
  1188. case false:
  1189. if (__self.raffle_status) {
  1190. // close the raffle
  1191. __self.raffle_status = false;
  1192. // request toggle
  1193. __self.coin_toggle = __self.temp.raffle_toggle;
  1194. delete __self.temp.raffle_toggle;
  1195. // default request timer
  1196. __self.coin_response_timer = __self.temp.raffle_timer;
  1197. __self.coin_response_reset = __self.temp.raffle_timer_reset;
  1198. delete __self.temp.raffle_timer;
  1199. delete __self.temp.raffle_timer_reset;
  1200. // validation / winner / deduction
  1201. __self.raffle_winner();
  1202. } else {
  1203. // raffle is already open response
  1204. __self.irc.emit('message',{message:__self.pre_text + 'Raffle is already closed'});
  1205. }
  1206. break;
  1207. case 'cancel':
  1208. if (__self.raffle_status) {
  1209. // close the raffle
  1210. __self.raffle_status = false;
  1211. // request toggle
  1212. __self.coin_toggle = __self.temp.raffle_toggle;
  1213. delete __self.temp.raffle_toggle;
  1214. // default request timer
  1215. __self.coin_response_timer = __self.temp.raffle_timer;
  1216. __self.coin_response_reset = __self.temp.raffle_timer_reset;
  1217. delete __self.temp.raffle_timer;
  1218. delete __self.temp.raffle_timer_reset;
  1219. // clear previous tickets
  1220. __self.raffle_ticket_requests = [];
  1221. __self.raffle_tickets = [];
  1222. // raffle cancelled notification
  1223. __self.irc.emit('message', {message:__self.pre_text + 'Raffle has been cancelled'});
  1224. } else {
  1225. // raffle cancelled notification
  1226. __self.irc.emit('message', {message:__self.pre_text + 'Raffle is not opened'});
  1227. }
  1228. break;
  1229. case 'restore':
  1230. if (__self.raffle_status) {
  1231. // close raffle
  1232. __self.raffle_status = false;
  1233. // restore previous raffle tickets
  1234. __self.raffle_ticket_requests = __self.raffle_restore_ticket_requests;
  1235. __self.raffle_tickets = __self.raffle_restore_tickets;
  1236. __self.irc.emit('message', {message:__self.pre_text + 'Previous raffle has been restored'});
  1237. } else {
  1238. // raffle restore failed notification
  1239. __self.irc.emit('message', {message:__self.pre_text + 'Raffle is closed, unable to restore'});
  1240. }
  1241. break;
  1242. }
  1243. };
  1244. Currency.prototype.collect_tickets = function (caller, amount) {
  1245. var __self = this, has_tickets = false;
  1246. if (__self.raffle_ticket_requests.length > 0) {
  1247. // check if viewer already has tickets
  1248. for (var i = 0; i < __self.raffle_ticket_requests.length; i++) {
  1249. if (__self.raffle_ticket_requests[i].viewer === caller) {
  1250. has_tickets = true;
  1251. if (amount <= __self.raffle_max_tickets && amount >= 1) {
  1252. __self.raffle_ticket_requests[i].tickets = amount;
  1253. } else if (amount === 0) {
  1254. __self.raffle_ticket_requests.splice(i, 1);
  1255. }
  1256. break;
  1257. }
  1258. }
  1259. // if viewer doesn't have tickets and meets > 1 < max req add their request
  1260. if (!has_tickets && amount <= __self.raffle_max_tickets && amount >= 1 && amount !== 0) {
  1261. __self.raffle_ticket_requests.push({viewer: caller, tickets: amount});
  1262. }
  1263. } else {
  1264. // push first ticket if > 1 < max
  1265. if (amount <= __self.raffle_max_tickets && amount >= 1 && amount !== 0) {
  1266. __self.raffle_ticket_requests.push({viewer: caller, tickets: amount});
  1267. }
  1268. }
  1269. };
  1270. Currency.prototype.raffle_winner = function () {
  1271. var __self = this, sql = '';
  1272. if (__self.raffle_ticket_requests.length > 0) {
  1273. // setup sql to grab all viewers that request coins from the database
  1274. sql += 'SELECT * FROM viewers WHERE ';
  1275. for (var i = 0; i < __self.raffle_ticket_requests.length; i++) {
  1276. if (i !== __self.raffle_ticket_requests.length - 1) {
  1277. sql += 'user=\'' + __self.raffle_ticket_requests[i].viewer.toLowerCase() + '\' OR ';
  1278. } else {
  1279. sql += 'user=\'' + __self.raffle_ticket_requests[i].viewer.toLowerCase() + '\'';
  1280. }
  1281. }
  1282. // execute viewer search query
  1283. __self.db.execute(sql, function(rows) {
  1284. // currency validation
  1285. // - this takes the results of the query and uses the names from the database
  1286. // to filter through the viewers that requested tickets (since they have to be in the
  1287. // database in the first place)
  1288. // - during the filtering process the viewers requested tickets are multiplied by the
  1289. // ticket cost and compared against their currency amount
  1290. // - if the viewer has the funds, their tickets are added and the sql is updated to include their
  1291. // deduction
  1292. sql = '';
  1293. for (var i = 0; i < rows.length; i++) {
  1294. for (var j = 0; j < __self.raffle_ticket_requests.length; j++) {
  1295. if (__self.raffle_ticket_requests[j].viewer.toLowerCase() === rows[i].user) {
  1296. var money = __self.raffle_ticket_requests[j].tickets * __self.raffle_ticket_cost;
  1297. if (rows[i].points >= money) {
  1298. for (var k = 1; k <= __self.raffle_ticket_requests[j].tickets; k++) {
  1299. __self.raffle_tickets.push(__self.raffle_ticket_requests[j].viewer);
  1300. }
  1301. if (i !== rows.length - 1) {
  1302. sql += 'UPDATE viewers ';
  1303. sql += 'SET points = points - ' + money + ' ';
  1304. sql += 'WHERE user = \'' + rows[i].user + '\'; ';
  1305. } else {
  1306. sql += 'UPDATE viewers ';
  1307. sql += 'SET points = points - ' + money + ' ';
  1308. sql += 'WHERE user = \'' + rows[i].user + '\'';
  1309. }
  1310. }
  1311. break;
  1312. }
  1313. }
  1314. }
  1315. // randomize array before selecting a random winner
  1316. __self.raffle_tickets.sort(function () {return 0.5 - Math.random();});
  1317. // select random ticket from array
  1318. var winner = utils.selectRandomArrayItem(__self.raffle_tickets);
  1319. // count winner's tickets
  1320. var winning_ticket_amount;
  1321. for (var i = 0; i < __self.raffle_ticket_requests.length; i++) {
  1322. if (__self.raffle_ticket_requests[i].viewer === winner) {
  1323. winning_ticket_amount = __self.raffle_ticket_requests[i].tickets;
  1324. break;
  1325. }
  1326. }
  1327. // output winner to chat
  1328. __self.irc.emit('message', {message:__self.pre_text + 'Raffle closed, ' + __self.raffle_tickets.length + ' tickets purchased!'});
  1329. __self.irc.emit('message', {message:'+ Winner: ' + winner + ' (' + winning_ticket_amount + ' tickets purchased)'});
  1330. // remove one ticket from raffle bowl
  1331. if (__self.raffle_tickets.indexOf(winner) >= 0 ) {
  1332. __self.raffle_tickets.splice(__self.raffle_tickets.indexOf(winner), 1);
  1333. }
  1334. // execute query
  1335. __self.db.execute(sql, function () {});
  1336. });
  1337. } else {
  1338. // no tickets to pick from response
  1339. __self.irc.emit('message', {message:__self.pre_text + 'Raffle closed, no tickets to draw a winner'});
  1340. }
  1341. };
  1342. Currency.prototype.next_raffle_winner = function () {
  1343. var __self = this, empty_list = [];
  1344. // custom dialog when there are no more raffle tickets
  1345. empty_list.push('Hey, I just met you and this is crazy, but there\'s no more tickets, so start an new raffle maybe?');
  1346. empty_list.push('Are there more tickets? Well, to tell you the truth, in all this excitement I kind of lost track myself.');
  1347. empty_list.push('Heyyyyyy there\'s no more tickets, Op, op, op, op, Open Raffle Style.');
  1348. empty_list.push('Da tickets! Da tickets! Where are all da tickets, boss?');
  1349. if (!__self.raffle_status) {
  1350. // draw next ticket or prompt to open new raffle
  1351. if (__self.raffle_tickets.length > 0) {
  1352. // randomize array before selecting a random winner
  1353. __self.raffle_tickets.sort(function () {return 0.5 - Math.random();});
  1354. // select random ticket from array
  1355. var winner = utils.selectRandomArrayItem(__self.raffle_tickets);
  1356. // count next winner's tickets
  1357. var winning_ticket_amount;
  1358. for (var i = 0; i < __self.raffle_ticket_requests.length; i++) {
  1359. if (__self.raffle_ticket_requests[i].viewer === winner) {
  1360. winning_ticket_amount = __self.raffle_ticket_requests[i].tickets;
  1361. break;
  1362. }
  1363. }
  1364. // output winner to chat
  1365. __self.irc.emit('message', {message:__self.pre_text + 'Drawing next ticket'});
  1366. __self.irc.emit('message', {message:'+ Winner: ' + winner + ' (' + winning_ticket_amount + ' tickets purchased)'});
  1367. // remove one ticket from raffle bowl
  1368. if (__self.raffle_tickets.indexOf(winner) >= 0 ) {
  1369. __self.raffle_tickets.splice(__self.raffle_tickets.indexOf(winner), 1);
  1370. }
  1371. } else {
  1372. __self.irc.emit('message', {message:__self.pre_text + utils.selectRandomArrayItem(empty_list)});
  1373. }
  1374. }
  1375. };
  1376. /*
  1377. * VOTING SYSTEM
  1378. * ------------
  1379. */
  1380. Currency.prototype.votes = function(status, data) {
  1381. var __self = this;
  1382. switch(status){
  1383. case true:
  1384. if (!__self.bets_status) {
  1385. if (!__self.auction_status) {
  1386. if (!__self.raffle_status) {
  1387. if (!__self.votes_status && !__self.votes_payout) {
  1388. var wager_msg = '';
  1389. __self.votes_status = true;
  1390. __self.votes_payout = true;
  1391. __self.votes_board = [];
  1392. __self.votes_viewers = [];
  1393. __self.votes_total = 0;
  1394. __self.votes_board = data.join().split(',').filter(function(n){return n}).slice(6).map(function(n){return {name: n, num: 0, total: 0};});
  1395. for (var i = 0; i < __self.votes_board.length; i++) {
  1396. __self.votes_board[i].idx = i;
  1397. }
  1398. for (var i = 0; i < __self.votes_board.length; i++) {
  1399. if (i !== __self.votes_board.length - 1) {
  1400. wager_msg += '"!' + __self.votes_board[i].name + '" / ';
  1401. } else {
  1402. wager_msg += '"!' + __self.votes_board[i].name + '"';
  1403. }
  1404. }
  1405. // output to chat
  1406. __self.irc.emit('message', {message:__self.pre_text + 'Voting is now open'});
  1407. __self.irc.emit('message', {message:'+ Type ' + wager_msg + ' and the vote amount to enter'});
  1408. } else {
  1409. if (__self.votes_payout) {
  1410. // payout pending message
  1411. __self.irc.emit('message', {message:__self.pre_text + 'Unable to take new votes until the last has been decided'});
  1412. } else {
  1413. __self.irc.emit('message', {message:__self.pre_text + 'Voting already in progress'});
  1414. }
  1415. }
  1416. // FIXME: messages below should be "cant open a vote until X is over/closed" instead? test it
  1417. } else {
  1418. // raffle in progress
  1419. __self.irc.emit('message', {message:__self.pre_text + 'Voting must be closed before you can open a raffle'});
  1420. }
  1421. } else {
  1422. // auction currently running
  1423. __self.irc.emit('message', {message:__self.pre_text + 'Voting must be closed before you can open an auction'});
  1424. }
  1425. }
  1426. break;
  1427. case false:
  1428. if (__self.votes_status && __self.votes_payout) {
  1429. __self.votes_status = false;
  1430. __self.votes_deduct_votes();
  1431. // output to chat
  1432. if (__self.votes_viewers.length > 0) {
  1433. __self.irc.emit('message', {message:__self.pre_text + 'Voting is now closed'});
  1434. for (var i = 0; i < __self.votes_board.length; i++) {
  1435. __self.irc.emit('message', {message:'+ ' + __self.votes_board[i].name + ' with ' + __self.votes_board[i].num + ' supporters totaling ' + __self.votes_board[i].total + ' votes'});
  1436. }
  1437. //
  1438. } else {
  1439. __self.irc.emit('message', {message:__self.pre_text + 'Voting closed, no votes were cast.'});
  1440. }
  1441. }
  1442. break;
  1443. case 'pool':
  1444. function do_work() {
  1445. if (__self.votes_board.length > 0) {
  1446. __self.irc.emit('message', {message:__self.pre_text + 'Current voting pool is:'});
  1447. for (var i = 0; i < __self.votes_board.length; i++) {
  1448. __self.irc.emit('message', {message:'+ ' + __self.votes_board[i].name + ' with ' + __self.votes_board[i].num + ' supporters totaling ' + __self.votes_board[i].total + ' votes'});
  1449. }
  1450. } else {
  1451. __self.irc.emit('message', {message:__self.pre_text + 'No current vote.'});
  1452. }
  1453. }
  1454. if (__self.votes_response_reset) {
  1455. __self.votes_response = setTimeout(function () {do_work();}, __self.votes_response_timer);
  1456. } else {
  1457. setTimeout(function () {do_work();}, __self.votes_response_timer);
  1458. }
  1459. break;
  1460. case 'winner':
  1461. if (!__self.votes_status) {
  1462. if (__self.votes_payout) {
  1463. for (var i = 0; i < __self.votes_board.length; i++) {
  1464. if (data == __self.votes_board[i].name) {
  1465. __self.votes_award_winner(__self.votes_board[i]);
  1466. __self.irc.emit('message', {message:__self.pre_text + 'Winner:' + data + 'had the most votes!'});
  1467. }
  1468. }
  1469. } else {
  1470. __self.irc.emit('message', {message:__self.pre_text + 'A winner has already been decided.'});
  1471. }
  1472. } else {
  1473. __self.irc.emit('message', {message:__self.pre_text + 'Voting must be closed before you can have a winner'});
  1474. }
  1475. break;
  1476. case 'cancel':
  1477. if (!__self.votes_status) {
  1478. // Return all the currency back to original owners
  1479. if (__self.votes_payout) {
  1480. sql = '';
  1481. for (var i = 0; i < __self.votes_viewers.length; i++) {
  1482. if (__self.votes_viewers[i].amount > 0) {
  1483. if (sql.length > 0) {
  1484. sql += '; ';
  1485. }
  1486. sql += 'UPDATE viewers ';
  1487. sql += 'SET points = points + ' + __self.votes_viewers[i].amount + ' ';
  1488. sql += 'WHERE user = \'' + __self.votes_viewers[i].viewer + '\'';
  1489. }
  1490. }
  1491. __self.db.execute(sql, function() {
  1492. __self.irc.emit('message', {message:__self.pre_text + 'Vote was canceled, all ' + __self.config.currency.toLowerCase() + ' returned.'});
  1493. });
  1494. __self.votes_payout = false;
  1495. } else {
  1496. __self.irc.emit('message', {message:__self.pre_text + 'No vote to cancel.'});
  1497. }
  1498. } else {
  1499. __self.votes_status = false;
  1500. __self.votes_payout = false;
  1501. __self.irc.emit('message', {message:__self.pre_text + 'Current vote was canceled.'});
  1502. }
  1503. break;
  1504. }
  1505. };
  1506. Currency.prototype.collect_votes = function (caller, vote, amount) {
  1507. var __self = this, has_vote = false;
  1508. function do_work() {
  1509. var multi_response = [];
  1510. for (var i = 0; i < __self.votes_board.length; i++) {
  1511. multi_response.push([]);
  1512. }
  1513. if (__self.votes_flood.length > 0) {// send flood requests
  1514. var vote;
  1515. // setup vote response
  1516. for (var i = 0; i < __self.votes_flood.length; i++) {
  1517. vote = __self.votes_viewers[__self.votes_flood[i]];
  1518. multi_response[vote.vote].push(vote.viewer + ' (' + vote.amount + ')');
  1519. }
  1520. for (var i = 0; i < __self.votes_board.length; i++) {
  1521. if (multi_response[i].length > 0) {
  1522. __self.irc.emit('message', {message:'New votes for ' + __self.votes_board[i].name + ': ' + multi_response[i].join(', '), timer: 1});
  1523. }
  1524. }
  1525. }
  1526. // clear flood requests
  1527. __self.votes_flood = [];
  1528. }
  1529. // Bound amount by positive currency
  1530. __self.query_coins(caller, function (rows) {
  1531. for (var i = 0; i < rows.length; i++) {
  1532. amount = Math.min(amount, rows[i].points);
  1533. }
  1534. if (__self.votes_viewers.length > 0) {
  1535. for (var i = 0; i < __self.votes_viewers.length; i++) {
  1536. if (__self.votes_viewers[i].viewer === caller) {
  1537. has_vote = true;
  1538. if (amount > __self.votes_viewers[i].amount) {
  1539. __self.votes_board[__self.votes_viewers[i].vote].num -= 1;
  1540. __self.votes_board[__self.votes_viewers[i].vote].total -= __self.votes_viewers[i].amount;
  1541. __self.votes_viewers[i].vote = vote.idx;
  1542. __self.votes_viewers[i].amount = amount;
  1543. __self.votes_board[vote.idx].num += 1;
  1544. __self.votes_board[vote.idx].total += amount;
  1545. // add flood users to array
  1546. if (__self.votes_flood.indexOf(i) < 0) {
  1547. __self.votes_flood.push(i);
  1548. }
  1549. }
  1550. break;
  1551. }
  1552. }
  1553. if (!has_vote && amount >= 1 && amount !== 0) {
  1554. __self.votes_viewers.push({viewer: caller, vote: vote.idx, amount: amount});
  1555. __self.votes_board[vote.idx].num += 1;
  1556. __self.votes_board[vote.idx].total += amount;
  1557. __self.votes_flood.push(__self.votes_viewers.length - 1);
  1558. }
  1559. } else {
  1560. if (amount >= 1 && amount !== 0) {
  1561. __self.votes_viewers.push({viewer: caller, vote: vote.idx, amount: amount});
  1562. __self.votes_board[vote.idx].num += 1;
  1563. __self.votes_board[vote.idx].total += amount;
  1564. __self.votes_flood.push(__self.votes_viewers.length - 1);
  1565. }
  1566. }
  1567. console.log(__self.votes_viewers);
  1568. // check if flood has a set amount of requests and output
  1569. // if not, set the output timer
  1570. if (__self.votes_flood.length === __self.max_requests) {
  1571. do_work();
  1572. } else {
  1573. if (__self.votes_response_reset) {
  1574. __self.votes_response = setTimeout(function () {do_work();}, __self.votes_response_timer);
  1575. } else {
  1576. setTimeout(function () {do_work();}, __self.votes_response_timer);
  1577. }
  1578. }
  1579. });
  1580. };
  1581. Currency.prototype.votes_deduct_votes = function () {
  1582. var __self = this;
  1583. if (__self.votes_viewers.length > 0) {
  1584. // Don't trust the on-the-fly numbers
  1585. for (var i = 0; i < __self.votes_board.length; i++) {
  1586. __self.votes_board[i].num = 0;
  1587. __self.votes_board[i].total = 0;
  1588. }
  1589. __self.votes_total = 0;
  1590. // Remove the points and add them to an escrow
  1591. sql = '';
  1592. for (var i = 0; i < __self.votes_viewers.length; i++) {
  1593. if (__self.votes_viewers[i].amount > 0) {
  1594. if (sql.length > 0) {
  1595. sql += '; ';
  1596. }
  1597. sql += 'UPDATE viewers ';
  1598. sql += 'SET points = points - ' + __self.votes_viewers[i].amount + ' ';
  1599. sql += 'WHERE user = \'' + __self.votes_viewers[i].viewer + '\'';
  1600. __self.votes_board[__self.votes_viewers[i].vote].num += 1;
  1601. __self.votes_board[__self.votes_viewers[i].vote].total += __self.votes_viewers[i].amount;
  1602. __self.votes_total += __self.votes_viewers[i].amount;
  1603. }
  1604. }
  1605. __self.db.execute(sql, function() {});
  1606. }
  1607. };
  1608. Currency.prototype.votes_award_winner = function (winner) {
  1609. var __self = this;
  1610. if (__self.votes_payout) {
  1611. // set payout to complete
  1612. __self.votes_payout = false;
  1613. }
  1614. // Clear the board
  1615. __self.votes_board = [];
  1616. __self.votes_viewers = [];
  1617. __self.votes_total = 0;
  1618. };
  1619. /**
  1620. * ============================================
  1621. * BETTING SYSTEM
  1622. * --------------------------------------------
  1623. */
  1624. Currency.prototype.bets = function(status, data) {
  1625. var __self = this;
  1626. switch(status){
  1627. case true:
  1628. if (!__self.auction_status) {
  1629. if (!__self.raffle_status) {
  1630. if (!__self.bets_status && !__self.bets_payout) {
  1631. var wager_msg = '';
  1632. // open up bets
  1633. __self.bets_status = true;
  1634. __self.bets_payout = true;
  1635. // clear previous board / bets
  1636. __self.bets_board = [];
  1637. __self.bets_viewers = [];
  1638. __self.bets_total = 0;
  1639. // create new betting board
  1640. __self.bets_board = data.join().split(',').filter(function(n){return n}).slice(6).map(function(n){return {name: n, num: 0, total: 0};});
  1641. for (var i = 0; i < __self.bets_board.length; i++) {
  1642. __self.bets_board[i].idx = i;
  1643. }
  1644. // create chat message on how to place a bet
  1645. for (var i = 0; i < __self.bets_board.length; i++) {
  1646. if (i !== __self.bets_board.length - 1) {
  1647. wager_msg += '"!' + __self.bets_board[i].name + '" / ';
  1648. } else {
  1649. wager_msg += '"!' + __self.bets_board[i].name + '"';
  1650. }
  1651. }
  1652. // output to chat
  1653. __self.irc.emit('message', {message:__self.pre_text + 'Betting is now open'});
  1654. __self.irc.emit('message', {message:'+ Type ' + wager_msg + ' and the bet amount to enter'});
  1655. } else {
  1656. if (__self.bets_payout) {
  1657. // payout pending message
  1658. __self.irc.emit('message', {message:__self.pre_text + 'Unable to take new bets until previous have been paid out'});
  1659. } else {
  1660. // gambling is already open response
  1661. __self.irc.emit('message', {message:__self.pre_text + 'Betting already in progress'});
  1662. }
  1663. }
  1664. // FIXME: messages below should be "cant open a bet until X is over/closed" instead? test it
  1665. } else {
  1666. // raffle in progress
  1667. __self.irc.emit('message', {message:__self.pre_text + 'Betting must be closed before you can open a raffle'});
  1668. }
  1669. } else {
  1670. // auction currently running
  1671. __self.irc.emit('message', {message:__self.pre_text + 'Betting must be closed before you can open an auction'});
  1672. }
  1673. break;
  1674. case false:
  1675. if (__self.bets_status && __self.bets_payout) {
  1676. // close out bets
  1677. __self.bets_status = false;
  1678. // deduct bets from viewers amounts
  1679. __self.bets_deduct_bets();
  1680. // output to chat
  1681. if (__self.bets_viewers.length > 0) {
  1682. __self.irc.emit('message', {message:__self.pre_text + 'Betting is now closed'});
  1683. for (var i = 0; i < __self.bets_board.length; i++) {
  1684. if(parseInt(__self.bets_board[i].total,10) > parseInt(__self.score_bet_pool, 10)) {
  1685. __self.score_bet_pool = __self.bets_board[i].total;
  1686. sql = 'INSERT INTO highscores (`value`, `name`) VALUES (\'' + __self.bets_board[i].total + '\', \'bet_pool\') ON DUPLICATE KEY UPDATE value=values(value);';
  1687. __self.db.execute(sql, function() {});
  1688. __self.irc.emit('message', {message:'+ ' + __self.bets_board[i].name + ' with ' + __self.bets_board[i].num + ' bets totaling ' + __self.bets_board[i].total + '. New record set!!'});
  1689. } else {
  1690. __self.irc.emit('message', {message:'+ ' + __self.bets_board[i].name + ' with ' + __self.bets_board[i].num + ' bets totaling ' + __self.bets_board[i].total});
  1691. }
  1692. }
  1693. //
  1694. } else {
  1695. __self.irc.emit('message', {message:__self.pre_text + 'Betting closed, no bets were placed'});
  1696. }
  1697. }
  1698. break;
  1699. case 'pool':
  1700. function do_work() {
  1701. if (__self.bets_board.length > 0) {
  1702. __self.irc.emit('message', {message:__self.pre_text + 'Current betting pool is:'});
  1703. for (var i = 0; i < __self.bets_board.length; i++) {
  1704. __self.irc.emit('message', {message:'+ ' + __self.bets_board[i].name + ' with ' + __self.bets_board[i].num + ' bets totaling ' + __self.bets_board[i].total});
  1705. }
  1706. } else {
  1707. __self.irc.emit('message', {message:__self.pre_text + 'No current bet.'});
  1708. }
  1709. }
  1710. if (__self.bets_response_reset) {
  1711. __self.bets_response = setTimeout(function () {do_work();}, __self.bets_response_timer);
  1712. } else {
  1713. setTimeout(function () {do_work();}, __self.bets_response_timer);
  1714. }
  1715. break;
  1716. case 'winner':
  1717. if (!__self.bets_status) {
  1718. if (__self.bets_payout) {
  1719. for (var i = 0; i < __self.bets_board.length; i++) {
  1720. if (data == __self.bets_board[i].name) {
  1721. __self.bets_award_winner(__self.bets_board[i]);
  1722. __self.irc.emit('message', {message:__self.pre_text + 'Betting payed out to ' + data});
  1723. }
  1724. }
  1725. } else {
  1726. __self.irc.emit('message', {message:__self.pre_text + 'Betting has already payed out'});
  1727. }
  1728. } else {
  1729. __self.irc.emit('message', {message:__self.pre_text + 'Betting must be closed before you can have a winner'});
  1730. }
  1731. break;
  1732. case 'cancel':
  1733. if (!__self.bets_status) {
  1734. // Return all the currency back to original owners
  1735. if (__self.bets_payout) {
  1736. sql = '';
  1737. for (var i = 0; i < __self.bets_viewers.length; i++) {
  1738. if (__self.bets_viewers[i].amount > 0) {
  1739. if (sql.length > 0) {
  1740. sql += '; ';
  1741. }
  1742. sql += 'UPDATE viewers ';
  1743. sql += 'SET points = points + ' + __self.bets_viewers[i].amount + ' ';
  1744. sql += 'WHERE user = \'' + __self.bets_viewers[i].viewer + '\'';
  1745. }
  1746. }
  1747. __self.db.execute(sql, function() {
  1748. __self.irc.emit('message', {message:__self.pre_text + 'Bet was canceled, all ' + __self.config.currency.toLowerCase() + ' returned.'});
  1749. });
  1750. __self.bets_payout = false;
  1751. // Or just cancel the bets
  1752. } else {
  1753. __self.irc.emit('message', {message:__self.pre_text + 'No bet to cancel.'});
  1754. }
  1755. } else {
  1756. __self.bets_status = false;
  1757. __self.bets_payout = false;
  1758. __self.irc.emit('message', {message:__self.pre_text + 'Current bet was canceled.'});
  1759. }
  1760. break;
  1761. }
  1762. };
  1763. Currency.prototype.collect_bets = function (caller, bet, amount) {
  1764. var __self = this, has_bet = false;
  1765. function do_work() {
  1766. var multi_response = [];
  1767. for (var i = 0; i < __self.bets_board.length; i++) {
  1768. multi_response.push([]);
  1769. }
  1770. if (__self.bets_flood.length > 0) {// send flood requests
  1771. var bet;
  1772. // setup bet response
  1773. for (var i = 0; i < __self.bets_flood.length; i++) {
  1774. bet = __self.bets_viewers[__self.bets_flood[i]];
  1775. multi_response[bet.bet].push(bet.viewer + ' (' + bet.amount + ')');
  1776. // check for hiscore and set db appropriately
  1777. if ( parseInt(bet.amount, 10) > parseInt(__self.score_bet_single, 10) ) {
  1778. sql = 'INSERT INTO highscores (`value`, `user`, `name`) VALUES (\'' + amount + '\', \'' + caller + '\', \'bet_single\') ON DUPLICATE KEY UPDATE user=values(user), value=values(value);';
  1779. __self.db.execute(sql, function() {
  1780. __self.score_bet_single = amount;
  1781. __self.irc.emit('message', {message:__self.pre_text + ' ' + caller + ' set new record bet at ' + amount + '!'});
  1782. });
  1783. }
  1784. }
  1785. for (var i = 0; i < __self.bets_board.length; i++) {
  1786. if (multi_response[i].length > 0) {
  1787. __self.irc.emit('message', {message:'New bets for ' + __self.bets_board[i].name + ': ' + multi_response[i].join(', '), timer: 1});
  1788. }
  1789. }
  1790. }
  1791. // clear flood requests
  1792. __self.bets_flood = [];
  1793. }
  1794. // Bound amount by positive currency
  1795. __self.query_coins(caller, function (rows) {
  1796. for (var i = 0; i < rows.length; i++) {
  1797. amount = Math.min(amount, rows[i].points);
  1798. }
  1799. if (__self.bets_viewers.length > 0) {
  1800. for (var i = 0; i < __self.bets_viewers.length; i++) {
  1801. if (__self.bets_viewers[i].viewer === caller) {
  1802. has_bet = true;
  1803. if (amount > __self.bets_viewers[i].amount) {
  1804. __self.bets_board[__self.bets_viewers[i].bet].num -= 1;
  1805. __self.bets_board[__self.bets_viewers[i].bet].total -= __self.bets_viewers[i].amount;
  1806. __self.bets_viewers[i].bet = bet.idx;
  1807. __self.bets_viewers[i].amount = amount;
  1808. __self.bets_board[bet.idx].num += 1;
  1809. __self.bets_board[bet.idx].total += amount;
  1810. // add flood users to array
  1811. if (__self.bets_flood.indexOf(i) < 0) {
  1812. __self.bets_flood.push(i);
  1813. }
  1814. }
  1815. break;
  1816. }
  1817. }
  1818. if (!has_bet && amount >= 1 && amount !== 0) {
  1819. __self.bets_viewers.push({viewer: caller, bet: bet.idx, amount: amount});
  1820. __self.bets_board[bet.idx].num += 1;
  1821. __self.bets_board[bet.idx].total += amount;
  1822. __self.bets_flood.push(__self.bets_viewers.length - 1);
  1823. }
  1824. } else {
  1825. if (amount >= 1 && amount !== 0) {
  1826. __self.bets_viewers.push({viewer: caller, bet: bet.idx, amount: amount});
  1827. __self.bets_board[bet.idx].num += 1;
  1828. __self.bets_board[bet.idx].total += amount;
  1829. __self.bets_flood.push(__self.bets_viewers.length - 1);
  1830. }
  1831. }
  1832. console.log(__self.bets_viewers);
  1833. // check if flood has a set amount of requests and output
  1834. // if not, set the output timer
  1835. if (__self.bets_flood.length === __self.max_requests) {
  1836. do_work();
  1837. } else {
  1838. if (__self.bets_response_reset) {
  1839. __self.bets_response = setTimeout(function () {do_work();}, __self.bets_response_timer);
  1840. } else {
  1841. setTimeout(function () {do_work();}, __self.bets_response_timer);
  1842. }
  1843. }
  1844. });
  1845. };
  1846. Currency.prototype.bets_deduct_bets = function () {
  1847. var __self = this;
  1848. if (__self.bets_viewers.length > 0) {
  1849. // Don't trust the on-the-fly numbers
  1850. for (var i = 0; i < __self.bets_board.length; i++) {
  1851. __self.bets_board[i].num = 0;
  1852. __self.bets_board[i].total = 0;
  1853. }
  1854. __self.bets_total = 0;
  1855. // Remove the points and add them to an escrow
  1856. sql = '';
  1857. for (var i = 0; i < __self.bets_viewers.length; i++) {
  1858. if (__self.bets_viewers[i].amount > 0) {
  1859. if (sql.length > 0) {
  1860. sql += '; ';
  1861. }
  1862. sql += 'UPDATE viewers ';
  1863. sql += 'SET points = points - ' + __self.bets_viewers[i].amount + ' ';
  1864. sql += 'WHERE user = \'' + __self.bets_viewers[i].viewer + '\'';
  1865. __self.bets_board[__self.bets_viewers[i].bet].num += 1;
  1866. __self.bets_board[__self.bets_viewers[i].bet].total += __self.bets_viewers[i].amount;
  1867. __self.bets_total += __self.bets_viewers[i].amount;
  1868. }
  1869. }
  1870. __self.db.execute(sql, function() {});
  1871. }
  1872. };
  1873. Currency.prototype.bets_award_winner = function (winner) {
  1874. var __self = this;
  1875. if (__self.bets_payout) {
  1876. // set payout to complete
  1877. __self.bets_payout = false;
  1878. }
  1879. // Payout the points
  1880. if (__self.bets_viewers.length > 0) {
  1881. sql = '';
  1882. for (var i = 0; i < __self.bets_viewers.length; i++) {
  1883. if (__self.bets_viewers[i].bet == winner.idx) {
  1884. if (sql.length > 0) {
  1885. sql += '; ';
  1886. }
  1887. sql += 'UPDATE viewers ';
  1888. sql += 'SET points = points + ' + Math.ceil(__self.bets_total * __self.bets_viewers[i].amount / __self.bets_board[__self.bets_viewers[i].bet].total) + ' ';
  1889. sql += 'WHERE user = \'' + __self.bets_viewers[i].viewer + '\'';
  1890. }
  1891. }
  1892. __self.db.execute(sql, function() {});
  1893. }
  1894. // Clear the board
  1895. __self.bets_board = [];
  1896. __self.bets_viewers = [];
  1897. __self.bets_total = 0;
  1898. };
  1899. module.exports = function (irc, db, commands, options) {
  1900. return new Currency(irc, db, commands, options);
  1901. };