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.

1749 lines
71 KiB

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