-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
180 lines (156 loc) · 5.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"use strict"
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const storage = require('./storage.js');
const { token } = require('./config.json');
const units = require('./units.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
/* Run command */
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
console.log(interaction)
if (interaction.commandName == "convert") {
var response = storage.retrieve(interaction.guildId, interaction.channelId);
if (response) {
interaction.reply({content: response});
} else {
interaction.reply({content: "No recent unit conversions.", ephemeral: true})
}
}
});
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
client.on(Events.MessageCreate , (message) => {
console.log(JSON.stringify(message))
var conversions = []
if (!message.author.bot) {
// Regex: '[0-9]+\s*' plus unit plus '\b'.
units.forEach((currUnitType) => {
conversions = conversions.concat(createConversions(message.content, currUnitType.unitsSI, getImperial));
conversions = conversions.concat(createConversions(message.content, currUnitType.unitsImperial, getMetric));
});
}
if (conversions.length != 0) {
storage.set(message.guildId, message.channelId, conversions.join("\n"));
}
})
function createConversions(messageText, unitList, conversionFunction) {
var conversions = [];
unitList.forEach((unit) => {
var matches = [];
matches = matches.concat(Array.from(messageText.matchAll("\\d+\\.?\\d*\\s*" + unit.name + "\\b")));
unit.alternate.forEach((altName) => {
matches = matches.concat(Array.from(messageText.matchAll("\\d+\\.?\\d*\\s*" + altName + "\\b")));
});
if (matches.length > 0) {
matches.forEach((match) => {
conversions.push(match[0] + " is "
+ conversionFunction(parseFloat(match[0]), unit.name));
});
}
});
return conversions;
}
/*
* Converts a given imperial value to metric.
* Arguments:
* value (int): The value to be converted
* oldUnit (str): Name of imperial unit to be converted
* Returns:
* (str): Converted value w/ units
*/
function getMetric(value, oldUnit) {
var baseValue = 0;
var unitTypeIndex = -1;
units.forEach((unitType, i) => {
unitType.unitsImperial.forEach((currUnit) => {
if (currUnit.name == oldUnit) {
unitTypeIndex = i;
baseValue = value * currUnit.conversionFactor;
}
});
});
// Generate unit options
var outputUnits = [];
units[unitTypeIndex].unitsSI.forEach((candidate) => {
if (candidate.target) {
outputUnits.push({"name": candidate.name, "value": baseValue/candidate.conversionFactor});
}
});
// Now sort, by distance to the value 70 to find most appropriate conversion.
outputUnits.sort((a, b) => {
return Math.abs(20 - a.value) - Math.abs(20 - b.value)
});
console.log(outputUnits);
return Math.round(100*outputUnits[0].value)/100 + " " + outputUnits[0].name;
}
/*
* Converts given metric unit to imperial.
* Arguments:
* value (int): The value to be converted
* oldUnit (str): Name of metric unit.
* Returns:
* (str): Converted value w/ units.
*/
function getImperial(value, oldUnit) {
var baseValue = convertToBaseSI(value, oldUnit);
// Get type of unit
var unitTypeIndex = -1;
units.forEach((unitType, i) => {
unitType.unitsSI.forEach((currUnit) => {
if (currUnit.name == oldUnit) {
unitTypeIndex = i;
}
});
});
if (unitTypeIndex == -1) {
throw "Invalid unit."
}
// Generate unit options
var outputUnits = [];
units[unitTypeIndex].unitsImperial.forEach((candidate) => {
if (candidate.target) {
outputUnits.push({"name": candidate.name, "value": baseValue/candidate.conversionFactor});
}
});
// Now sort, by distance to the value 70 to find most appropriate conversion.
outputUnits.sort((a, b) => {
return Math.abs(20 - a.value) - Math.abs(20 - b.value)
});
console.log(outputUnits);
// Return first value.
var toReturn = "";
if (outputUnits[0].value < 0.01) {
// don't try to round bc it's so small!
toReturn += outputUnits[0].value;
} else {
toReturn += Math.round(100*outputUnits[0].value)/100;
}
toReturn += " " + outputUnits[0].name;
return toReturn
}
/*
* Converts an SI value to its base value.
* Arguments:
* value (int): the value to convert
* oldUnit (str): the name of the SI unit being converted
* Returns:
* Converted value (no units) - base value for this unit type.
*/
function convertToBaseSI(value, oldUnit) {
for (const currUnitType of units) {
for (const currSI of currUnitType.unitsSI) {
if (currSI.name == oldUnit) {
console.log(value, oldUnit, "=>", value*currSI.conversionFactor);
return value*currSI.conversionFactor;
}
}
}
throw "Invalid unit."
}
// Login to Discord with your client's token
client.login(token);