-
Notifications
You must be signed in to change notification settings - Fork 0
/
local.js
68 lines (57 loc) · 1.7 KB
/
local.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* eslint-disable import/no-extraneous-dependencies */
const ngrok = require('ngrok');
const axios = require('axios');
const express = require('express');
const parser = require('claudia-bot-builder/lib/telegram/parse');
const responder = require('claudia-bot-builder/lib/telegram/reply');
const config = require('./src/configs/global.config');
const {
models: {
sequelize,
},
} = require('./src/database');
const handlers = require('./src/features');
const port = 3000;
const webhookPath = '/webhook';
const token = config.TELEGRAM_TOKEN;
if (!token) {
throw new Error('Cannot find TELEGRAM_TOKEN in your environments');
}
sequelize
.authenticate()
.then(() => {
// eslint-disable-next-line no-console
console.log('Connection has been established successfully.');
})
.catch((err) => {
// eslint-disable-next-line no-console
console.error('Unable to connect to the database:', err);
});
// eslint-disable-next-line func-names
const telegramConnect = async () => {
try {
const url = await ngrok.connect(port);
await axios({
method: 'GET',
url: `https://api.telegram.org/bot${token}/setWebhook?url=${url}${webhookPath}`,
});
} catch (err) {
throw new Error(`Cannot setup webhook, reason: ${err.message}`);
}
};
telegramConnect();
const app = express();
app.use(express.json());
app.post(webhookPath, async (req, res) => {
const parsedMessage = parser(req.body);
const botResponse = await handlers(parsedMessage);
try {
if (botResponse) {
await responder(parsedMessage, botResponse, token);
}
} catch (e) {
console.log(e);
}
res.sendStatus(200);
});
app.listen(port, () => process.stdout.write(`Server started at port ${port}\n`));