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.

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