telme/lib/flows/init.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

108 lines
3.6 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
import * as TelegramBot from 'node-telegram-bot-api';
import { IInitProfileOptions } from '../utils';
import Telme from '../telme';
import Config, { IConfig } from '../config/config';
export default class Init {
static async init(options: IInitProfileOptions = null) {
const profileName = options.profileName || 'default';
let currentConfig: IConfig;
try {
currentConfig = await Config.getFullConfig();
if (currentConfig.profiles[profileName]) {
// This will override existing profile
const response = await prompt(`Do you wish to override you current '${profileName}' profile [y/n]? `);
if (response[0].toLowerCase() !== 'y') {
console.log('Aborting.');
process.exit(1);
}
} else {
currentConfig.profiles[profileName] = Config.generateProfileTemplate();
}
} catch (e) {
currentConfig = {
version: Config.CURRENT_CONFIG_VERSION,
profiles: {
[profileName]: Config.generateProfileTemplate()
}
}
}
console.log(`Initializing '${profileName}' profile...`);
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 chatId = await listenToMessage(bot, code);
currentConfig.profiles[profileName].bot_token = token;
currentConfig.profiles[profileName].chat_id = chatId;
console.log('Cool, Got the chat. Saving config...');
await Config.writeConfigToFile(currentConfig);
const profileFlag = profileName === 'default' ? '' : `-p ${profileName}`;
await Telme.sendMessage(currentConfig.profiles[profileName],
`*Thanks!*\nYou are all set.\ntelme usage:\n\`\`\`\n
$ ${Config.APP_NAME} ${profileFlag} --m "message to send"
$ ${Config.APP_NAME} ${profileFlag} <command> <args>
\n\`\`\`\nFor more info, visit: [telme repo](https://gitlab.com/sagidayan/telme)\n\n_Enjoy!_`
);
return true;
} catch (e) {
throw e;
}
}
}
function listenToMessage(bot, code): Promise<string> {
console.log(`
✅ Thanks! Please send '/code ${code}' to your bot from telegram.
You can send a direct message to the bot OR send this message to a group that this bot is a member of.
Keep in mind that '${Config.APP_NAME}' will send messages to the chat of your choosing.
`);
return new Promise((resolve, reject) => {
const now = Date.now();
bot.on('message', msg => {
const msgDate = 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): Promise<string> {
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());
});
});
}