Answer the question
In order to leave comments, you need to log in
What is the best way to save command parameters?
I am writing a bot, users send a command with parameters.
It looks something like this:
var text = '#перевести Лёша 100'
text = text.split('#')
text.shift()
text = text[0].split(' ')
console.log(text);
[ 'translate', 'Lesha', '100' ]
Answer the question
In order to leave comments, you need to log in
set a description for each command
const commands = [{
name: 'transfer',
value: /#перевести/i,
separator: / /,
params: ['name', 'count']
}, /* ... */];
const parse = (msg) => {
const command = commands.find((item) => (msg.match(item.value) || {}).index === 0);
if (!command) {
return null;
}
const args = msg.split(command.separator).slice(1);
return {
name: command.name,
params: command.params.reduce((acc, curr, i) => ({...acc, [curr]: args[i] || null}), {})
};
};
parse('#перевести Лёша 100');
/*
{
name: 'transfer',
params: {
name: 'Лёша',
count: '100'
}
}
*/
It can be stored in a similar object:
{
command: "перевести",
params: ["Лёша", 100]
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question