aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/durov.js
blob: e9bbdb9a3231339065e4bcd9b67d7b38b0a8ea76 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import TelegramBot from 'node-telegram-bot-api';
import debug from 'debug';
var log = debug('durov');
import config from 'config';


import { formatQuote, formatTitle } from './common/MessageUtils';
import { format } from '../src/utils/embed';

let sender;
let demouser;
let bot_token;
const durov_token_key = 'service.durov.token';

if (config.has(durov_token_key)) {
    bot_token = config.get(durov_token_key);
    sender = new TelegramBot(bot_token);
    demouser = config.get('service.durov.demouser');
    sender.setWebHook(`${config.get('service.baseURL')}/api/${bot_token}`).then(() => {
        log('Webhook is set');
    }).catch(console.log);
    sender.on('message', msg => {
        log(`MESSAGE: ${JSON.stringify(msg)}`);
    });
}

export const webhookPath = () => {
    return bot_token;
};

export const webhook = (req, res) => {
    sender.processUpdate(JSON.parse(req.body));
    res.sendStatus(200);
};

/**
 * @param {import('../src/api').Message} msg
 * @param {string[]} subscribers
 */
export const sendTelegramNotification = (msg, subscribers) => {
    log(`Telegram event: ${JSON.stringify(msg)}, ${subscribers} ${subscribers.length}`);
    if (!msg.service) {
        if (subscribers && subscribers.includes(demouser)) {
            const message = `${formatTitle(msg)}\n${formatQuote(msg)}\n${format(msg.body, msg.uid, false)}`;
            log(message);
            sender.sendMessage(demouser, message, {
                parse_mode: 'HTML',
                disable_web_page_preview: true
            }).then(log).catch(log);
        }
    }
};