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.

2199 lines
91 KiB

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