'use strict'; const TelegramBot = require('node-telegram-bot-api'); const HOME = require('os').homedir(); const CONFIG_FILE_NAME = '.telmeconfig'; const FILEPATH = `${HOME}/${CONFIG_FILE_NAME}`; const APP_NAME = 'telme'; const fs = require('fs'); class Init { static async init() { console.log( 'Hi, In order for telme to work you will need to create a bot. If you don\'t know how, Please take a look at README.md'); const token = await prompt('Please provide your bot token: '); const code = generateCode(); try { const bot = new TelegramBot(token, {polling: true}); const userId = await listenToMessage(bot, code); console.log('Cool, Got your userId. Saving config...'); const _default = { TOKEN: token, USER_ID: userId, DONE_MESSAGE: '*Task:*\n\n```sh\n%cmd%\n```\nHas finished.\n*Errors*:\n %errors%' }; await bot.sendMessage( userId, `*Thanks!*\nYou are all set.\ntelme usage:\n\`\`\`\n $ ${APP_NAME} --m "message to send" $ ${APP_NAME} \n\`\`\`\nFor more info, visit: [telme repo](https://git.sagidayan.com/sagi/telme)\n\n_Enjoy!_`, {parse_mode: 'Markdown'}); fs.writeFileSync(FILEPATH, JSON.stringify(_default, null, 2)); console.log(`created config file at ${FILEPATH}`); return true; } catch (e) { throw e; } } } function listenToMessage(bot, code) { console.log(`Thanks! Please send '/code ${code}' to your bot from telegram`); return new Promise((resolve, reject) => { const now = Date.now(); bot.on('message', msg => { const msgDate = new Date(msg.date * 1000); if (msgDate < now) return; const userId = msg.chat.id; if (msg.text.indexOf('/code') === 0) { const receivedCode = msg.text.split('/code')[1].trim(); if (code === receivedCode) resolve(userId); else reject(new Error('Code does not match!')); } }); bot.on('polling_error', () => { console.log('polling error'); reject(new Error('Invalid token')); }) }); } function generateCode(codeLength = 6) { const allowedChars = 'aAbBcCdDEeFf0123456789'; let code = ''; for (let i = 0; i < codeLength; i++) { code += allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)); } return code; } function prompt(question) { return new Promise(resolve => { var stdin = process.stdin, stdout = process.stdout; stdin.resume(); stdout.write(question); stdin.once('data', function(data) { resolve(data.toString().trim()); }); }); } module.exports = Init