'use strict'; const { spawn } = require('child_process'); // import TelegramBot from 'node-telegram-bot-api'; import SendMessage from './send_message'; import { IProfileConfig } from '../config/config'; import { ITaskOptions } from '../utils'; import Config from '../config/config' import InvalidCommandError from '../errors/invalid_command'; export default class TaskMessage { static async run(config: IProfileConfig, options: ITaskOptions) { 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 promisifyExec(exec, command): Promise { 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); }); }); }