telme/lib/flows/task_message.ts
Sagi Dayan 49c36b471f Fixes
- init/help/version does not throw an error if there is no config file
 - node_module usage - now working
2020-03-25 18:40:18 -04:00

58 lines
2.1 KiB
TypeScript

'use strict';
const { spawn } = require('child_process');
// import TelegramBot from 'node-telegram-bot-api';
import SendMessage from './send_message';
import { ITaskConfig } from '../config/config';
import { ITaskOptions } from '../utils';
import Config from '../config/config'
import InvalidCommandError from '../errors/invalid_command';
import InvalidArgumentsError from '../errors/invalid_arguments.error';
export default class TaskMessage {
static async run(config: ITaskConfig, options: ITaskOptions) {
validate(config, options);
const exec = spawn(options.command, options.args);
let errors = await promisifyExec(exec, options.command);
let msg = config.task_message_template.replace('%cmd%', ` $ ${options.command} ${options.args.join(' ')}`)
.replace('%errors%', errors);
try {
await SendMessage.send(config, msg);
} catch (e) {
errors = e.message;
console.error(`[${Config.APP_NAME}]: An error occurred. Error: ${e.message}`);
}
return true;
}
}
function validate(config: ITaskConfig, options: ITaskOptions) {
if (!config.bot_token || !config.chat_id || !config.task_message_template) throw new InvalidArgumentsError(`Config object must have bot_token<string>, chat_id<string>, task_message_template<string>`);
if (!options.command || !options.args || !Array.isArray(options.args) || typeof options.command !== 'string') throw new InvalidArgumentsError(`Option object must have command<string>, and args<string[]>`)
}
function promisifyExec(exec, command): Promise<string> {
let errors = null;
return new Promise((resolve, reject) => {
exec.stdout.on('data', (data) => {
console.log(String(data));
});
exec.on('error', (error) => {
if (error.message.indexOf('ENOENT') >= 0) {
reject(new InvalidCommandError(`Command '${command}' not found`));
}
});
exec.stderr.on('data', (data) => {
console.error(String(data));
if (!errors)
errors = data;
else
errors += `\n${data}`;
});
exec.on('close', async (code) => {
resolve(errors);
});
});
}