Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@veob
Forked from imdkbj/setwebhook.js
Created January 30, 2020 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veob/b6353e6309e2e4477f934d6118865df7 to your computer and use it in GitHub Desktop.
Save veob/b6353e6309e2e4477f934d6118865df7 to your computer and use it in GitHub Desktop.
Setup to listen telegram multiple bots on webhooks.
const axios = require('axios');
const apiurl = 'https://api.telegram.org/bot';
const serveraddress = 'https://yourdomain.com';
const tokens = ['3445345345:454545-iY_wE6wj_aKDJwKLXk', '453454545:gffgfgzbcfjhsdbflhjdsfvhjlvdsf'];
//set webhook
//you can make this as call as way you want.
webhookURL(tokens, 50, 8443, 'tgram');
async function webhookURL(bot_tokens, max_connections, port, from) {
const requests = bot_tokens.map((token) => {
const webhook_url = `${apiurl}${token}/setwebhook?max_connections=${max_connections}&url=${serveraddress}:${port}?${from}=bot${token}`;
return setWebhook(webhook_url)
.catch(err => {
console.log('first error', err);
});
})
await Promise.all(requests)
.then(response => {
console.log(response);
})
.catch(e => {
console.log('all error', e);
})
}
function setWebhook(webhook_url) {
return new Promise(function(resolve, reject) {
axios.post(webhook_url)
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error.data);
});
})
}
var fs = require('fs');
var https = require('https');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
const TelegramBot = require('node-telegram-bot-api');
//ssl details
//i have copied the cert details from the cpanel.
var privateKey = fs.readFileSync('./ssl/mycert.key', 'utf8');
var certificate = fs.readFileSync('./ssl/mycert.crt', 'utf8');
var caCerts = [
fs.readFileSync('./ssl/CA_root.crt'),
fs.readFileSync('./ssl/ca_bundle_certificate.crt')
];
var credentials = {
key: privateKey,
cert: certificate,
ca: caCerts
};
//port to listen
var port = process.env.PORT || 8443;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.sendStatus(200);
//console.log(req);
var query = req.originalUrl.split('=');
//get bot token from the webhook
var token = query[1].substring(3);
//get webhook from
var from = query[0].substring(2);
//body of the message.
var msg = req.body;
console.log(msg);
var telegram_id = msg.message.chat.id;
switch (from) {
case ('tgram'):
const bot = new TelegramBot(token);
bot.sendMessage(telegram_id, 'You are live on webhook.')
break;
default:
console.log('Webhook response from unknown source', msg);
}
})
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(port, function() {
console.log('Webhook server started on: ' + port)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment