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.

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