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.

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