Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- registerPlugin({
- name: 'SConomy NG',
- version: '1.7.2',
- description: 'This plugin will give you a currency system',
- author: 'Mmoi <mmoi.addic7ed@gmail.com>',
- vars: [
- /*** General ***/
- {
- name: 'unused0',
- title: 'General'
- },
- {
- name: 'useMinute',
- title: 'Use minutes instead of seconds as interval unit (reduce CPU / disk usage)',
- type: 'checkbox',
- indent: 3
- },
- {
- name: 'tick',
- title: 'Currency generation interval (in seconds)',
- type: 'number',
- placeholder: 1,
- indent: 3
- },
- {
- name: 'currencyAmount',
- title: 'Currency amount generated per interval',
- type: 'number',
- placeholder: 1,
- indent: 3
- },
- {
- name: 'maxCurrency',
- title: 'Maximum generated currency (no other currency will be generated after the user reaches this value)',
- type: 'string',
- placeholder: 9007199254740991,
- indent: 3
- },
- {
- name: 'viewDistance',
- title: 'Number of digits to be shown after the comma',
- type: 'number',
- placeholder: 0,
- indent: 3
- },
- {
- name: 'diskIOLimit',
- title: 'User progress [progress only, not wallet amount] save to disk interval (in seconds, bigger = better | reduce disk load) [0 = disabled, max = Currency generation interval]',
- type: 'number',
- placeholder: 10,
- indent: 3
- },
- {
- name: 'blacklistedChannels',
- title: 'Don\'t generate currency for users within those channels:',
- type: 'array',
- vars: [{
- name: 'channel',
- title: 'Channel',
- type: 'channel'
- }],
- indent: 3
- },
- {
- name: 'storageProvider',
- title: 'Storage provider (default: internal - private)',
- type: 'select',
- options: [
- 'Internal / Private',
- 'Internal / Public'
- ],
- indent: 3
- },
- {
- name: 'allowDumbBuy',
- title: 'Allow user to buy a group even if the user already has the group',
- type: 'checkbox',
- indent: 3
- },
- {
- name: 'enableGiving',
- title: 'Allow user to give other money',
- type: 'checkbox',
- indent: 3
- },
- {
- name: 'donationFee',
- title: 'Donation fees (in percent)',
- type: 'number',
- placeholder: 10,
- indent: 6,
- conditions: [{
- field: 'enableGiving',
- value: true
- }]
- },
- {
- name: 'givingOnlineOnly',
- title: 'Only allow to give to online users (exception to admins)',
- type: 'checkbox',
- indent: 6,
- conditions: [{
- field: 'enableGiving',
- value: true
- }]
- },
- {
- name: 'limitGN',
- title: 'Limit maximum group number per user (does not sell to user who have too many groups)',
- type: 'checkbox',
- indent: 3
- },
- {
- name: 'limitGNOnlySold',
- title: 'Limitation only applied to groups that are in the store',
- type: 'checkbox',
- indent: 6,
- conditions: [{
- field: 'limitGN',
- value: true
- }]
- },
- {
- name: 'limitGNValue',
- title: 'Maximum of allowed groups',
- type: 'number',
- placeholder: 2,
- indent: 6,
- conditions: [{
- field: 'limitGN',
- value: true
- }]
- },
- {
- name: 'historyEnable',
- title: 'Enable the store history (who bought something, when. Display in channel desciption)',
- type: 'checkbox',
- indent: 3
- },
- {
- name: 'historyIncludeSell',
- title: 'Include refunds in the store history',
- type: 'checkbox',
- indent: 6,
- conditions: [{
- field: 'historyEnable',
- value: true
- }]
- },
- {
- name: 'historyChannel',
- title: 'Channel in which the history will be placed (channel description)',
- type: 'channel',
- indent: 6,
- conditions: [{
- field: 'historyEnable',
- value: true
- }]
- },
- {
- name: 'historyLimit',
- title: 'Number of entry in the history (200 should be the maximum)',
- type: 'number',
- placeholder: 10,
- indent: 6,
- conditions: [{
- field: 'historyEnable',
- value: true
- }]
- },
- /*** Commands ***/
- {
- name: 'unused1',
- title: 'Command customization'
- },
- {
- name: 'helpCommand',
- title: 'Help for users',
- type: 'string',
- placeholder: '!schelp',
- indent: 3
- },
- {
- name: 'command',
- title: 'Check wallet',
- type: 'string',
- placeholder: '!money',
- indent: 3
- },
- {
- name: 'storeCommand',
- title: 'Check available servergroup in the store',
- type: 'string',
- placeholder: '!store',
- indent: 3
- },
- {
- name: 'buyCommand',
- title: 'Buy a servergroup from the store',
- type: 'string',
- placeholder: '!buy',
- indent: 3
- },
- {
- name: 'sellCommand',
- title: 'Sell a servergroup',
- type: 'string',
- placeholder: '!sell',
- indent: 3
- },
- {
- name: 'giveCommand',
- title: 'Give user money',
- type: 'string',
- placeholder: '!give',
- indent: 3,
- conditions: [{
- field: 'enableGiving',
- value: true
- }],
- },
- {
- name: 'getUserCommand',
- title: 'See the specified user wallet',
- type: 'string',
- placeholder: '!seemoney',
- indent: 3
- },
- {
- name: 'setUserCommand',
- title: 'Set the specified user wallet',
- type: 'string',
- placeholder: '!setmoney',
- indent: 3
- },
- {
- name: 'addUserCommand',
- title: 'Add amount to the specified user wallet',
- type: 'string',
- placeholder: '!addmoney <user> <amount>',
- indent: 3
- },
- {
- name: 'removeUserCommand',
- title: 'Remove amount from the specified user wallet',
- type: 'string',
- placeholder: '!removemoney <user> <amount>',
- indent: 3
- },
- {
- name: 'setAllUserCommand',
- title: 'Set all user wallet',
- type: 'string',
- placeholder: '!setallmoney <amount>',
- indent: 3
- },
- {
- name: 'setStoreQuantity',
- title: 'Set an item quantity in the store (/!\\ Once an item has been bought, changing the quantity in the settings doesn\'t affect the actual count)',
- type: 'string',
- placeholder: '!setquantity <group ID> <amount>',
- indent: 3
- },
- /*** I18N ***/
- {
- name: 'unused2',
- title: 'Customization'
- },
- {
- name: 'helpOutput',
- title: 'Help for users (put %give for the give command, %f for the fees in percent, for the oder ones please see the placeholder)',
- type: 'multiline',
- placeholder: '[b]SConomy NG by Mmoi.[/b]\nCommands:\n- %money | Shows the current wallet amount\n- %store | Display the store\n- %buy <serverGroup ID> | Buy a serverGroup\n- %sell <serverGroup ID> | Sell a serverGroup',
- indent: 3
- },
- {
- name: 'output',
- title: 'Check wallet output (put %d for the current wallet value)',
- type: 'string',
- placeholder: 'You have %d coin(s)',
- indent: 3
- },
- {
- name: 'storeOutputHeader',
- title: 'Store command output [Header] (put %x for the buy command and \\n for line feed)',
- type: 'string',
- placeholder: 'Groups available in the store:\\n(You can buy them with "%x <ID>")',
- indent: 3
- },
- {
- name: 'storeOutputBody',
- title: 'Store command output [Body] (put %s for the group name, %d for the ID, %x for the price, %c for the remove otions [see below] and %q for the quantity option [see below])',
- type: 'string',
- placeholder: '(ID) %d / %s for %x coin(s) [%c] --- %q',
- indent: 3
- },
- {
- name: 'storeOutputBodySI',
- title: 'Store command output, remove option [Not soldable]',
- type: 'string',
- placeholder: 'No possible refund',
- indent: 3
- },
- {
- name: 'storeOutputBodySP',
- title: 'Store command output, remove option [Refund] (put %d for the sell price)',
- type: 'string',
- placeholder: 'Refund for %d coin(s)',
- indent: 3
- },
- {
- name: 'storeOutputBodySN',
- title: 'Store command output, remove option [Pay to remove] (put %d for the sell price)',
- type: 'string',
- placeholder: 'Remove price: %d coin(s)',
- indent: 3
- },
- {
- name: 'storeOutputBodyIQU',
- title: 'Store command output, quantity option [Unlimited]',
- type: 'string',
- placeholder: 'Unlimited quantity',
- indent: 3
- },
- {
- name: 'storeOutputBodyIQL',
- title: 'Store command output, quantity option [Limited] (put %d for the available quantity and %c for the total qantity)',
- type: 'string',
- placeholder: 'Available: %d of %c',
- indent: 3
- },
- {
- name: 'storeOutputBodyIQLOUT',
- title: 'Store command output, quantity option [Limited, out of order] (put %d for the total qantity)',
- type: 'string',
- placeholder: 'Out of order',
- indent: 3
- },
- {
- name: 'groupNotFoud',
- title: 'Text for group not found by the bot (the group is for sale but the bot can\'t get its name because sinusbot only update the group list on connection)',
- type: 'string',
- placeholder: 'N/A',
- indent: 3
- },
- {
- name: 'tooManyGroups',
- title: 'Text for too many groups',
- type: 'string',
- placeholder: 'You have too many groups',
- indent: 3
- },
- {
- name: 'buyNotInStore',
- title: 'Text for not in store item',
- type: 'string',
- placeholder: 'Item not available in the store',
- indent: 3
- },
- {
- name: 'buyTooExpensive',
- title: 'Text for too expensive item',
- type: 'string',
- placeholder: 'Not enough coins',
- indent: 3
- },
- {
- name: 'buyAlreadyAssigned',
- title: 'Text for already purchased item',
- type: 'string',
- placeholder: 'You already have this item',
- indent: 3
- },
- {
- name: 'buyOutOfStock',
- title: 'Text for item out of stock',
- type: 'string',
- placeholder: 'The item is out of stock',
- indent: 3
- },{
- name: 'buyPerformed',
- title: 'Text for successfully purchased item',
- type: 'string',
- placeholder: 'Item successfully bought',
- indent: 3
- },
- {
- name: 'sellNotSoldable',
- title: 'Text for refund when the group isn\'t refundable / soldable',
- type: 'string',
- placeholder: 'This item can\'t be sold',
- indent: 3
- },
- {
- name: 'sellNotInStore',
- title: 'Text for not in store item at sell time',
- type: 'string',
- placeholder: 'Items that aren\'t in the store can\'t be sold',
- indent: 3
- },
- {
- name: 'sellNotInGroup',
- title: 'Text for refund when the user doesn\'t belong to the group',
- type: 'string',
- placeholder: 'You can\'t sell an item you don\'t have',
- indent: 3
- },
- {
- name: 'sellPerformed',
- title: 'Text for successfully refunded item',
- type: 'string',
- placeholder: 'Item successfully sold',
- indent: 3
- },
- {
- name: 'notEnoughtArgument',
- title: 'Text when a command don\'t have all the requested arguments (put %h for help command)',
- type: 'string',
- placeholder: 'The command isn\'t full, please see help (%h)',
- indent: 3
- },
- {
- name: 'userNotFound',
- title: 'Text when a user is not found',
- type: 'string',
- placeholder: 'User not found',
- indent: 3
- },
- {
- name: 'notValidNumber',
- title: 'Text when a number isn\'t a valid one (put %d for the user input)',
- type: 'string',
- placeholder: '%d is not a valid number',
- indent: 3
- },
- {
- name: 'tooPoorForDonation',
- title: 'Text for requested donation is too expensive',
- type: 'string',
- placeholder: 'You don\'t have the money to donate that amount',
- indent: 3,
- conditions: [{
- field: 'enableGiving',
- value: true
- }]
- },
- {
- name: 'transactionSucceed',
- title: 'Text when someone successfully donated money (put %d for the amount donated)',
- type: 'string',
- placeholder: 'You successfully donated %d coin(s)',
- indent: 3,
- conditions: [{
- field: 'enableGiving',
- value: true
- }]
- },
- {
- name: 'gotDonation',
- title: 'Text when someone successfully donated money to you (put %d for the amount donated and %s for the donator name)',
- type: 'string',
- placeholder: 'You received %d coin(s) from %s',
- indent: 3,
- conditions: [{
- field: 'enableGiving',
- value: true
- }]
- },
- {
- name: 'historyBuyStr',
- title: 'Text for the history when someone buy an item (put %name for buyer username, %group for bought group name and %date for the date)',
- type: 'string',
- placeholder: '%name bought %group (%date)',
- indent: 3,
- conditions: [{
- field: 'historyEnable',
- value: true
- }]
- },
- {
- name: 'historySellStr',
- title: 'Text for the history when someone sell an item (put %name for buyer username, %group for bought group name and %date for the date)',
- type: 'string',
- placeholder: '%name sold %group (%date)',
- indent: 3,
- conditions: [{
- field: 'historyEnable',
- value: true
- }]
- },
- {
- name: 'getUserOutput',
- title: 'Text for admin getting user wallet amount (%d for the amount)',
- type: 'string',
- placeholder: 'User has %d coin(s)',
- indent: 3
- },
- {
- name: 'setUserOutput',
- title: 'Text for admin setting a wallet amount (%d for the amount)',
- type: 'string',
- placeholder: 'Wallet has been set to %d coin(s)',
- indent: 3
- },
- {
- name: 'setStoreOutput',
- title: 'Text for admin setting a store item quantity (%d for the quantity)',
- type: 'string',
- placeholder: 'There is now %d of te item available in store',
- indent: 3
- },
- {
- name: 'showProgress',
- title: 'Add generation progress to the check wallet command output',
- type: 'checkbox',
- indent: 3
- },
- {
- name: 'outputProgress',
- title: 'Check wallet output [Progress] (put %s for the current progress, %c for currency generated by tick)',
- type: 'string',
- placeholder: 'Your current progress for the next %c coin(s) is %s',
- conditions: [{
- field: 'showProgress',
- value: true
- }],
- indent: 3
- },
- /*** Groups ***/
- {
- name: 'unused3',
- title: 'Admin and discount groups'
- },
- {
- name: 'adminGroups',
- title: 'Admin group IDs',
- type: 'strings',
- indent: 3
- },
- {
- name: 'discountGroups',
- title: 'Discount groups (negative number are valid)',
- type: 'array',
- vars: [{
- name: 'groups',
- title: 'Groups IDs',
- type: 'strings'
- },
- {
- name: 'currencyIncrease',
- title: 'Currency increase (in percent)',
- type: 'number'
- },
- {
- name: 'tickDecrease',
- title: 'Update interval decrease (in percent)',
- type: 'number'
- }],
- indent: 3
- },
- {
- name: 'discountChannels',
- title: 'Discount channels (negative number are valid)',
- type: 'array',
- vars: [{
- name: 'channel',
- title: 'Channel',
- type: 'channel'
- },
- {
- name: 'currencyIncrease',
- title: 'Currency increase (in percent)',
- type: 'number'
- },
- {
- name: 'tickDecrease',
- title: 'Update interval decrease (in percent)',
- type: 'number'
- }],
- indent: 3
- },
- {
- name: 'unused4',
- title: 'Sale groups'
- },
- {
- name: 'forSaleGroups',
- title: 'Servergroup that can be sold by the bot',
- type: 'array',
- vars: [{
- name: 'groups',
- title: 'Groups IDs',
- type: 'strings'
- },
- {
- name: 'price',
- title: 'Price',
- type: 'number'
- },
- {
- name: 'soldable',
- title: 'Can be sold',
- type: 'checkbox'
- },
- {
- name: 'soldPrice',
- title: 'Refund price (can be negative if user needs to pay to get it removed)',
- type: 'number',
- conditions: [{
- field: 'soldable',
- value: true
- }]
- },
- {
- name: 'isLimited',
- title: 'Limit the available item quantity',
- type: 'checkbox'
- },
- {
- name: 'limitedNumber',
- title: 'Item quantity',
- type: 'number',
- conditions: [{
- field: 'isLimited',
- value: true
- }]
- }],
- indent: 3
- },
- {
- name: 'unused5',
- title: 'Group number increase groups',
- conditions: [{
- field: 'limitGN',
- value: true
- }]
- },
- {
- name: 'increaseGN',
- title: 'Groups that increase the maximum group number (negative are valid)',
- type: 'array',
- vars: [{
- name: 'groups',
- title: 'Groups IDs',
- type: 'strings'
- },
- {
- name: 'increase',
- title: 'Group number increase',
- type: 'number'
- }],
- indent: 3,
- conditions: [{
- field: 'limitGN',
- value: true
- }]
- },
- ]
- },
- function(sinusbot, config, info)
- {
- // Adds the startsWith method
- if (typeof String.prototype.startsWith === 'undefined')
- {
- String.prototype.startsWith = function(substring)
- {
- return this.substr(0, substring.length) === substring;
- };
- }
- // Includes and global objects
- var engine = require('engine'),
- backend = require('backend'),
- store = require('store'),
- event = require('event'),
- sconomyDB = null;
- var migrationProvider = {confirmation: false},
- antiIOProvider = {progress: [], flush: null};
- /* ============================ Default Settings ============================ */
- config = config === null ? {} : config;
- config.tick = config.tick || 1;
- config.currencyAmount = config.currencyAmount || 1;
- config.maxCurrency = config.maxCurrency || 9007199254740991;
- config.limitGNValue = config.limitGNValue || 2;
- config.historyLimit = config.historyLimit || 10;
- config.helpCommand = config.helpCommand || '!schelp';
- config.command = config.command || '!money';
- config.storeCommand = config.storeCommand || '!store';
- config.getUserCommand = config.getUserCommand || '!see';
- config.setUserCommand = config.setUserCommand || '!set';
- config.buyCommand = config.buyCommand || '!buy';
- config.sellCommand = config.sellCommand || '!sell';
- config.giveCommand = config.giveCommand || '!give';
- config.addUserCommand = config.addUserCommand || '!addmoney';
- config.removeUserCommand = config.removeUserCommand || '!removemoney';
- config.setAllUserCommand = config.setAllUserCommand || '!setallmoney';
- config.setStoreQuantity = config.setStoreQuantity || '!setquantity';
- config.output = config.output || 'You have %d coin(s)';
- config.outputProgress = config.outputProgress || 'Your current progress for the next %c coin(s) is %s';
- config.getUserOutput = config.getUserOutput || 'User has %d coin(s)';
- config.setUserOutput = config.setUserOutput || 'Wallet has been set to %d coin(s)';
- config.setStoreOutput = config.setStoreOutput || 'There is now %d of te item available in store';
- config.blacklistedChannels = config.blacklistedChannels || [];
- config.adminGroups = config.adminGroups || [];
- config.discountGroups = config.discountGroups || [];
- config.discountChannels = config.discountChannels || [];
- config.forSaleGroups = config.forSaleGroups || [];
- config.increaseGN = config.increaseGN || [];
- config.storeOutputHeader = config.storeOutputHeader || 'Groups available in the store:\\n(You can buy them with "%x <ID>")';
- config.storeOutputBody = config.storeOutputBody || '(ID) %d / %s for %x coin(s) [%c] --- %q';
- config.storeOutputBodySI = config.storeOutputBodySI || 'No possible refund';
- config.storeOutputBodySP = config.storeOutputBodySP || 'Refund for %d coin(s)';
- config.storeOutputBodySN = config.storeOutputBodySN || 'Remove price: %d coin(s)';
- config.storeOutputBodyIQU = config.storeOutputBodyIQU || 'Unlimited quantity';
- config.storeOutputBodyIQL = config.storeOutputBodyIQL || 'Available: %d of %c';
- config.storeOutputBodyIQLOUT= config.storeOutputBodyIQLOUT|| 'Out of order';
- config.groupNotFoud = config.groupNotFoud || 'N/A';
- config.tooManyGroups = config.tooManyGroups || 'You have too many groups';
- config.buyNotInStore = config.buyNotInStore || 'Item not available in the store';
- config.buyTooExpensive = config.buyTooExpensive || 'Not enough coins';
- config.buyOutOfStock = config.buyOutOfStock || 'The item is out of stock';
- config.buyAlreadyAssigned = config.buyAlreadyAssigned || 'You already have this item';
- config.buyPerformed = config.buyPerformed || 'Item successfully bought';
- config.sellNotInStore = config.sellNotInStore || 'Items that aren\'t in the store can\'t be sold';
- config.sellNotSoldable = config.sellNotSoldable || 'This item can\'t be sold';
- config.sellNotInGroup = config.sellNotInGroup || 'You can\'t sell an item you don\'t have';
- config.sellPerformed = config.sellPerformed || 'Item successfully sold';
- config.userNotFound = config.userNotFound || 'User not found';
- config.helpOutput = config.helpOutput || '[b]SConomy NG by Mmoi.[/b]\nCommands:\n- %money | Shows the current wallet amount\n- %store | Display the store\n- %buy <serverGroup ID> | Buy a serverGroup\n- %sell <serverGroup ID> | Sell a serverGroup';
- config.notEnoughtArgument = config.notEnoughtArgument || 'The command isn\'t full, please see help (%h)';
- config.tooPoorForDonation = config.tooPoorForDonation || 'You don\'t have the money to donate that amount';
- config.notValidNumber = config.notValidNumber || '%d is not a valid number';
- config.transactionSucceed = config.transactionSucceed || 'You successfully donated %d coin(s)';
- config.gotDonation = config.gotDonation || 'You received %d coin(s) from %s';
- config.historyBuyStr = config.historyBuyStr || '%name bought %group (%date)';
- config.historySellStr = config.historySellStr || '%name sold %group (%date)';
- config.viewDistance = typeof config.viewDistance === 'undefined' ? 0 : config.viewDistance;
- config.diskIOLimit = typeof config.diskIOLimit === 'undefined' ? 10 : config.diskIOLimit;
- config.donationFee = typeof config.donationFee === 'undefined' ? 10 : config.donationFee;
- config.storageProvider = typeof config.storageProvider === 'undefined' ? '0' : config.storageProvider;
- config.useMinute = typeof config.useMinute === 'undefined' ? false : config.useMinute;
- config.allowDumbBuy = typeof config.allowDumbBuy === 'undefined' ? false : config.allowDumbBuy;
- config.enableGiving = typeof config.enableGiving === 'undefined' ? false : config.enableGiving;
- config.givingOnlineOnly = typeof config.givingOnlineOnly === 'undefined' ? true : config.givingOnlineOnly;
- config.limitGN = typeof config.limitGN === 'undefined' ? false : config.limitGN;
- config.limitGNOnlySold = typeof config.limitGNOnlySold === 'undefined' ? false : config.limitGNOnlySold;
- config.historyEnable = typeof config.historyEnable === 'undefined' ? false : config.historyEnable;
- config.historyIncludeSell = typeof config.historyIncludeSell === 'undefined' ? false : config.historyIncludeSell;
- config.showProgress = typeof config.showProgress === 'undefined' ? false : config.showProgress;
- /* ======================= Storage provider functions ======================= */
- /**
- * @fn sconomySet Set a key in the storage
- * @param params Object with following members:
- * - userUID: user UID
- * - type: storage field type
- * - value: value to be stored
- */
- function sconomySet(params)
- {
- if (sconomyDB !== null)
- {
- sconomyDB.setData(params.userUID, params.type, params.value);
- }
- else
- {
- // Default
- if (config.storageProvider === '0')
- {
- store.set(params.userUID + params.type, params.value);
- }
- // Public
- else
- {
- store.setGlobal(params.userUID + params.type, params.value);
- }
- }
- }
- /**
- * @fn sconomySetAll Set all key in the storage
- * @param params Object with following members:
- * - type: storage field type
- * - value: value to be stored
- */
- function sconomySetAll(params)
- {
- if (sconomyDB !== null)
- {
- sconomyDB.setAllData(params.type, params.value);
- }
- else
- {
- // Default
- if (config.storageProvider === '0')
- {
- store.getKeys().forEach(function(storedKey)
- {
- // Search sconomy currency keys
- if (storedKey.match(new RegExpr('.*' + params.type + '$')))
- {
- store.set(storedKey, params.value);
- }
- });
- }
- // Public
- else
- {
- store.getKeysGlobal().forEach(function(storedKey)
- {
- // Search sconomy currency keys
- if (storedKey.match(new RegExp('.*' + params.type + '$')))
- {
- store.setGlobal(storedKey, params.value);
- }
- });
- }
- }
- }
- /**
- * @fn sconomyGet Get a key from the storage
- * @param params Object with following members:
- * - userUID: user UID
- * - type: storage field type
- * @return requested value or undefined
- */
- function sconomyGet(params)
- {
- if (sconomyDB !== null)
- {
- return sconomyDB.getData(params.userUID, params.type);
- }
- else
- {
- // Default
- if (config.storageProvider === '0')
- {
- return store.get(params.userUID + params.type);
- }
- // Public
- else
- {
- return store.getGlobal(params.userUID + params.type);
- }
- }
- }
- // Fonctions that flushes the user in-RAM progress (and store it on disk)
- antiIOProvider.flush = function(uid, removeKey)
- {
- if (antiIOProvider.progress[uid])
- {
- // Get the user total progress (disk + RAM)
- var progress = sconomyGet({userUID: uid, type: 'progress'});
- progress = progress ? progress : 1;
- progress += antiIOProvider.progress[uid];
- // Store it on dsk
- sconomySet({
- userUID: uid,
- type: 'progress',
- value: parseFloat(progress)
- });
- // Resets the RAM-progress
- antiIOProvider.progress[uid] = 0;
- if (removeKey)
- {
- delete antiIOProvider.progress[uid];
- }
- }
- };
- // Migration functions
- migrationProvider.private_public = function(storage, startingIndex)
- {
- var i = typeof startingIndex === 'undefined' ? 0 : startingIndex,
- date = (new Date()).getTime() + 4000,
- list = storage.getKeys(),
- len = list.length,
- storedKey;
- for (; i < len && (new Date()).getTime() < date; i++)
- {
- storedKey = list[i];
- // Copy the keys
- storage.setGlobal(storedKey, storage.get(storedKey));
- }
- // Migration not finished yet
- if (i !== len)
- {
- setTimeout(function()
- {
- migrationProvider.public_private(storage, i);
- }, 10);
- engine.log('Migration tool: still working...');
- }
- else
- {
- engine.log('Migration tool: work done.');
- }
- return true;
- };
- migrationProvider.public_private = function(storage, startingIndex)
- {
- var i = typeof startingIndex === 'undefined' ? 0 : startingIndex,
- date = (new Date()).getTime() + 4000,
- list = storage.getKeysGlobal(),
- len = list.length,
- storedKey;
- for (; i < len && (new Date()).getTime() < date; i++)
- {
- storedKey = list[i];
- // Search sconomy keys
- if (storedKey.match(new RegExp('^(.{27}=(sconomy|progress)|SCO_GRP_\\d+quantity)$')))
- {
- storage.set(storedKey, storage.getGlobal(storedKey));
- }
- }
- // Migration not finished yet
- if (i !== len)
- {
- setTimeout(function()
- {
- migrationProvider.public_private(storage, i);
- }, 10);
- engine.log('Migration tool: still working...');
- }
- else
- {
- engine.log('Migration tool: work done.');
- }
- return true;
- };
- migrationProvider.unset_private = function(storage)
- {
- storage.getKeys().forEach(function(storedKey)
- {
- storage.unset(storedKey);
- });
- return true;
- };
- migrationProvider.unset_public = function(storage)
- {
- storage.getKeysGlobal().forEach(function(storedKey)
- {
- // Search sconomy keys
- if (storedKey.match(new RegExp('^(.{27}=(sconomy|progress)|SCO_GRP_\\d+quantity)$')))
- {
- storage.unsetGlobal(storedKey);
- }
- });
- return true;
- };
- /*
- * @fn sconomyDBIntegration Adds the database support for sconomy-ng
- */
- function sconomyDBIntegration()
- {
- sconomyDB = require('sconomy-ng-db.js');
- if (!sconomyDB || !sconomyDB.isEnabled())
- {
- // Disable the support
- engine.log('SConomy NG DB Plugin not found, database support is disabled');
- sconomyDB = null;
- }
- else
- {
- engine.log('SConomy NG DB loaded');
- // Connects to the database
- sconomyDB.start();
- // Adds the migrations methods
- sconomyDB.getMigrationFunctions().forEach(function(migrationFunction)
- {
- migrationProvider[migrationFunction.name] = migrationFunction.func;
- });
- }
- }
- /* ============================= Main function ============================= */
- /**
- * @fn computeTick Increase each connected client progress
- * and the wallet value if the tick is reached
- */
- function computeTick()
- {
- // Re-schedule the next tick
- if (sconomyDB !== null) setTimeout(computeTick, sconomyDB.getTick() * 1000);
- else if (config.useMinute) setTimeout(computeTick, 60 * 1000);
- else setTimeout(computeTick, 1000);
- backend.getChannels().forEach(function(channel)
- {
- // Ignore blacklisted channels
- var blacklisted = config.blacklistedChannels.some(function(blacklistChannel)
- {
- return channel.id() === blacklistChannel.channel;
- });
- if (blacklisted) return;
- // Load the base discount for the channel
- var channelDiscount = getChannelDiscount(channel, config.discountChannels);
- // Process the clients
- channel.getClients().forEach(function(client)
- {
- // Compute the increase and decrease factors for the groups
- var discount = getDiscount(client, config.discountGroups);
- // Adds the channel discount to the user one
- discount.currencyIncreaseSum += channelDiscount.currencyIncreaseSum;
- discount.tickDecreaseSum += channelDiscount.tickDecreaseSum;
- if (discount.tickDecreaseSum > 90) discount.tickDecreaseSum = 90;
- // For each connected client
- var uid = client.uid(),
- progress = sconomyGet({userUID: uid, type: 'progress'}),
- sconomy = sconomyGet({userUID: uid, type: 'sconomy'});
- // Maximum currency not reached yet
- if (sconomy < config.maxCurrency || sconomy === undefined)
- {
- // If IO reducer is enabled
- if (config.diskIOLimit > 0)
- {
- // Create the user RAM-progress
- if (antiIOProvider.progress[uid] === undefined)
- {
- antiIOProvider.progress[uid] = 0;
- }
- // Adds the RAM-stored progress to the disk-stored one
- progress += antiIOProvider.progress[uid];
- }
- // No money for that user
- if (sconomy === undefined)
- {
- sconomy = 0;
- progress = 1;
- if (config.diskIOLimit > 0) antiIOProvider.progress[uid] = 0;
- }
- // User has reached the end of a tick
- else if (progress >= config.tick * (1 - discount.tickDecreaseSum / 100))
- {
- sconomy += config.currencyAmount * ((100 + discount.currencyIncreaseSum) / 100);
- progress = 1;
- if (config.diskIOLimit > 0) antiIOProvider.progress[uid] = 0;
- }
- // User is in a tick
- else
- {
- // Progress is only incremented for the possible storage
- progress++;
- // Adds user progress for the next check
- if (config.diskIOLimit > 0) antiIOProvider.progress[uid]++;
- }
- // Save the updated currency amount (only on modification)
- if (progress === 1)
- {
- // Maximum currency reached
- if (sconomy > config.maxCurrency) sconomy = config.maxCurrency;
- sconomySet({
- userUID: uid,
- type: 'sconomy',
- value: parseFloat(sconomy)
- });
- }
- // Save, when needed, the new user progress
- if (config.diskIOLimit <= 0 || progress === 1 || antiIOProvider.progress[uid] >= config.diskIOLimit)
- {
- if (config.diskIOLimit > 0) antiIOProvider.progress[uid] = 0;
- sconomySet({
- userUID: uid,
- type: 'progress',
- value: parseFloat(progress)
- });
- }
- }
- });
- });
- }
- /* =========================== Utility functions =========================== */
- /**
- * @fn getDiscount Get Discount for the user
- * @param client Client
- * @param discountGroups Parameters discountGroups
- * @return Object with currencyIncreaseSum, tickDecreaseSum members
- */
- function getDiscount(client, discountGroups)
- {
- var currencyIncreaseSum = 0,
- tickDecreaseSum = 0;
- client.getServerGroups().forEach(function(userServergroup)
- {
- discountGroups.forEach(function(discountGroup)
- {
- discountGroup.groups.forEach(function(group)
- {
- // User has the discount
- if (group === userServergroup.id())
- {
- currencyIncreaseSum += discountGroup.currencyIncrease;
- tickDecreaseSum += discountGroup.tickDecrease;
- }
- });
- });
- });
- // Set bondaries
- tickDecreaseSum = tickDecreaseSum >= 90 ? 90 : tickDecreaseSum;
- return {
- currencyIncreaseSum: currencyIncreaseSum,
- tickDecreaseSum: tickDecreaseSum
- };
- }
- /**
- * @fn getChannelDiscount Get Discount for a specific channel
- * @param channel Channel
- * @param discountChannels Parameters discountChannels
- * @return Object with currencyIncreaseSum, tickDecreaseSum members
- */
- function getChannelDiscount(channel, discountChannels)
- {
- var currencyIncreaseSum = 0,
- tickDecreaseSum = 0;
- discountChannels.forEach(function(discountChannel)
- {
- if (discountChannel.channel === channel.id())
- {
- currencyIncreaseSum += discountChannel.currencyIncrease;
- tickDecreaseSum += discountChannel.tickDecrease;
- }
- });
- // Set bondaries
- tickDecreaseSum = tickDecreaseSum >= 90 ? 90 : tickDecreaseSum;
- return {
- currencyIncreaseSum: currencyIncreaseSum,
- tickDecreaseSum: tickDecreaseSum
- };
- }
- /**
- * @fn getUserUID Get user UID based on multiple possible inputs
- * @param input string of the client identifier (UID, name etc)
- * @param allowOffline boolean to validate offline user too
- * @return UID or null if not found
- */
- function getUserUID(input, allowOffline)
- {
- var regexRes = null,
- client = null;
- /*
- * CLient URL
- * ^\[URL=client://\d+/.{27}=~[^\]]*\](\\\[|[^\[])*\[/URL\]$
- * ^\[URL=client:\/\/\d+\/(.{27}=)~[^\]]*\](\\\[|[^\[])*\[\/URL\]$ (escaped)
- */
- regexRes = input.match(/^\[URL=client:\/\/\d+\/(.{27}=)~[^\]]*\](\\\[|[^\[])*\[\/URL\]$/);
- if (regexRes)
- {
- if (allowOffline || backend.getClientByUniqueID(regexRes[1]))
- {
- return regexRes[1];
- }
- else
- {
- return null;
- }
- }
- /*
- * CLient UID
- * ^.{27}=$
- * ^(.{27}=)$
- */
- regexRes = input.match(/^(.{27}=)$/);
- if (regexRes)
- {
- if (allowOffline || backend.getClientByUniqueID(regexRes[1]))
- {
- return regexRes[1];
- }
- else
- {
- return null;
- }
- }
- /*
- * Client Nickname
- */
- client = backend.getClientByName(input);
- if (client)
- {
- return client.uid();
- }
- return null;
- }
- /**
- * @fn isAdmin Checks if the user is an Admin
- * @param client client
- * @return Boolean
- */
- function isAdmin(client)
- {
- return config.adminGroups.some(function(adminGroup)
- {
- return client.getServerGroups().some(function(userServergroup)
- {
- return adminGroup === userServergroup.id();
- });
- });
- }
- /**
- * @fn clientGroupNumber Return the number of groups the client is in
- * @param client client
- * @return Number of groups
- * @warning May be number of sold groups only based on config.limitGNOnlySold
- */
- function clientGroupNumber(client)
- {
- var clientGroups = client.getServerGroups();
- // Group number limitation (heavy but process only on buy)
- if (config.limitGNOnlySold)
- {
- var clientGroupNumberValue = 0;
- // Check for each sales plan if the groups are possessed by the user
- config.forSaleGroups.forEach(function(saleGroup)
- {
- saleGroup.groups.forEach(function(group)
- {
- clientGroups.forEach(function(userServergroup)
- {
- if (userServergroup.id() === group)
- {
- clientGroupNumberValue++;
- }
- });
- });
- });
- return clientGroupNumberValue;
- }
- else
- {
- return clientGroups.length;
- }
- }
- /**
- * @fn clientAllowedGroupNumber Return the number of groups the client allowed to have
- * @param client client
- * @return Number of groups
- */
- function clientAllowedGroupNumber(client)
- {
- var clientGroups = client.getServerGroups(),
- maxAllowed = config.limitGNValue;
- // Group number limitation (heavy but process only on buy)
- // Check for each sales plan if the groups are possessed by the user
- config.increaseGN.forEach(function(incGNGroup)
- {
- incGNGroup.groups.forEach(function(group)
- {
- clientGroups.forEach(function(userServergroup)
- {
- if (userServergroup.id() === group)
- {
- maxAllowed += incGNGroup.increase;
- }
- });
- });
- });
- return maxAllowed;
- }
- /**
- * @fn userFound Return the client UID or flase and message the client about not found UID
- * @param userUID UID returned by getUserUID() function
- * @param client client
- * @return false or UID
- */
- function userFound(userUID, client)
- {
- if (userUID === null)
- {
- client.chat(config.userNotFound);
- }
- return userUID !== null;
- }
- /**
- * @fn addToHistory Adds to store history the provided entry
- * @param params Object with members:
- * name: name of the client who performed the action
- * groupID: servergroup ID
- * action: action (buy or sell)
- */
- function addToHistory(params)
- {
- // Handle the channel
- var channel = backend.getChannelByID(config.historyChannel);
- if (!channel)
- {
- engine.log('SConomy: history channel not found');
- return;
- }
- // Handle the provided serverGroup
- var serverGrp = backend.getServerGroupByID(params.groupID);
- if (!serverGrp)
- {
- serverGrp = {name: function(){return config.groupNotFoud;}};
- }
- // Handle the output
- var baseOutput = '';
- switch (params.action)
- {
- case 'buy':
- baseOutput = config.historyBuyStr;
- break;
- case 'sell':
- baseOutput = config.historySellStr;
- break;
- default:
- // Should never be called...
- engine.log('SConomy: unknown action in addToHistory()');
- break;
- }
- // Adds to the description
- var oldDesc = channel.description(),
- descArray = oldDesc.split('\n');
- if (descArray.length >= config.historyLimit)
- {
- // Remove oldest
- descArray.splice(0, 1);
- }
- descArray.push(baseOutput.replace(/%group/g, serverGrp.name())
- .replace(/%name/g, params.name)
- .replace(/%date/g, (new Date()).toLocaleString())
- );
- channel.setDescription(descArray.join('\n'));
- }
- /* ============================= Chat functions ============================= */
- /**
- * @fn getHelp Send to client the help message
- * @param client client to send the info
- */
- function getHelp(client)
- {
- client.chat(
- config.helpOutput.replace(
- /%money/g,
- config.command
- ).replace(
- /%store/g,
- config.storeCommand
- ).replace(
- /%buy/g,
- config.buyCommand
- ).replace(
- /%sell/g,
- config.sellCommand
- ).replace(
- /%give/g,
- config.giveCommand
- ).replace(
- /%f/g,
- config.donationFee
- )
- );
- }
- /**
- * @fn getCurrency Send to client its current wallet amount
- * @param client client to send the info
- */
- function getCurrency(client)
- {
- var sconomy = sconomyGet({userUID: client.uid(), type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- client.chat(config.output.replace(/%d/g, sconomy.toFixed(config.viewDistance)));
- if (config.showProgress)
- {
- // Compute the increase and decrease factors for the groups
- var discount = getDiscount(client, config.discountGroups),
- chanDiscount = getChannelDiscount(client.getChannels()[0], config.discountChannels),
- progress = sconomyGet({userUID: client.uid(), type: 'progress'});
- progress = progress ? progress : 1;
- // Adds the channel discount to the user one
- discount.currencyIncreaseSum += chanDiscount.currencyIncreaseSum;
- discount.tickDecreaseSum += chanDiscount.tickDecreaseSum;
- if (discount.tickDecreaseSum > 90) discount.tickDecreaseSum = 90;
- client.chat(
- config.outputProgress.replace(
- /%s/g,
- progress + '/' + (config.tick * (1 - discount.tickDecreaseSum / 100)).toFixed(0)
- ).replace(
- /%c/g,
- (config.currencyAmount * ((100 + discount.currencyIncreaseSum) / 100)).toFixed(config.viewDistance)
- )
- );
- }
- }
- /**
- * @fn getStore Send to client the available purchase items (servergroups)
- * @param client client to send the info
- */
- function getStore(client)
- {
- // Header
- config.storeOutputHeader.split('\\n').forEach(function(line)
- {
- client.chat(line.replace(/%x/g, config.buyCommand));
- });
- // Body
- config.forSaleGroups.forEach(function(saleGroup)
- {
- saleGroup.groups.forEach(function(group)
- {
- var backendGroup = backend.getServerGroupByID(group),
- soldTypeString,
- quantityString;
- // Handle soldability strings
- if (saleGroup.soldable)
- {
- if (saleGroup.soldPrice >= 0)
- {
- soldTypeString = config.storeOutputBodySP.replace(/%d/g, saleGroup.soldPrice.toFixed(config.viewDistance));
- }
- else
- {
- soldTypeString = config.storeOutputBodySN.replace(/%d/g, (-saleGroup.soldPrice).toFixed(config.viewDistance));
- }
- }
- else
- {
- soldTypeString = config.storeOutputBodySI;
- }
- // Handle quantity string
- if (saleGroup.isLimited)
- {
- var quantity = sconomyGet({userUID: 'SCO_GRP_' + group, type: 'quantity'});
- if (typeof quantity === 'undefined') quantity = saleGroup.limitedNumber;
- if (quantity === 0)
- {
- quantityString = config.storeOutputBodyIQLOUT.replace(/%d/g, saleGroup.limitedNumber);
- }
- else
- {
- quantityString = config.storeOutputBodyIQL.replace(/%d/g, quantity)
- .replace(/%c/g, saleGroup.limitedNumber);
- }
- }
- else
- {
- quantityString = config.storeOutputBodyIQU;
- }
- // Adds the final item string to the output
- client.chat(config.storeOutputBody.replace(/%s/g, backendGroup ? backendGroup.name() : config.groupNotFoud)
- .replace(/%d/g, group)
- .replace(/%x/g, saleGroup.price.toFixed(config.viewDistance))
- .replace(/%c/g, soldTypeString)
- .replace(/%q/g, quantityString)
- );
- });
- });
- }
- /**
- * @fn buyServergroup Try to performe a sale based on the buyer message
- * @param message The full message sent by the buyer
- */
- function buyServergroup(message)
- {
- var requestedGroup = message.text.substr(config.buyCommand.length + 1).trim(),
- groupFound = false,
- alreadyAssigned = false;
- // Group number limitation
- if (config.limitGN && clientGroupNumber(message.client) >= clientAllowedGroupNumber(message.client))
- {
- message.client.chat(config.tooManyGroups);
- }
- else
- {
- // Proces all the groups of sales plans
- config.forSaleGroups.forEach(function(saleGroup)
- {
- // Search the requested group
- saleGroup.groups.forEach(function(group)
- {
- if (group === requestedGroup)
- {
- groupFound = true;
- var quantity = 0;
- if (saleGroup.isLimited)
- {
- // Check the availibility of the requested group
- quantity = sconomyGet({userUID: 'SCO_GRP_' + group, type: 'quantity'});
- if (typeof quantity === 'undefined') quantity = saleGroup.limitedNumber;
- }
- if (!saleGroup.isLimited || quantity > 0)
- {
- // Check if the user can buy
- var sconomy = sconomyGet({userUID: message.client.uid(), type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- if (sconomy >= saleGroup.price)
- {
- // Check if already assigned
- if (!config.allowDumbBuy)
- {
- alreadyAssigned = message.client.getServerGroups().some(function(userServergroup)
- {
- return group === userServergroup.id();
- });
- }
- // If user don't have the group or allowDumbBuy is on
- if (alreadyAssigned === false)
- {
- if (saleGroup.isLimited)
- {
- // Reduce the available quantity
- sconomySet({
- userUID: 'SCO_GRP_' + group,
- type: 'quantity',
- value: parseFloat(quantity - 1)
- });
- }
- // Take the price requested for the group
- sconomy -= saleGroup.price;
- sconomySet({
- userUID: message.client.uid(),
- type: 'sconomy',
- value: parseFloat(sconomy)
- });
- message.client.addToServerGroup(group);
- message.client.chat(config.buyPerformed);
- if (config.historyEnable)
- {
- addToHistory({
- name: message.client.name(),
- groupID: group,
- action: 'buy'
- });
- }
- }
- else
- {
- message.client.chat(config.buyAlreadyAssigned);
- }
- }
- else
- {
- message.client.chat(config.buyTooExpensive);
- }
- }
- else
- {
- message.client.chat(config.buyOutOfStock);
- }
- }
- });
- });
- // Group not found
- if (!groupFound)
- {
- message.client.chat(config.buyNotInStore);
- }
- }
- }
- /**
- * @fn sellServergroup Try to performe a refund based on the buyer message
- * @param message The full message sent by the buyer
- */
- function sellServergroup(message)
- {
- var requestedGroup = message.text.substr(config.sellCommand.length + 1).trim(),
- groupFound = false,
- userIsInGroup = false;
- config.forSaleGroups.forEach(function(saleGroup)
- {
- // Search the requested group
- saleGroup.groups.forEach(function(group)
- {
- if (group === requestedGroup)
- {
- groupFound = true;
- // Check the soldability
- if (saleGroup.soldable)
- {
- // Check if the user has the group
- userIsInGroup = message.client.getServerGroups().some(function(userServergroup)
- {
- return group === userServergroup.id();
- });
- // If user has the group
- if (userIsInGroup)
- {
- var sconomy = sconomyGet({userUID: message.client.uid(), type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- // Check if user needs to pay to get the group removed
- if (saleGroup.soldPrice < 0 && sconomy < (-saleGroup.soldPrice))
- {
- message.client.chat(config.buyTooExpensive);
- }
- else
- {
- if (saleGroup.isLimited)
- {
- // Get back the item in the circuit
- quantity = sconomyGet({userUID: 'SCO_GRP_' + group, type: 'quantity'});
- if (typeof quantity === 'undefined') quantity = saleGroup.limitedNumber;
- quantity++;
- if (quantity > saleGroup.limitedNumber) quantity = saleGroup.limitedNumber;
- sconomySet({
- userUID: 'SCO_GRP_' + group,
- type: 'quantity',
- value: parseFloat(quantity)
- });
- }
- // Refund the wallet
- sconomy += saleGroup.soldPrice;
- sconomySet({
- userUID: message.client.uid(),
- type: 'sconomy',
- value: parseFloat(sconomy)
- });
- message.client.removeFromServerGroup(group, group);
- message.client.chat(config.sellPerformed);
- if (config.historyEnable && config.historyIncludeSell)
- {
- addToHistory({
- name: message.client.name(),
- groupID: group,
- action: 'sell'
- });
- }
- }
- }
- else
- {
- message.client.chat(config.sellNotInGroup);
- }
- }
- else
- {
- message.client.chat(config.sellNotSoldable);
- }
- }
- });
- });
- // Message the result to the client
- if (!groupFound)
- {
- message.client.chat(config.sellNotInStore);
- }
- }
- /**
- * @fn giveCurrency Try to give money based on the client full message
- * @param message The full message sent by the client
- */
- function giveCurrency(message)
- {
- var fullArgument = message.text.substr(config.giveCommand.length + 1).trim(),
- argSplit = fullArgument.split(' ');
- if (argSplit.length >= 2)
- {
- // Compute arguments
- var requestedCurrency = argSplit.splice(argSplit.length - 1, 1)[0],
- currency = parseFloat(requestedCurrency),
- userUID = getUserUID(argSplit.join(' ').trim(), !config.givingOnlineOnly);
- if (userFound(userUID, message.client))
- {
- if (currency && currency > 0)
- {
- var sconomy = sconomyGet({userUID: message.client.uid(), type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- if (sconomy >= currency)
- {
- // Taking apart the currency
- sconomy -= currency;
- sconomySet({
- userUID: message.client.uid(),
- type: 'sconomy',
- value: parseFloat(sconomy)
- });
- // Get the amount after the fees calculations
- var newSconomy = currency * ((100 - config.donationFee) / 100);
- // Giving the currency to the receiver
- var receiver = sconomyGet({userUID: userUID, type: 'sconomy'});
- receiver = receiver ? receiver + newSconomy : newSconomy;
- sconomySet({
- userUID: userUID,
- type: 'sconomy',
- value: parseFloat(receiver)
- });
- // Notify the donator
- message.client.chat(config.transactionSucceed.replace(/%d/g, currency.toFixed(config.viewDistance)));
- // Notify the receiver
- var receiverClient = backend.getClientByUniqueID(userUID);
- if (receiverClient)
- {
- receiverClient.chat(
- config.gotDonation.replace(/%d/g, newSconomy.toFixed(config.viewDistance))
- .replace(/%s/g, message.client.name())
- );
- }
- }
- else
- {
- message.client.chat(config.tooPoorForDonation);
- }
- }
- else
- {
- message.client.chat(config.notValidNumber.replace(/%d/g, requestedCurrency));
- }
- }
- }
- }
- /**
- * @fn getUserCurrency Try to get a user wallet amount based on the full admin request message
- * @param message The full message sent by the admin
- */
- function getUserCurrency(message)
- {
- var userUID = getUserUID(message.text.substr(config.getUserCommand.length + 1).trim(), true);
- if (userFound(userUID, message.client))
- {
- var sconomy = sconomyGet({userUID: userUID, type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- message.client.chat(config.getUserOutput.replace(/%d/g, sconomy.toFixed(config.viewDistance)));
- }
- }
- /**
- * @fn setUserCurrency Try to set a user wallet amount based on the full admin request message
- * @param message The full message sent by the admin
- */
- function setUserCurrency(message)
- {
- var fullArgument = message.text.substr(config.setUserCommand.length + 1).trim(),
- argSplit = fullArgument.split(' ');
- if (argSplit.length >= 2)
- {
- // Compute arguments
- var currency = parseFloat(argSplit.splice(argSplit.length - 1, 1)[0]),
- userUID = getUserUID(argSplit.join(' ').trim(), true);
- if (userFound(userUID, message.client) && !isNaN(currency))
- {
- sconomySet({
- userUID: userUID,
- type: 'sconomy',
- value: parseFloat(currency)
- });
- var sconomy = sconomyGet({userUID: userUID, type: 'sconomy'});
- message.client.chat(config.setUserOutput.replace(/%d/g, sconomy.toFixed(config.viewDistance)));
- }
- }
- else
- {
- message.client.chat(config.notEnoughtArgument.replace(/%h/g, config.helpCommand));
- }
- }
- /**
- * @fn addUserCurrency Try to add currency to a user wallet based on the full admin request message
- * @param message The full message sent by the admin
- */
- function addUserCurrency(message)
- {
- var fullArgument = message.text.substr(config.addUserCommand.length + 1).trim(),
- argSplit = fullArgument.split(' ');
- if (argSplit.length >= 2)
- {
- // Compute arguments
- var currency = parseFloat(argSplit.splice(argSplit.length - 1, 1)[0]);
- userUID = getUserUID(argSplit.join(' ').trim(), true);
- if (userFound(userUID, message.client) && !isNaN(currency))
- {
- var sconomy = sconomyGet({userUID: userUID, type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- sconomySet({
- userUID: userUID,
- type: 'sconomy',
- value: parseFloat(sconomy + currency)
- });
- sconomy = sconomyGet({userUID: userUID, type: 'sconomy'});
- message.client.chat(config.setUserOutput.replace(/%d/g, sconomy.toFixed(config.viewDistance)));
- }
- }
- else
- {
- message.client.chat(config.notEnoughtArgument.replace(/%h/g, config.helpCommand));
- }
- }
- /**
- * @fn removeUserCurrency Try to remove currency to a user wallet based on the full admin request message
- * @param message The full message sent by the admin
- */
- function removeUserCurrency(message)
- {
- var fullArgument = message.text.substr(config.removeUserCommand.length + 1).trim(),
- argSplit = fullArgument.split(' ');
- if (argSplit.length >= 2)
- {
- // Compute arguments
- var currency = parseFloat(argSplit.splice(argSplit.length - 1, 1)[0]),
- userUID = getUserUID(argSplit.join(' ').trim(), true);
- if (userFound(userUID, message.client) && !isNaN(currency))
- {
- var sconomy = sconomyGet({userUID: userUID, type: 'sconomy'});
- sconomy = sconomy ? sconomy : 0;
- sconomySet({
- userUID: userUID,
- type: 'sconomy',
- value: parseFloat(sconomy - currency)
- });
- sconomy = sconomyGet({userUID: userUID, type: 'sconomy'});
- message.client.chat(config.setUserOutput.replace(/%d/g, sconomy.toFixed(config.viewDistance)));
- }
- }
- else
- {
- message.client.chat(config.notEnoughtArgument.replace(/%h/g, config.helpCommand));
- }
- }
- /**
- * @fn setAllUserCurrency Set all user wallet amount based on the full admin request message
- * @param message The full message sent by the admin
- */
- function setAllUserCurrency(message)
- {
- var amount = message.text.substr(config.setAllUserCommand.length + 1).trim();
- if ((amount = parseFloat(amount)))
- {
- sconomySetAll({type: 'sconomy', value: amount});
- message.client.chat(config.setUserOutput.replace(/%d/g, amount.toFixed(config.viewDistance)));
- }
- else
- {
- message.client.chat(config.notValidNumber.replace(/%d/g, message.text.substr(config.setAllUserCommand.length + 1).trim()));
- }
- }
- /**
- * @fn setStoreQuantity Set an item quantity based on the full admin request message
- * @param message The full message sent by the admin
- */
- function setStoreQuantity(message)
- {
- var args = message.text.substr(config.setStoreQuantity.length + 1).trim().split(' ');
- if (args.length >= 2)
- {
- var group = parseFloat(args[0]),
- amount = parseFloat(args[args.length - 1]);
- if (!isNaN(group) && !isNaN(amount))
- {
- // Actual setting
- sconomySet({
- userUID: 'SCO_GRP_' + group,
- type: 'quantity',
- value: amount
- });
- message.client.chat(config.setStoreOutput.replace(/%d/g, amount.toFixed(config.viewDistance)));
- }
- else
- {
- message.client.chat(config.notValidNumber.replace(/%d/g, args[0] + ' - ' + args[args.length - 1]));
- }
- }
- else
- {
- message.client.chat(config.notEnoughtArgument.replace(/%h/g, config.helpCommand));
- }
- }
- /**
- * @fn migrateDataFromProvider Migrate from data from one provider to another based on the full admin request message
- * @param message The full message sent by the admin
- */
- function migrateDataFromProvider(message)
- {
- /*
- * Possible arguments:
- * private_public
- * public_private
- * unset_private
- * unset_public
- * <any other argument added by the sconomy external data provider>
- */
- var arg = message.text.substr(29).trim();
- if (typeof migrationProvider[arg] === "function")
- {
- // Save users progress
- backend.getClients().forEach(function(client)
- {
- antiIOProvider.flush(client.uid(), false);
- });
- // Migrate the data
- var success = migrationProvider[arg](store);
- message.client.chat(success ? "Should be OK, see the log for sure" : "Error");
- }
- else
- {
- message.client.chat("Unknown argument");
- }
- }
- /* ============================= Start process ============================= */
- event.on('load', function()
- {
- // Try to link sconomy to a database
- sconomyDBIntegration();
- /* ============================== Timer start ============================== */
- setTimeout(computeTick, 1000);
- /* ================== Client connection events registring ================== */
- event.on('clientMove', function(evt)
- {
- // Client leaves
- if (typeof evt.toChannel === 'undefined')
- {
- // Flush the RAM-proress as the main function won't be capable of
- antiIOProvider.flush(evt.client.uid(), true);
- }
- });
- /* ========================= Chat events registring ========================= */
- // Chat response
- event.on('chat', function(message)
- {
- // Get help
- if (message.text === config.helpCommand)
- {
- getHelp(message.client);
- }
- // Get wallet amount
- else if (message.text === config.command)
- {
- // Flush the RAM-proress (compatibility purpose)
- antiIOProvider.flush(message.client.uid(), false);
- getCurrency(message.client);
- }
- // Get the store
- else if (message.text === config.storeCommand)
- {
- getStore(message.client);
- }
- // Buy
- else if (message.text.startsWith(config.buyCommand))
- {
- buyServergroup(message);
- }
- // Sell
- else if (message.text.startsWith(config.sellCommand))
- {
- sellServergroup(message);
- }
- // Give
- else if (config.enableGiving && message.text.startsWith(config.giveCommand))
- {
- giveCurrency(message);
- }
- // Permission check
- else if (isAdmin(message.client))
- {
- // Get a user sconomy
- if (message.text.startsWith(config.getUserCommand))
- {
- getUserCurrency(message);
- }
- // Set a user sconomy
- else if (message.text.startsWith(config.setUserCommand))
- {
- setUserCurrency(message);
- }
- // Add currency to a user
- else if (message.text.startsWith(config.addUserCommand))
- {
- addUserCurrency(message);
- }
- // Remove currency to a user
- else if (message.text.startsWith(config.removeUserCommand))
- {
- removeUserCurrency(message);
- }
- // Set all user sconomy
- else if (message.text.startsWith(config.setAllUserCommand))
- {
- setAllUserCurrency(message);
- }
- // Set store item quantity
- else if (message.text.startsWith(config.setStoreQuantity))
- {
- setStoreQuantity(message);
- }
- // Migration command
- else if (message.text.startsWith('!sconomy-data-migration-tool '))
- {
- // Small confirmation that may save some people
- if (!migrationProvider.confirmation)
- {
- migrationProvider.confirmation = true;
- setTimeout(function()
- {
- migrationProvider.confirmation = false;
- }, 5000);
- message.client.chat("You have 5 seconds to send it again to confirm your request");
- }
- else
- {
- migrateDataFromProvider(message);
- }
- }
- }
- });
- // log info on startup
- engine.log( info.name +
- ' v' + info.version +
- ' by ' + info.author +
- ' loaded successfully!'
- );
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement