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.

1546 lines
64 KiB

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