feat: If a required argument is not supplied, ask for it and then resolve the command listener.

Thanks to @amovah for his contributions
This commit is contained in:
Mahdi Dibaiee
2015-07-09 15:46:27 +04:30
parent 2aaed21195
commit 41ca326173
5 changed files with 162 additions and 107 deletions

View File

@ -6,6 +6,7 @@ const ESCAPABLE = '.^$*+?()[{\\|}]'.split('');
const REQUIRED = 0;
const OPTIONAL = 1;
const REST = 2;
/**
* Parses a message for arguments, based on format
@ -39,8 +40,7 @@ export default function argumentParser(format, string) {
string = string.replace(/[^\s]+/, '').trim();
format = format.replace(/[^\s]+/, '').trim();
if (!format)
return {args: {}, params: {}};
if (!format) return {args: {}, params: {}};
let indexes = [],
params = {};
@ -60,6 +60,7 @@ export default function argumentParser(format, string) {
});
format = format.replace(FORMAT_REST, (full, arg, offset) => {
indexes.push({offset, arg});
params[arg] = REST;
return getFormat(null, 'rest');
});

View File

@ -13,6 +13,9 @@ const DEFAULTS = {
}
};
const REQUIRED = 0;
const OPTIONAL = 1;
/**
* Bot class used to connect to a new bot
* Bots have an api property which gives access to all Telegram API methods,
@ -165,40 +168,43 @@ export default class Bot extends EventEmitter {
return;
}
if (ev.parse) {
let {params, args} = ev.parse(res.message.text);
if (!Object.keys(params).length) {
if (!ev.parse) {
ev.listener(res.message);
return;
}
let {params, args} = ev.parse(res.message.text);
const requiredParams = Object.keys(params).filter(param => {
return params[param] === REQUIRED;
});
if (!requiredParams.length) {
ev.listener(res.message);
return;
}
const bot = this;
function* getAnswer() {
for (let param of requiredParams) {
const msg = new Message().to(res.message.chat.id)
.text(`Enter value for ${param}`);
yield bot.send(msg).then(answer => {
args[param] = answer.text;
});
}
}
const iterator = getAnswer();
(function loop() {
const next = iterator.next();
if (next.done) {
ev.listener(res.message);
return;
}
var bot = this;
function ask(param) {
if (!args[param]) {
bot.send(new Message().text(`Enter value for ${param}`).to(res.message.chat.id))
.then(answer => {
args[param] = answer.text;
iter.next();
});
}
}
function* gen(par) {
let index = 0;
while (index < par.length) {
while (args[par[index]] && index < par.length) index++;
yield ask(par[index]);
index++;
if (index == par.length) {
res.message.args = args;
ev.listener(res.message);
return;
}
}
}
var iter = gen(Object.keys(params));
iter.next();
} else {
ev.listener(res.message);
}
next.value.then(loop);
}());
});
}
}