// 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_HP_FOR_MP = 1; // Change this 1 to a 0 if you don't want to create a skill that swaps HP for MP const CREATE_XP_FOR_MP = 1; // Change this 1 to a 0 if you don't want to create a skill that swaps XP for MP /* ========================================== */ /* [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 = "Swap HP or XP for MP"; 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 const HP_FOR_MP_TEXT = "**Swap Health for Mana**"; const HP_FOR_MP_ALIAS = "HPforMP"; const HP_FOR_MP_NOTES = "Pay 5 HP, gain 10 MP. Maximum 12 per day."; const HP_FOR_MP_VALUE = "0"; const HP_FOR_MP_LEVEL_LOCK = 11; const MAX_DAILY_HP_FOR_MP_USAGE = 12; const MSG_HP_FOR_MP_LEVEL_LOCK_FAIL = "You must be at least level 11 to use this skill."; const MSG_HP_FOR_MP_DAILY_USAGE_EXCEEDED = "You can only use this skill 12 times each day."; const MSG_INSUFFICIENT_HP = "Insufficient Health to use this skill." const XP_FOR_MP_TEXT = "**Swap Experience for Mana**"; const XP_FOR_MP_ALIAS = "XPforMP"; const XP_FOR_MP_NOTES = "Pay 50 XP, gain 10 MP. Maximum XP spent per day: 1/3 of what's needed to level up."; const XP_FOR_MP_VALUE = "0"; const XP_FOR_MP_LEVEL_LOCK = 11; const MAX_DAILY_XP_FOR_MP_USAGE = 12; const MSG_XP_FOR_MP_LEVEL_LOCK_FAIL = "You must be at least level 11 to use this skill."; const MSG_XP_FOR_MP_DAILY_USAGE_EXCEEDED = "You can only use this skill to spend up to 1/3 of the XP needed to level up, and you've reached your limit."; const MSG_INSUFFICIENT_XP = "Insufficient Experience to use this skill." const MSG_ALREADY_AT_MAX_MANA = "You are already have maximum mana. This skill had no effect and did not count towards your daily usage limit." const MSG_NEAR_MAX_MANA = "This skill filled you to maximum Mana, but not beyond the max."; const HP_FOR_MP_BUTTON = { "text": HP_FOR_MP_TEXT, "type": "reward", "alias": HP_FOR_MP_ALIAS, "notes": HP_FOR_MP_NOTES, "value": HP_FOR_MP_VALUE, } const XP_FOR_MP_BUTTON = { "text": XP_FOR_MP_TEXT, "type": "reward", "alias": XP_FOR_MP_ALIAS, "notes": XP_FOR_MP_NOTES, "value": XP_FOR_MP_VALUE, } const CRON_COUNT_KEY = "CRON_COUNT_KEY"; const HP_FOR_MP_KEY = "HP_FOR_MP_KEY"; const XP_FOR_MP_KEY = "XP_FOR_MP_KEY"; const TIMESTAMP_KEY = "TIMESTAMP_KEY"; var cronCountKey = ""; var HpForMpUsageKey = ""; var XpForMpUsageKey = ""; var timestampKey = ""; function doOneTimeSetup() { if ((CREATE_HP_FOR_MP == 1) && (CREATE_XP_FOR_MP == 1)) { api_createNewTaskForUser([XP_FOR_MP_BUTTON, HP_FOR_MP_BUTTON]); } else if ((CREATE_HP_FOR_MP == 1) && (CREATE_XP_FOR_MP == 0)) { api_createNewTaskForUser([HP_FOR_MP_BUTTON]); } else if ((CREATE_HP_FOR_MP == 0) && (CREATE_XP_FOR_MP == 1)) { api_createNewTaskForUser([XP_FOR_MP_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 if ((task.alias == undefined) || (task.alias == null)) { task.alias = ""; } if ( (type == "scored") && ( (task.alias == HP_FOR_MP_ALIAS) || (task.alias == XP_FOR_MP_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 ) { // Run all the things that run regardless of the skill const responseUser = api_getAuthenticatedUserProfile("stats,items.gear.equipped"); user = JSON.parse(responseUser).data; var hp = user.stats.hp; var exp = user.stats.exp; var mp = user.stats.mp; var gp = user.stats.gp; var lvl = user.stats.lvl; // Get equipment stats info const responseContent = apiFree_getAllAvailableContentObjects(); content = JSON.parse(responseContent).data; // Compute total Intelligence var int = calcTotalIntelligence(); // Compute maximum mana and how close they are to max var maxMp = (2 * int) + 30; var mpDiff = maxMp - mp; // Counters var cronCountKey = CRON_COUNT_KEY; var HpForMpUsageKey = HP_FOR_MP_KEY; var XpForMpUsageKey = XP_FOR_MP_KEY; var cronCount = Number(scriptProperties.getProperty(cronCountKey)); var HpForMpUsage = Number(scriptProperties.getProperty(HpForMpUsageKey)); var XpForMpUsage = Number(scriptProperties.getProperty(XpForMpUsageKey)); // If they've Cronned, reset all counters if (cronCount != user.flags.cronCount) { cronCount = user.flags.cronCount; HpForMpUsage = 0; XpForMpUsage = 0; } // If it was the HP-for-MP alias, do those things if (task.alias == HP_FOR_MP_ALIAS){ // If level lock fails, send failure message if (lvl < HP_FOR_MP_LEVEL_LOCK) { api_sendPrivateMessage({"message" : MSG_HP_FOR_MP_LEVEL_LOCK_FAIL, "toUserId" : USER_ID}); } else { // Check if they've exceeded daily usage. If yes, send failure message. if (HpForMpUsage >= MAX_DAILY_HP_FOR_MP_USAGE) { api_sendPrivateMessage({"message" : MSG_HP_FOR_MP_DAILY_USAGE_EXCEEDED, "toUserId" : USER_ID}); } else { // Check if they have sufficient Health. Send failure message if not. if (hp < 5) { api_sendPrivateMessage({"message" : MSG_INSUFFICIENT_HP, "toUserId" : USER_ID}); } else { // Check if they're already at maximum mana. If yes, send failure message if (mpDiff <= 0) { 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 <= 10) { api_updateUser({"stats.hp" : hp - 5, "stats.mp" : mp + mpDiff, "stats.exp" : exp, "stats.gp" : gp}); HpForMpUsage++; api_sendPrivateMessage({"message" : MSG_NEAR_MAX_MANA, "toUserId" : USER_ID}); } // Otherwise, run as normal else if (mpDiff > 10){ api_updateUser({"stats.hp" : hp - 5, "stats.mp" : mp + 10, "stats.exp" : exp, "stats.gp" : gp}); HpForMpUsage++; } } } } } // If it was the XP-for-MP alias, do those things if (task.alias == XP_FOR_MP_ALIAS){ // If level lock fails, send failure message if (lvl < XP_FOR_MP_LEVEL_LOCK) { api_sendPrivateMessage({"message" : MSG_XP_FOR_MP_LEVEL_LOCK_FAIL, "toUserId" : USER_ID}); } else { // Check if another use (50 XP) would cause them to exceed daily usage. If yes, send failure message. var XpToNextLevel = Math.round((Math.pow(user.stats.lvl, 2) * 0.25 + 10 * user.stats.lvl + 139.75) / 10) * 10; var MaxDailyXpUsage = Math.floor(XpToNextLevel / 3); if (XpForMpUsage + 50 > MaxDailyXpUsage) { api_sendPrivateMessage({"message" : MSG_XP_FOR_MP_DAILY_USAGE_EXCEEDED, "toUserId" : USER_ID}); } else { // Check if they have sufficient Experience. Send failure message if not. if (exp < 50) { api_sendPrivateMessage({"message" : MSG_INSUFFICIENT_XP, "toUserId" : USER_ID}); } else { // Check if they're already at maximum mana. If yes, send failure message if (mpDiff <= 0) { 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 <= 10) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp + mpDiff, "stats.exp" : exp - 50, "stats.gp" : gp}); XpForMpUsage += 50; api_sendPrivateMessage({"message" : MSG_NEAR_MAX_MANA, "toUserId" : USER_ID}); } // Otherwise, run as normal else if (mpDiff > 10){ api_updateUser({"stats.hp" : hp, "stats.mp" : mp + 10, "stats.exp" : exp - 50, "stats.gp" : gp}); XpForMpUsage += 50; } } } } } // 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(cronCountKey, cronCount); scriptProperties.setProperty(HpForMpUsageKey, HpForMpUsage); scriptProperties.setProperty(XpForMpUsageKey, XpForMpUsage); scriptProperties.setProperty(timestampKey, timeStart); } } return HtmlService.createHtmlOutput(); } // 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() { var timestampInit = Date.now(); scriptProperties.setProperty(CRON_COUNT_KEY, 0); scriptProperties.setProperty(HP_FOR_MP_KEY, 0); scriptProperties.setProperty(XP_FOR_MP_KEY, 0); scriptProperties.setProperty(TIMESTAMP_KEY, timestampInit); } // 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 apiFree_getAllAvailableContentObjects() { const params = { "method" : "get", "muteHttpExceptions" : true, } const url = "https://habitica.com/api/v3/content"; return UrlFetchApp.fetch(url, params); } function calcTotalIntelligence() { 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; } // 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; } }