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.

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