Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // eslint-disable-next-line no-unused-vars
- const findResource = (() => {
- const r20_5e = {
- repSec: [
- {
- sec: 'repeating_resource',
- nameAttrs: ['resource_left_name', 'resource_right_name'], // index of Name Attributes should match index of linked Value Attributes in next Array
- valAttrs: ['resource_left', 'resource_right'],
- }
- ],
- other:
- {
- nameAttrs: ['class_resource_name', 'other_resource_name'], // index of Name Attributes should match index of linked Value Attributes in next Array
- valAttrs: ['class_resource', 'other_resource']
- }
- };
- const currentSheet = r20_5e;
- let scriptName = 'findResourceBot';
- let lastWho, selectedToken;
- let silentMode, publicMode;
- const modRes = (char, attrName, attrMod, limit, silent) => {
- silentMode = (silent) ? true : silentMode;
- let targetAttr = findRes(char, attrName);
- if (!targetAttr) return sendChat(scriptName, `/w ${lastWho} No resource named ${attrName} found on ${char.id}`);
- let curVal = targetAttr.get('current');
- let mod = (attrMod.match(/^\s*([+-])\s*/)) ? attrMod.match(/^\s*([+-])\s*/)[1] : null;
- let newVal;
- if (mod) {
- curVal = parseFloat(curVal, 10);
- let modVal = (attrMod.match(/\d+/)) ? parseFloat(attrMod.match(/\d+/)[0]) : null;
- if (isNaN(curVal) || isNaN(modVal)) return sendChat(scriptName, `/w ${lastWho} Error: must use integers with math, check input:"${attrMod} or resource ${attrName}`);
- if (mod.match(/\+/)) newVal = (curVal + modVal);
- if (mod.match(/-/)) newVal = curVal - modVal;
- } else newVal = attrMod;
- if (limit.length) {
- newVal = (isNaN(newVal)) ? parseFloat(newVal, 10) : newVal;
- if (isNaN(newVal)) sendChat(`/w ${lastWho} Error: can only apply limit to numeric values.`);
- else {
- let minmax = limit.map(lim => {
- if (typeof(lim) === 'string' && lim.match(/max/i)) lim = targetAttr.get('max');
- lim = (!isNaN(parseFloat(lim, 10))) ? parseFloat(lim, 10) : null;
- return lim;
- });
- if (minmax[0] || minmax[0] === 0) newVal = Math.max(minmax[0], newVal);
- if (minmax[1] || minmax[1] === 0) newVal = Math.min(minmax[1], newVal);
- }
- }
- getObj('attribute', targetAttr.id).set('current', newVal);
- silentChat(scriptName, `/w ${lastWho} ${attrName} set to ${newVal}.`);
- if (publicMode) pubChat(`${char.get('name')}'s ${attrName} was set to ${newVal}.`);
- }
- const findRes = (char, attrName) => {
- let regexRes = new RegExp(`\\d+:\\s*${attrName}\\s*$`,'i');
- let otherResNames = []; // first try non-repeating attributes
- currentSheet.other.nameAttrs.forEach((attr,i) => {
- let v = findObjs({type: 'attribute', characterid: char.id, name: attr}, {caseInsensitive: true});
- if (v.length > 0) {
- otherResNames.push(`${i}:${v[0].get('current')}`);
- }
- })
- let target = otherResNames.find(a => a.match(regexRes));
- if (target) {
- let attrIndex = target.match(/(^\d+)/)[1];
- let targetName = currentSheet.other.valAttrs[attrIndex];
- let targetAttr = findObjs({type: 'attribute', characterid: char.id, name: targetName});
- if (targetAttr.length) return targetAttr[0];
- else log(`Couldn't find attribute "${targetName}"`);
- }
- let targetRep = getRepResNames(char.id, attrName); // then try rep rows
- if (targetRep) {
- let targetAttr = findObjs({type: 'attribute', characterid: char.id, name: targetRep});
- if (targetAttr.length) return targetAttr[0];
- else log(`Couldn't find repeating attribute "${targetRep}"`);
- }
- return null;
- }
- const getRepResNames = (charId, attrName) => {
- let regexRes = new RegExp(`${attrName}`,'i');
- let targetAttr;
- for (let i=0; i<currentSheet.repSec.length; i++) {
- let secName = `${currentSheet.repSec[i].sec}_$0_${currentSheet.repSec[i].nameAttrs[0]}`;
- let idArray = getRepIds(charId, secName);
- let repAttrs = getRepAttrs(charId, secName, idArray, currentSheet.repSec[i].nameAttrs, true);
- repAttrs.forEach(row => {
- currentSheet.repSec[i].nameAttrs.forEach((a, valIndex) => {
- if (row[a] && row[a].current) {
- //log(`Searching ${row[a].current}...`);
- if (row[a].current.match(regexRes)) {
- let rowId = row.rowId;
- let valAttr = currentSheet.repSec[i].valAttrs[valIndex];
- targetAttr = `${currentSheet.repSec[i].sec}_${rowId}_${valAttr}`;
- }
- }
- });
- });
- }
- return targetAttr;
- }
- const getRepIds = (charId, sectionName, ignoreBlanks = false) => {
- if (getObj('character', charId)) {
- let repSecParts = sectionName.trim().split(/_\$\d*_/);
- let regex = new RegExp(`${repSecParts[0]}_(-.*)_${repSecParts[1]}$`);
- if (repSecParts.length !== 2 || repSecParts[0].search(/repeating/i) === -1) {
- log(`Bad repeating section name: ${sectionName}, aborting...`);
- return;
- }
- //log(`repeating section: ${repSecParts[0]} --- ${repSecParts[1]}`);
- let idArray = [];
- findObjs({type: 'attribute', characterid: charId}).filter(attr => {
- if (attr.get('name').match(regex) && attr.id) {
- if (!ignoreBlanks || attr.get('current').trim() !== '') idArray.push(attr.get('name').match(regex)[1]);
- else log(`Row found, but name field blank - skipping ${charId} -- ${attr.get('name').current}`);
- }
- })
- let reporder = findObjs({type: 'attribute', characterid: charId, name: `_reporder_${repSecParts[0]}`})[0];
- if (reporder) {
- reporder = reporder.get('current').trim().split(',');
- idArray = [...new Set(reporder.filter((id) => idArray.includes(id)).concat(idArray))];
- }
- idArray.filter((attr) => attr.current != '')
- //log(idArray);
- return idArray;
- }
- }
- const getRepAttrs = (charId, sectionName, rowIds, attrNamesArray, createMissing = false) => {
- if (getObj('character', charId) && sectionName.search(/repeating.*_\$/i) !== -1) {
- let sectionPrefix = sectionName.match(/(repeating.*_)\$/i)[1];
- attrNamesArray = (Array.isArray(attrNamesArray)) ? attrNamesArray : [attrNamesArray];
- attrNamesArray = attrNamesArray.filter((a) => (a) && a != '0')
- rowIds = (Array.isArray(rowIds)) ? rowIds : [rowIds];
- let attrArray = [], index = 0;
- rowIds.forEach(row => {
- let rowObj = {prefix: sectionPrefix, rowId: row};
- attrNamesArray.forEach(attrName => {
- if (findObjs({type:'attribute', characterid: charId, name: `${sectionPrefix}${row}_${attrName}`}).length < 1) {
- log(`Can't find attribute: ${sectionPrefix}$${index}_${attrName}`)
- if (createMissing) {
- let x = createObj('attribute', {characterid: charId, name: `${sectionPrefix}${row}_${attrName}`, current: '', max: ''});
- rowObj[attrName] = {id: x.id, current: '', max: ''}
- }
- } else {
- let currentAttr = findObjs({type:'attribute', characterid: charId, name: `${sectionPrefix}${row}_${attrName}`})[0];
- rowObj[attrName] = {id: currentAttr.get('_id'), current: currentAttr.get('current'), max: currentAttr.get('max')}
- }
- })
- attrArray.push(rowObj);
- index ++;
- })
- //log(attrArray);
- return attrArray;
- } else {log(`invalid charId (${charId}) or repeating section name (${sectionName}), aborting...`)}
- }
- const getChar = (charRef) => {
- if (charRef.match(/^(sel|selected)$/)) {
- if (!selectedToken) {
- sendChat(scriptName, `/w ${lastWho} No token selected!`);
- return null;
- }
- let t = getObj('graphic', selectedToken._id)
- let r = (t) ? t.get('represents') : null;
- if (!r) {
- sendChat(scriptName, `/w ${lastWho} No linked character found for token: ${t.id}`)
- return null;
- }
- let char = (getObj('character', r)) ? getObj('character', r) : false;
- return char;
- }
- let char = getObj('character', charRef);
- if (char) return char;
- let chars = findObjs({type:'character', name: charRef}, {caseInsensitive: true});
- if (chars.length > 0) return chars[0];
- return false;
- }
- const handleInput = (msg) => { // !findres --char|sel --name|arrows --mod|-1 --limit|0,max
- if (msg.type === "api" && msg.content.match(/^!findres/i)) {
- lastWho = `"${msg.who.replace(/\s*\(gm\)\s*/i, '')}"`;
- selectedToken = (msg.selected) ? msg.selected[0] : null;
- let cmds = (msg.content.match(/^[^-]*(-.*)/i)) ? msg.content.match(/^[^-]*(-.*)/i)[1].split(/\s*--\s*/) : [];
- if (cmds.length) cmds.shift();
- let char, attrName, attrMod, limit=[], silent = false;
- silentMode = (state.findResource.silentMode) ? true : false;
- publicMode = (state.findResource.publicMode) ? true : false;
- cmds.forEach(c => {
- let parts = c.split(/\s*\|\s*/);
- let cmd = parts[0];
- let args = (parts.length > 1) ? parts[1] : null;
- switch(cmd) {
- case 'char':
- if (!args) return sendChat(scriptName, `/w ${lastWho} no argument supplied: ${c}`);
- char = getChar(args);
- if (char === false) return sendChat(scriptName, `/w ${lastWho} bad character ID or name.`);
- break;
- case 'name':
- if (!args) return sendChat(scriptName, `/w ${lastWho} no argument supplied: ${c}`);
- attrName = args;
- break;
- case 'mod':
- if (!args) return sendChat(scriptName, `/w ${lastWho} no argument supplied: ${c}`);
- attrMod = args;
- break;
- case 'limit':
- if (!args) return sendChat(scriptName, `/w ${lastWho} no argument supplied: ${c}`);
- limit = args.split(/\s*,\s*/);
- break;
- case 'pub':
- if (!args) publicMode = true;
- else {
- if (args.match(/(on|true)/i)) state.findResource.publicMode = true;
- else if (args.match(/(off|false)/i)) state.findResource.publicMode = false;
- else return;
- publicMode = state.findResource.publicMode;
- sendChat(scriptName, `/w ${lastWho} Public reporting is ${(state.findResource.publicMode) ? 'enabled' : 'disabled'}.`)
- }
- break;
- case 'silent':
- if (!args) silent = true;
- else {
- if (args.match(/(on|true)/i)) state.findResource.silentMode = true;
- else if (args.match(/(off|false)/i)) state.findResource.silentMode = false;
- else return;
- silentMode = state.findResource.silentMode;
- sendChat(scriptName, `/w ${lastWho} Silent mode is ${(state.findResource.silentMode) ? 'enabled' : 'disabled'}.`)
- }
- break;
- case 'sel':
- char = getChar('sel');
- if (char === false) return sendChat(scriptName, `/w ${lastWho} bad character ID or name.`);
- break;
- default:
- sendChat(scriptName, `/w ${lastWho} unrecognised command: ${c}`);
- break;
- }
- });
- if (char) {
- if (attrName && attrMod) {
- modRes(char, attrName, attrMod, limit, silent);
- } else if (attrName) {
- let target = findRes(char, attrName);
- if (target) {
- let curVal = (target.get('current') || target.get('current') == 0) ? target.get('current') : '<no value>';
- let maxVal = (target.get('max')) ? `/${target.get('max')}` : '';
- pubChat(`${char.get('name')}'s current ${attrName}: ${curVal}${maxVal}`);
- }
- } else sendChat(scriptName, `/w ${lastWho} Not enough arguments supplied to modify resource.`);
- }
- }
- };
- const style = {
- std: "color:darkblue; display:block; border:2px solid darkblue; background:white; padding:4px; font-size:14px; text-align:center; "
- }
- const silentChat = (from, msg) => {
- if (!silentMode) sendChat(from, msg);
- return;
- }
- const pubChat = (msg) => {
- let w = (publicMode) ? '' : `/w ${lastWho} `;
- sendChat(scriptName, `${w}[${msg}](#" style="${style.std})`);
- }
- const registerEventHandlers = () => {
- on('chat:message', handleInput);
- };
- on('ready', () => {
- if (!state.findResource) state.findResource = {silentMode: false, publicMode: false};
- registerEventHandlers();
- });
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement