// This code is licensed under the same terms as Habitica: // https://raw.githubusercontent.com/HabitRPG/habitrpg/develop/LICENSE /* ========================================== */ /* [Users] Required script data to fill in */ /* ========================================== */ const USER_ID = "PasteYourUserIdHere" const API_TOKEN = "PasteYourApiTokenHere" // Do not share this to anyone const WEB_APP_URL = "PasteGeneratedWebAppUrlHere" /* ========================================== */ /* [Users] Required customizations to fill in */ /* ========================================== */ const CREATE_EXPERIENCE_POTION = 1 // Change this 1 to a 0 if you don't want the Experience Potion const CREATE_MANA_POTION = 1 // Change this 1 to a 0 if you don't want the Mana Potion /* ========================================== */ /* [Users] Optional customizations to fill in */ /* ========================================== */ // Do you want to get private message notifications? (examples include if you're already at max Mana or exceeded the limit for daily potion usage) // If you don't want them, change the 1 to a 0 in the line below const NOTIFICATIONS_ON = 1 /* ========================================== */ /* [Users] Do not edit code below this line */ /* ========================================== */ const AUTHOR_ID = "0034eb14-b4d8-494e-8386-d3f33cff7922" const SCRIPT_NAME = "Experience and Mana Potions" const HEADERS = { "x-client" : AUTHOR_ID + " - " + SCRIPT_NAME, "x-api-user" : USER_ID, "x-api-key" : API_TOKEN, } const scriptProperties = PropertiesService.getScriptProperties() // Constants can have properties changed // Parts of messages that get reused const MSG_LEVEL_LOCK_START = "You must be at least level " const MSG_LEVEL_LOCK_END = " to use this " const MSG_LEVEL_LOCK_END_POTION = MSG_LEVEL_LOCK_END + "potion." const MSG_DAILY_USAGE_EXCEEDED_START = "You can only use this " const MSG_DAILY_USAGE_EXCEEDED_START_POTION = MSG_DAILY_USAGE_EXCEEDED_START + "potion " const MSG_DAILY_USAGE_EXCEEDED_END = " times each day." // Conversion rate between stats const XP_CONVERSION_RATE = 6 // 150 XP = 25 GP const MP_CONVERSION_RATE = 1.2 // 30 MP = 25 GP const XP_POTION_TEXT = "**Experience Potion** ![Yellow potion](https://raw.githubusercontent.com/mike-the-monk/Habitica-customizations/main/Automated%20FCV%20scripts/images/experience%20potion%20large%20transparent%20wide%20432.png)" const XP_POTION_ALIAS = "XPpotion" const XP_POTION_COST = 25 const XP_GAIN = XP_CONVERSION_RATE * XP_POTION_COST const MAX_DAILY_XP_POTION_USAGE = "1/3" const XP_POTION_NOTES = "Gain " + XP_GAIN + " Experience (Instant Use). Maximum per day: no more than " + MAX_DAILY_XP_POTION_USAGE + " of what's needed to level up." const XP_POTION_LEVEL_LOCK = 21 const MP_POTION_TEXT = "**Mana Potion** ![Blue potion](https://raw.githubusercontent.com/mike-the-monk/Habitica-customizations/main/Automated%20FCV%20scripts/images/mana%20potion%20large%20transparent%20wide%20432.png)" const MP_POTION_ALIAS = "MPpotion" const MP_POTION_COST = 25 const MP_GAIN = MP_CONVERSION_RATE * MP_POTION_COST const MAX_DAILY_MP_POTION_USAGE = 4 const MP_POTION_NOTES = "Recover " + MP_GAIN + " Mana (Instant Use). Maximum " + MAX_DAILY_MP_POTION_USAGE + " per day." const MP_POTION_LEVEL_LOCK = 11 const MSG_ALREADY_AT_MAX_MANA = "You are already have maximum mana. This potion had no effect and did not count towards your daily limit of "+MAX_DAILY_MP_POTION_USAGE+" potions." const MSG_NEAR_MAX_MANA = "This potion filled you to maximum Mana, but not beyond the max." const XP_POTION_BUTTON = { "text": XP_POTION_TEXT, "type": "reward", "alias": XP_POTION_ALIAS, "notes": XP_POTION_NOTES, "value": XP_POTION_COST, } const MP_POTION_BUTTON = { "text": MP_POTION_TEXT, "type": "reward", "alias": MP_POTION_ALIAS, "notes": MP_POTION_NOTES, "value": MP_POTION_COST, } const CRON_COUNT_KEY = "CRON_COUNT_KEY" const XP_USAGE_KEY = "XP_USAGE_KEY" const MP_USAGE_KEY = "MP_USAGE_KEY" const TIMESTAMP_KEY = "TIMESTAMP_KEY" var cronCountKey = "" var xpUsageKey = "" var mpUsageKey = "" var timestampKey = "" function doOneTimeSetup() { if (CREATE_MANA_POTION == 1) { api_createNewTaskForUser([MP_POTION_BUTTON]) } if (CREATE_EXPERIENCE_POTION == 1) { api_createNewTaskForUser([XP_POTION_BUTTON]) } // Next, create the webhook const options = { "scored" : true, } const payload = { "url" : WEB_APP_URL, "label" : SCRIPT_NAME + " Webhook", "type" : "taskActivity", "options" : options, } apiMult_createNewWebhookNoDuplicates(payload) // set script properties so they carry over to next session initScriptProperties() } // do things when the webhook runs function doPost(e) { const dataContents = JSON.parse(e.postData.contents) const type = dataContents.type const task = dataContents.task // Sanitize task alias let sanitizedAlias = "sanitized" // This will be the value if undefined, null, or blank if ( (task.alias != undefined) && (task.alias != null) && (task.alias != "") ) { sanitizedAlias = task.alias } // Check if a task was scored and if it was the either alias if ((type == "scored") && ( (sanitizedAlias == XP_POTION_ALIAS) || (sanitizedAlias == MP_POTION_ALIAS) ) ) { var timestampKey = TIMESTAMP_KEY var timeStart = Number(scriptProperties.getProperty(timestampKey)) if ( (timeStart == 0) || (timeStart == "") || (timeStart == undefined) || (timeStart == null) ) { timeStart = Date.now() } var timeEnd = Date.now() // Rate limiting: If it's been less than 30 seconds since they last clicked one of these buttons, do nothing if ( (timeEnd - timeStart) >= 30000 ) { const response = api_getAuthenticatedUserProfile("stats,items.gear.equipped") user = JSON.parse(response).data var cronCountKey = CRON_COUNT_KEY var xpUsageKey = XP_USAGE_KEY var mpUsageKey = MP_USAGE_KEY var cronCount = Number(scriptProperties.getProperty(cronCountKey)) var xpUsage = Number(scriptProperties.getProperty(xpUsageKey)) var mpUsage = Number(scriptProperties.getProperty(mpUsageKey)) let exp = user.stats.exp let mp = user.stats.mp let gp = user.stats.gp let lvl = user.stats.lvl // If they've Cronned, reset all counters if (cronCount != user.flags.cronCount) { cronCount = user.flags.cronCount resetCounters() // Save to non-volatile memory scriptProperties.setProperty(cronCountKey, cronCount) } // Switch-case based on which button was pressed. All button-click actions are in a separate function. switch (sanitizedAlias){ case XP_POTION_ALIAS: doButtonXpPotion(lvl, gp, exp, xpUsage, xpUsageKey) break case MP_POTION_ALIAS: doButtonMpPotion(lvl, gp, mp, mpUsage, mpUsageKey) break } // Save values to non-volatile memory, but only from within the rate-limited if-block (we don't want to save the timestamp unless the script ran) timeStart = timeEnd scriptProperties.setProperty(timestampKey, timeStart) } } return HtmlService.createHtmlOutput() } // When the XP Potion button is clicked function doButtonXpPotion(lvl, gp, exp, xpUsage, xpUsageKey){ let XpToNextLevel = Math.round((Math.pow(lvl, 2) * 0.25 + 10 * lvl + 139.75) / 10) * 10 let MaxDailyXpUsage = Math.floor(XpToNextLevel * eval(MAX_DAILY_XP_POTION_USAGE)) // If level lock fails, refund the money and send failure message let sufficientLevel = checkLevelLock(lvl, XP_POTION_LEVEL_LOCK, "potion.") if (!sufficientLevel) { api_updateUser({"stats.gp" : gp + XP_POTION_COST}) } else { // If another potion (+XP_GAIN XP) would put them above the max, refund the money and send failure message let usageLimitOkay = checkUsageLimit(xpUsage, XP_GAIN, MaxDailyXpUsage, "potion ", true, false) if (!usageLimitOkay) { api_updateUser({"stats.gp" : gp + XP_POTION_COST}) } else { // If another potion wouldn't make them exceed the max, run as normal and increment counter api_updateUser({"stats.exp" : exp + XP_GAIN}) xpUsage += XP_GAIN // Save new counter value since it's updated scriptProperties.setProperty(xpUsageKey, xpUsage) } } } // When the MP Potion button is clicked function doButtonMpPotion(lvl, gp, mp, mpUsage, mpUsageKey){ // Get equipment stats info const responseContent = api_getAllAvailableContentObjects() content = JSON.parse(responseContent).data // Compute total Intelligence let int = calculateIntelligence() let maxMp = (2 * int) + 30 let mpDiff = maxMp - mp // If level lock fails, refund the money and send failure message let sufficientLevel = checkLevelLock(lvl, MP_POTION_LEVEL_LOCK, "potion.") if (!sufficientLevel) { api_updateUser({"stats.gp" : gp + MP_POTION_COST}) } else { // Check if they've exceeded daily usage. If yes, refund the money and send failure message let usageLimitOkay = checkUsageLimit(mpUsage, 1, MAX_DAILY_MP_POTION_USAGE, "potion ", false, false) if (!usageLimitOkay) { api_updateUser({"stats.gp" : gp + MP_POTION_COST}) } else { // Check if they're already at maximum mana. If yes, refund the money and send failure message if (mpDiff <= 0) { api_updateUser({"stats.gp" : gp + MP_POTION_COST}) api_sendPrivateMessage({"message" : MSG_ALREADY_AT_MAX_MANA, "toUserId" : USER_ID}) } // Check if they're close to maximum mana. If yes, refill them to max but not beyond, and send a message else if (mpDiff <= MP_GAIN) { api_updateUser({"stats.mp" : mp + mpDiff}) mpUsage++ api_sendPrivateMessage({"message" : MSG_NEAR_MAX_MANA, "toUserId" : USER_ID}) // Save new counter value since it's updated scriptProperties.setProperty(mpUsageKey, mpUsage) } // Run as normal if they're further than MP_GAIN MP away from maximum else if (mpDiff > MP_GAIN) { api_updateUser({"stats.mp" : mp + MP_GAIN}) mpUsage ++ // Save new counter value since it's updated scriptProperties.setProperty(mpUsageKey, mpUsage) } } } } // Create custom reward buttons function api_createNewTaskForUser(payload) { var params = { "method" : "post", "headers" : HEADERS, "contentType" : "application/json", "payload" : JSON.stringify(payload), // Rightmost button goes on top "muteHttpExceptions" : true, } var url = "https://habitica.com/api/v3/tasks/user" UrlFetchApp.fetch(url, params) } // Create a webhook if no duplicate exists function apiMult_createNewWebhookNoDuplicates(payload) { const response = api_getWebhooks() const webhooks = JSON.parse(response).data var duplicateExists = 0 for (var i in webhooks) { if (webhooks[i].label == payload.label) { duplicateExists = 1 } } // If webhook to be created doesn't exist yet if (!duplicateExists) { api_createNewWebhook(payload) } } // Used to see existing webhooks, and therefore if there's a duplicate function api_getWebhooks() { const params = { "method" : "get", "headers" : HEADERS, "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/user/webhook" return UrlFetchApp.fetch(url, params) } // Creates a webhook (as part of the "don't make it if there's a duplicate" function) function api_createNewWebhook(payload) { const params = { "method" : "post", "headers" : HEADERS, "contentType" : "application/json", "payload" : JSON.stringify(payload), "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/user/webhook" return UrlFetchApp.fetch(url, params) } // Sets initial properties that will be used/saved later. function initScriptProperties() { const responseUser = api_getAuthenticatedUserProfile("stats") user = JSON.parse(responseUser).data let cronCount = user.flags.cronCount scriptProperties.setProperty(CRON_COUNT_KEY, cronCount) var timestampInit = Date.now() scriptProperties.setProperty(TIMESTAMP_KEY, timestampInit) scriptProperties.setProperty(XP_USAGE_KEY, 0) scriptProperties.setProperty(MP_USAGE_KEY, 0) } // Gets user info so I can use it, especially stats like mana, experience, and level function api_getAuthenticatedUserProfile(userFields) { const params = { "method" : "get", "headers" : HEADERS, "muteHttpExceptions" : true, } var url = "https://habitica.com/api/v3/user" if (userFields != "") { url += "?userFields=" + userFields } return UrlFetchApp.fetch(url, params) } function api_getAllAvailableContentObjects() { const params = { "method" : "get", "headers" : HEADERS, "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/content" return UrlFetchApp.fetch(url, params) } // Changes stats function api_updateUser(payload) { const params = { "method" : "put", "headers" : HEADERS, "contentType" : "application/json", "payload" : JSON.stringify(payload), "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/user" return UrlFetchApp.fetch(url, params) } // Send a notification as a private message, only if they're enabled function api_sendPrivateMessage(payload) { switch (NOTIFICATIONS_ON){ // Check if notifications are on, send message if yes case 0: break case 1: const params = { "method" : "post", "headers" : HEADERS, "contentType" : "application/json", "payload" : JSON.stringify(payload), "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/members/send-private-message" return UrlFetchApp.fetch(url, params) break } } // Resets usage counters, usually done at Cron function resetCounters(){ scriptProperties.setProperty(XP_USAGE_KEY, 0) scriptProperties.setProperty(MP_USAGE_KEY, 0) } function calculateIntelligence() { const levelIntRaw = Math.floor(user.stats.lvl / 2) const levelInt = (levelIntRaw > 50) ? 50 : levelIntRaw var totalEquipmentAndClassInt = 0 const allocatedInt = user.stats.int const buffsInt = user.stats.buffs.int // Get INT from equipped gear totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.weapon]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.shield]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.head]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.armor]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.headAccessory]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.eyewear]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.body]) totalEquipmentAndClassInt += calcEquipmentAndClassInt(content.gear.flat[user.items.gear.equipped.back]) return levelInt + totalEquipmentAndClassInt + allocatedInt + buffsInt } function calcEquipmentAndClassInt(equipment) { var equipmentAndClassInt = 0 if (equipment != undefined) { equipmentAndClassInt += equipment.int if ( (equipment.klass == user.stats.class) || ( (equipment.klass == "special") && (equipment.specialClass == user.stats.class) ) ) { equipmentAndClassInt += equipment.int / 2 } } return equipmentAndClassInt } // Check if sufficient level, send message if not. function checkLevelLock(level, levelLock, messageEndVariable){ if (level < levelLock){ let errorMsg = MSG_LEVEL_LOCK_START + levelLock + MSG_LEVEL_LOCK_END + messageEndVariable api_sendPrivateMessage({"message" : errorMsg, "toUserId" : USER_ID}) return false } else { return true } } // Check if (daily) usage exceeded, send message if yes. function checkUsageLimit(usageCounter, newUsageIncrement, maxUsage, messageMidVariable, isForXp, isForXpPaid){ if ( (usageCounter + newUsageIncrement) > maxUsage ) { let errorMsg = MSG_DAILY_USAGE_EXCEEDED_START + messageMidVariable + maxUsage + MSG_DAILY_USAGE_EXCEEDED_END // Since the max usage for XP potion/skill is different, the message will be different. if (isForXp) { // Message start differs if it's XP gained vs. XP paid if (isForXpPaid) { errorMsg = MSG_DAILY_USAGE_EXCEEDED_XP_START_PAY } else { errorMsg = MSG_DAILY_USAGE_EXCEEDED_XP_START } errorMsg += messageMidVariable + MSG_DAILY_USAGE_EXCEEDED_XP_MID_1 + maxUsage + MSG_DAILY_USAGE_EXCEEDED_XP_MID_2 + MAX_DAILY_XP_POTION_USAGE + MSG_DAILY_USAGE_EXCEEDED_XP_END } api_sendPrivateMessage({"message" : errorMsg, "toUserId" : USER_ID}) return false } else { return true } } // Send a notification as a private message regardless of if they're enabled function api_sendPrivateMessageAlways(payload) { const params = { "method" : "post", "headers" : HEADERS, "contentType" : "application/json", "payload" : JSON.stringify(payload), "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/members/send-private-message" return UrlFetchApp.fetch(url, params) } // FUNCTIONS FOR DEBUGGING. SCRIPT DOES NOT USE THEM, THEY MUST BE TRIGGERED MANUALLY // Manually reset usage counters function debugResetCounters() { resetCounters() } // Retrieves saved values and sends them in a private message function debugGetSavedValues(){ let cronCount = Number(scriptProperties.getProperty(CRON_COUNT_KEY)) let xpUsage = Number(scriptProperties.getProperty(XP_USAGE_KEY)) let mpUsage = Number(scriptProperties.getProperty(MP_USAGE_KEY)) // saving these will make my life easier let MSG_JOINER_BEFORE = " is `" let MSG_JOINER_AFTER = "`, " api_sendPrivateMessageAlways({"message" : "Saved values are as follows: cronCount is `" + cronCount + MSG_JOINER_AFTER + "xpUsage" + MSG_JOINER_BEFORE + xpUsage + MSG_JOINER_AFTER + "mpUsage" + MSG_JOINER_BEFORE + mpUsage + "`", "toUserId" : USER_ID}) } // Mannually edits and saves the selected value (in case it saved incorrectly) function debugManuallyEditSavedValue() { // Fill them in below. xpUsage is shown as a sample. let newValue = 0 let key = XP_USAGE_KEY // Save scriptProperties.setProperty(key, newValue) }