@twitchfy/chatbot
Version:
A powerful node module to make your own Twitch ChatBot
94 lines (93 loc) • 3.92 kB
JavaScript
;
/* eslint-disable @typescript-eslint/ban-ts-comment */
Object.defineProperty(exports, "__esModule", { value: true });
exports.optionsParser = void 0;
const structures_1 = require("../structures");
/**
* Parses the options of a command.
* @param chatbot The current instance of the chatbot.
* @param content The content of the message.
* @param options The options of the command.
* @param data The data of the message.
* @param operator The operator of the command.
* @returns The parsed options.
* @internal
*/
function optionsParser(chatbot, content, options, data, operator) {
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const args = {};
let lastOption = null;
const regex = new RegExp(`(${escapeRegExp(operator)}[^${escapeRegExp(operator)}\\s]+(?:\\s(?:[^\\s${escapeRegExp(operator)}]+\\s?)+)?)`, 'g');
let match;
while ((match = regex.exec(content)) !== null) {
const arg = match[1];
const [key, ...values] = arg.split(/\s+/);
const value = values.join(' ').trim();
const optionKey = key.slice(1);
if (optionKey in options || Object.keys(args).some((existingKey) => optionKey.startsWith(existingKey))) {
if (options[optionKey].type === 'boolean' && value === '') {
// @ts-expect-error
args[optionKey] = true;
}
else {
// @ts-expect-error
args[optionKey] = value !== '' ? value : null;
lastOption = optionKey;
}
}
else if (lastOption) {
args[lastOption] += ` ${key}`;
}
}
for (const i of Object.keys(options)) {
if (((typeof options[i].defaultValue === 'boolean' && options[i].type === 'boolean') || options[i].defaultValue) && !args[i]) {
// @ts-expect-error
args[i] = options[i].defaultValue;
continue;
}
else if (!args[i]) {
// @ts-expect-error
args[i] = null;
continue;
}
switch (options[i].type) {
// @ts-expect-error
case 'number':
args[i] = Number(args[i]);
break;
// @ts-expect-error
case 'boolean':
args[i] = typeof args[i] === 'boolean' ? args[i] : args[i] === 'true' ? true : args[i] === 'false' ? false : null;
break;
case 'mention':
{
if (options[i].grouped) {
const mentions = new structures_1.Collection();
for (const possibleMention of args[i].split(' ')) {
const mention = data.message.fragments.find((x) => x.type === 'mention' && x.content === possibleMention)?.mention;
if (!mention)
continue;
mentions.set(mention.user.id, new structures_1.BaseUser(chatbot, { ...mention.user, display_name: mention.user.displayName }));
}
// @ts-expect-error
args[i] = mentions.size ? mentions : null;
}
else {
const mention = data.message.fragments.find((x) => x.type === 'mention' && x.content === args[i])?.mention;
if (!mention) {
// @ts-expect-error
args[i] = null;
continue;
}
// @ts-expect-error
args[i] = new structures_1.BaseUser(chatbot, { ...mention.user, display_name: mention.user.displayName });
}
}
break;
}
}
return args;
}
exports.optionsParser = optionsParser;