diff --git a/README.md b/README.md index 9fbce07..4e94c34 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ const bot = new TeleBot({ proxy: 'http://username:password@yourproxy.com:8080' // Optional. An HTTP proxy to be used. }, webhook: { // Optional. Use webhook instead of polling. + createServer: true, //Optional. Specifies whether httpServer or httpsServer instance should be created or not. Defaults to true. When set to false, bot.start() returns a promise which resolves with a listener function to be attached to the server manually. key: 'key.pem', // Optional. Private key for server. cert: 'cert.pem', // Optional. Public key. url: 'https://....', // HTTPS url to send updates to. @@ -313,7 +314,7 @@ Creates inlineKeyboard object for answerList articles. ##### `start()` -Start polling updates. +Start polling updates. If createServer is set to false in webhook options, then the method returns a promise resolving to a listener function suitable for usage with httpServer/httpsServer createServer method. ##### `stop()` diff --git a/examples/webhook-custom-http-server.js b/examples/webhook-custom-http-server.js new file mode 100644 index 0000000..1f5d918 --- /dev/null +++ b/examples/webhook-custom-http-server.js @@ -0,0 +1,16 @@ +const TeleBot = require('../'); + +const bot = new TeleBot({ + token: 'TELEGRAM_BOT_TOKEN', + webhook: { + createServer: false, + url: 'https://....' + } +}); + +bot.on('text', msg => bot.sendMessage(msg.from.id, msg.text)); + +bot.start().then(listener => { + const server = http.createServer(listener); + server.listen(3200, '0.0.0.0'); +}); diff --git a/lib/webhook.js b/lib/webhook.js index 2819e51..c48c52e 100644 --- a/lib/webhook.js +++ b/lib/webhook.js @@ -12,18 +12,24 @@ module.exports = (bot, opt) => { const path = url.parse(opt.url).pathname; const key = opt.key && fs.readFileSync(opt.key); const cert = opt.cert && fs.readFileSync(opt.cert); - - // Create server - const server = key && cert ? - https.createServer({key, cert}, listener) : - http.createServer(listener); - - // Start server - server.listen(port, host, () => { - if (bot.logging) { - console.log(`[bot.webhook] started${ key ? ' secure' : ''} server on "${ host }:${ port }"`); - } - }); + const createServer = opt.createServer === false ? false : true; + + if (createServer) { + // Create server + const server = key && cert ? + https.createServer({key, cert}, listener) : + http.createServer(listener); + + // Start server + server.listen(port, host, () => { + if (bot.logging) { + console.log(`[bot.webhook] started${ key ? ' secure' : ''} server on "${ host }:${ port }"`); + } + }); + }else{ + // Server will be created by consumer, just return the listener + return listener; + } // Request listener function listener(req, res) {