2
0
mirror of https://github.com/yagop/node-telegram-bot-api synced 2025-08-29 13:27:44 +00:00

Separated WebHook

This commit is contained in:
yago 2015-07-13 00:24:49 +02:00
parent 3573d0949d
commit 923e65c789
3 changed files with 89 additions and 78 deletions

View File

@ -1,10 +1,9 @@
var EventEmitter = require('events').EventEmitter; var TelegramBotWebHook = require('./telegramWebHook');
var debug = require('debug')('node-telegram-bot-api'); var debug = require('debug')('node-telegram-bot-api');
var EventEmitter = require('events').EventEmitter;
var Promise = require("bluebird"); var Promise = require("bluebird");
var request = require("request"); var request = require("request");
var stream = require('stream'); var stream = require('stream');
var https = require('https');
var http = require('http');
var util = require('util'); var util = require('util');
var mime = require('mime'); var mime = require('mime');
var path = require('path'); var path = require('path');
@ -42,81 +41,13 @@ var TelegramBot = function (token, options) {
} }
if (options.webHook) { if (options.webHook) {
var port = options.webHook.port || 8443; var binded = this._processUpdate.bind(this);
var key = options.webHook.key; this._WebHook = new TelegramBotWebHook(token, options.webHook, binded);
var cert = options.webHook.cert;
var host = options.webHook.host;
this._configureWebHook(port, host, key, cert);
} }
}; };
util.inherits(TelegramBot, EventEmitter); util.inherits(TelegramBot, EventEmitter);
TelegramBot.prototype._configureWebHook = function (port, host, key, cert) {
var binded = this._requestListener.bind(this);
if (key && cert) { // HTTPS Server
debug('HTTPS WebHook enabled');
var options = {
key: fs.readFileSync(key),
cert: fs.readFileSync(cert)
};
this._webServer = https.createServer(options, binded);
} else {
debug('HTTP WebHook enabled');
this._webServer = http.createServer(binded);
}
this._webServer.listen(port, host, function () {
debug("WebHook listening on port %s", port);
});
};
TelegramBot.prototype._requestListener = function (req, res) {
var self = this;
var regex = new RegExp(this.token);
debug('WebHook request URL:', req.url);
debug('WebHook request headers: %j', req.headers);
// If there isn't token on URL
if (!regex.test(req.url)) {
debug('WebHook request unauthorized');
res.statusCode = 401;
res.end();
} else if (req.method === 'POST') {
var fullBody = '';
req.on('data', function (chunk) {
fullBody += chunk.toString();
});
req.on('end', function () {
try {
debug('WebHook request fullBody', fullBody);
var data = JSON.parse(fullBody);
self._processUpdate(data);
} catch (error) {
debug(error);
}
res.end('OK');
});
} else { // Authorized but not a POST
debug('WebHook request isn\'t a POST');
res.statusCode = 418; // I'm a teabot!
res.end();
}
};
TelegramBot.prototype._processUpdate = function (update) {
if (update.message) {
this.emit('message', update.message);
}
};
TelegramBot.prototype._processUpdates = function (updates) {
for (var i = 0; i < updates.length; i++) {
this._processUpdate(updates[i]);
}
};
TelegramBot.prototype._polling = function (timeout) { TelegramBot.prototype._polling = function (timeout) {
var self = this; var self = this;
this.getUpdates(timeout).then(function (data) { this.getUpdates(timeout).then(function (data) {
@ -129,6 +60,20 @@ TelegramBot.prototype._polling = function (timeout) {
}); });
}; };
TelegramBot.prototype._processUpdate = function (update) {
debug('Process Update', update);
debug('Process Update message', update.message);
if (update.message) {
this.emit('message', update.message);
}
};
TelegramBot.prototype._processUpdates = function (updates) {
for (var i = 0; i < updates.length; i++) {
this._processUpdate(updates[i]);
}
};
TelegramBot.prototype._request = function (path, options) { TelegramBot.prototype._request = function (path, options) {
if (!this.token) { if (!this.token) {
throw new Error('Telegram Bot Token not provided!'); throw new Error('Telegram Bot Token not provided!');

66
src/telegramWebHook.js Normal file
View File

@ -0,0 +1,66 @@
var debug = require('debug')('node-telegram-bot-api');
var https = require('https');
var http = require('http');
var util = require('util');
var fs = require('fs');
var TelegramBotWebHook = function (token, options, callback) {
this.token = token;
this.callback = callback;
if (typeof options === 'boolean') {
options = {};
}
options.port = options.port || 8443;
var binded = this._requestListener.bind(this);
if (options.key && options.cert) { // HTTPS Server
debug('HTTPS WebHook enabled');
var opts = {
key: fs.readFileSync(options.key),
cert: fs.readFileSync(options.cert)
};
this._webServer = https.createServer(opts, binded);
} else {
debug('HTTP WebHook enabled');
this._webServer = http.createServer(binded);
}
this._webServer.listen(options.port, options.host, function () {
debug("WebHook listening on port %s", options.port);
});
};
TelegramBotWebHook.prototype._requestListener = function (req, res) {
var self = this;
var regex = new RegExp(this.token);
debug('WebHook request URL:', req.url);
debug('WebHook request headers: %j', req.headers);
// If there isn't token on URL
if (!regex.test(req.url)) {
debug('WebHook request unauthorized');
res.statusCode = 401;
res.end();
} else if (req.method === 'POST') {
var fullBody = '';
req.on('data', function (chunk) {
fullBody += chunk.toString();
});
req.on('end', function () {
try {
debug('WebHook request fullBody', fullBody);
var data = JSON.parse(fullBody);
self.callback(data);
} catch (error) {
debug(error);
}
res.end('OK');
});
} else { // Authorized but not a POST
debug('WebHook request isn\'t a POST');
res.statusCode = 418; // I'm a teabot!
res.end();
}
};
module.exports = TelegramBotWebHook;

View File

@ -60,7 +60,7 @@ describe('Telegram', function () {
method: 'POST' method: 'POST'
}, function (error, response, body) { }, function (error, response, body) {
response.statusCode.should.not.be.equal(200); response.statusCode.should.not.be.equal(200);
bot._webServer.close(); bot._WebHook._webServer.close();
done(); done();
}); });
}); });
@ -72,7 +72,7 @@ describe('Telegram', function () {
method: 'GET' method: 'GET'
}, function (error, response, body) { }, function (error, response, body) {
response.statusCode.should.not.be.equal(200); response.statusCode.should.not.be.equal(200);
bot._webServer.close(); bot._WebHook._webServer.close();
done(); done();
}); });
}); });
@ -80,7 +80,7 @@ describe('Telegram', function () {
it('should emit a `message` on HTTP WebHook', function (done) { it('should emit a `message` on HTTP WebHook', function (done) {
var bot = new Telegram(TOKEN, {webHook: true}); var bot = new Telegram(TOKEN, {webHook: true});
bot.on('message', function (msg) { bot.on('message', function (msg) {
bot._webServer.close(); bot._WebHook._webServer.close();
done(); done();
}); });
var url = 'http://localhost:8443/bot'+TOKEN; var url = 'http://localhost:8443/bot'+TOKEN;
@ -91,7 +91,7 @@ describe('Telegram', function () {
headers: { headers: {
"content-type": "application/json", "content-type": "application/json",
}, },
body: JSON.stringify({update_id: 0, message: {text: 'test'}}) body: {update_id: 0, message: {text: 'test'}}
}); });
}); });
@ -105,7 +105,7 @@ describe('Telegram', function () {
}; };
var bot = new Telegram(TOKEN, opts); var bot = new Telegram(TOKEN, opts);
bot.on('message', function (msg) { bot.on('message', function (msg) {
bot._webServer.close(); bot._WebHook._webServer.close();
done(); done();
}); });
var url = 'https://localhost:8443/bot'+TOKEN; var url = 'https://localhost:8443/bot'+TOKEN;