// 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 = "Custom 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 const XP_POTION_TEXT = "**Experience Potion** ![Yellow potion](https://raw.githubusercontent.com/Mike-Antonacci/Habitica-custom-potions/main/experience%20potion%20large%20transparent%20wide%20432.png)"; const XP_POTION_ALIAS = "XPpotion"; const XP_POTION_NOTES = "Gain 150 Experience (Instant Use). Maximum per day: no more than 1/3 of what's needed to level up."; const XP_POTION_VALUE = "25"; const XP_POTION_LEVEL_LOCK = 21; const MSG_XP_POTION_LEVEL_LOCK_FAIL = "You must be at least level 21 to use this potion."; const MSG_XP_POTION_DAILY_USAGE_EXCEEDED = "You've already gained your maximum allowable XP from potions today."; const MP_POTION_TEXT = "**Mana Potion** ![Blue potion](https://raw.githubusercontent.com/Mike-Antonacci/Habitica-custom-potions/main/mana%20potion%20large%20transparent%20wide%20432.png)"; const MP_POTION_ALIAS = "MPpotion"; const MP_POTION_NOTES = "Recover 30 Mana (Instant Use). Maximum 4 per day." const MP_POTION_VALUE = "25"; const MP_POTION_LEVEL_LOCK = 16; const MSG_MP_POTION_LEVEL_LOCK_FAIL = "You must be at least level 11 to use this potion."; const MAX_DAILY_MP_POTION_USAGE = 4; const MSG_MP_POTION_DAILY_USAGE_EXCEEDED = "You can only use this potion four times each day."; 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 4 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_VALUE, } const MP_POTION_BUTTON = { "text": MP_POTION_TEXT, "type": "reward", "alias": MP_POTION_ALIAS, "notes": MP_POTION_NOTES, "value": MP_POTION_VALUE, } 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_EXPERIENCE_POTION == 1) && (CREATE_MANA_POTION == 1)) { api_createNewTaskForUser([MP_POTION_BUTTON, XP_POTION_BUTTON]); } else if ((CREATE_EXPERIENCE_POTION == 1) && (CREATE_MANA_POTION == 0)) { api_createNewTaskForUser([XP_POTION_BUTTON]); } else if ((CREATE_EXPERIENCE_POTION == 0) && (CREATE_MANA_POTION == 1)) { api_createNewTaskForUser([MP_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 if ((task.alias == undefined) || (task.alias == null)) { task.alias = ""; } // Check if a task was scored and if it was the either alias if ((type == "scored") && ( (task.alias == XP_POTION_ALIAS) || (task.alias == 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)); 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; // If they've Cronned, reset all counters if (cronCount != user.flags.cronCount) { cronCount = user.flags.cronCount; xpUsage = 0; mpUsage = 0; } // Check if it was XPpotion alias, then do XP Potion things if (task.alias == XP_POTION_ALIAS) { 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 level lock fails, refund the money and send failure message if (lvl < XP_POTION_LEVEL_LOCK) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp, "stats.exp" : exp, "stats.gp" : gp + 25}); api_sendPrivateMessage({"message" : MSG_XP_POTION_LEVEL_LOCK_FAIL, "toUserId" : USER_ID}); } else { // If another potion (+150 XP) would put them above the max, refund the money and send failure message if (xpUsage + 150 > MaxDailyXpUsage) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp, "stats.exp" : exp, "stats.gp" : gp + 25}); api_sendPrivateMessage({"message" : MSG_XP_POTION_DAILY_USAGE_EXCEEDED, "toUserId" : USER_ID}); } // If another potion wouldn't make them exceed the max, run as normal and increment counter else { api_updateUser({"stats.hp" : hp, "stats.mp" : mp, "stats.exp" : exp + 150, "stats.gp" : gp}); xpUsage += 150; } } } // Check if it was MPpotion alias, then do XP Potion things else if (task.alias == MP_POTION_ALIAS) { // Get equipment stats info const responseContent = apiFree_getAllAvailableContentObjects(); content = JSON.parse(responseContent).data; // Compute total Intelligence var int = calcTotalIntelligence(); var maxMp = (2 * int) + 30; var mpDiff = maxMp - mp; // If level lock fails, refund the money and send failure message if (lvl < MP_POTION_LEVEL_LOCK) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp, "stats.exp" : exp, "stats.gp" : gp + 25}); api_sendPrivateMessage({"message" : MSG_MP_POTION_LEVEL_LOCK_FAIL, "toUserId" : USER_ID}); } else { // Check if they've exceeded daily usage. If yes, refund the money and send failure message if (mpUsage >= MAX_DAILY_MP_POTION_USAGE) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp, "stats.exp" : exp, "stats.gp" : gp + 25}); api_sendPrivateMessage({"message" : MSG_MP_POTION_DAILY_USAGE_EXCEEDED, "toUserId" : USER_ID}); } else { // Check if they're already at maximum mana. If yes, refund the money and send failure message if (mpDiff <= 0) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp, "stats.exp" : exp, "stats.gp" : gp + 25}); 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 <= 30) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp + mpDiff, "stats.exp" : exp, "stats.gp" : gp}); mpUsage ++; api_sendPrivateMessage({"message" : MSG_NEAR_MAX_MANA, "toUserId" : USER_ID}); } // Run as normal if they're further than 30 MP away from maximum else if (mpDiff > 30) { api_updateUser({"stats.hp" : hp, "stats.mp" : mp + 30, "stats.exp" : exp, "stats.gp" : gp}); mpUsage ++; } } } // 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(xpUsageKey, xpUsage); scriptProperties.setProperty(mpUsageKey, mpUsage); 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(XP_USAGE_KEY, 0); scriptProperties.setProperty(MP_USAGE_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); } // 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; } } 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; }