converts a few common units between imperial and metric
/*
to set up a command for this go to https://autocode.com/tools/discord/command-builder/
command name: /convert
description: between imperial and metric units
option 1:
type: string
name: value
description: supports: mm, cm, m, km, in, ft, mi, °C, °F, kg, lb | example: 187cm
option 2:
type: string
name: to-unit
description: what unit should the output be in (optional)
*/
let metric = new RegExp(`C\\b|cm\\b|mm\\b|m\\b|km\\b|kg\\b|g\\b`); // |[unit]\\b
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const {convertMany} = require('convert');
let event = context.params.event;
let input = event.data.options[0].value.replace(',', '.');
input = input.replace('°', '');
//sanitizing input for the convert library to work correctly
input = input.replace('ft', "'");
if (input.match(`'`)){
input = parseFloat(input.split(`'`)[0]) + parseFloat(input.split(`'`)[1])/12;
input += "ft";
}
if (input.match(/lbs\b|pound/)){
input = input.replace('s', '');
input = input.replace('pound', 'lb');
}
input = input.replace(' ', '');
let style = 'imperial';
if (input.match(metric)){
style = 'metric';
}
let inAmount = convertMany(input).to('best', style).quantity;
let inUnit = convertMany(input).to('best', style).unit;
input = convertMany(input).to('best', style).toString();
console.log(input); //sanitized input gets logged
//converting
let output;
let unit = 'best'
if (event.data.options[1] != undefined){
console.log('to custom');
unit = event.data.options[1].value;
output = convertMany(input).to(unit);
}
else if (inUnit.match(metric)){
console.log('to imperial');
if (inUnit == 'm' && inAmount < 5){
unit = 'ft'
}
output = convertMany(input).to(unit, 'imperial');
if(inUnit == 'm' && inAmount < 5){
let outf = Math.floor(output);
let outi=(parseFloat(`0.${output.toFixed(3).split(`.`)[1]}`)*12).toFixed(1);
output=`${outf}'${outi}"`;
}
}
else{
console.log('to metric');
output = convertMany(input).to(unit); //default: metric
}
console.log(output);
let send;
if (output.quantity != undefined) {
output.quantity = Math.round(output.quantity * 100) / 100;
send = output.quantity + output.unit;
}
else {
if (!isNaN(output)){
output = (Math.round(output * 100000) / 100000) + event.data.options[1]?.value
}
send = output;
}
console.log("->" + send);
//send
try {
await lib.discord.interactions['@1.0.1'].responses.create({
token: `${context.params.event.token}`,
content: `${event.data.options[0].value} equals ${send}`,
response_type: 'CHANNEL_MESSAGE_WITH_SOURCE'
});
}
catch (e) {
let user;
if (event.guild_id != null) user =event.member.user.id //server
else user = event.user.id //dm
await lib.discord.channels['@0.0.6'].messages.create({
channel_id: event.channel_id,
content: `<@${user}> used /convert.\n${event.data.options[0].value} equals ${send}`,
});
console.log(e);
}