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.

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