Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,7 @@ bot.postMessageToUser('user', 'hi').always(function(data) {
})
```

### HTTP Proxy Support

This package can work behind a corporate proxy when the `HTTP_PROXY` environment variable is set,
ie: `HTTP_PROXY=http://10.60.10.1:3128`
36 changes: 35 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ var Vow = require('vow');
var extend = require('extend');
var WebSocket = require('ws');
var EventEmitter = require('events').EventEmitter;
var HttpsProxyAgent = require('https-proxy-agent');
var Url = require('url');
var { setWsHeartbeat } = require('ws-heartbeat/client');

class Bot extends EventEmitter {
Expand All @@ -21,6 +23,10 @@ class Bot extends EventEmitter {
this.disconnect = params.disconnect;

console.assert(params.token, 'token must be defined');

this._configureProxy(params.proxy || undefined);

this.login();
if (!this.disconnect) {
this.login();
}
Expand Down Expand Up @@ -51,7 +57,7 @@ class Bot extends EventEmitter {
* Establish a WebSocket connection
*/
connect() {
this.ws = new WebSocket(this.wsUrl);
this.ws = new WebSocket(this.wsUrl, {agent: this._agent});

setWsHeartbeat(this.ws, '{ "kind": "ping" }');

Expand Down Expand Up @@ -499,6 +505,34 @@ class Bot extends EventEmitter {
});
});
}

/**
* Use a HTTP Proxy is supplied in the params of the custructor, otherwise look at the environment vars
* for proxy configuration. We need to accomodate both uppercase and lowercase environment definitions.
*
* @param {string} proxy
* @private
*/
_configureProxy(proxy) {
if (!proxy && ((typeof process.env['http_proxy'] !== 'undefined' && process.env['http_proxy']) || (typeof process.env['HTTP_PROXY'] !== 'undefined' && process.env['HTTP_PROXY']))) {
proxy = process.env['http_proxy'] || process.env['HTTP_PROXY'];
}

this._agent = null;
if (proxy) {
try {
// Url.parse can throw it's own errors but strangely doesn't throw when the url is not really valid.
var proxyUrl = Url.parse(process.env['http_proxy'] || process.env['HTTP_PROXY']);
if (!proxyUrl.hostname) {
throw new Error('Invalid HTTP_PROXY environment variable value');
}

this._agent = new HttpsProxyAgent(proxyUrl);
} catch (e) {
console.error(e);
}
}
}
}

module.exports = Bot;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
},
"dependencies": {
"extend": "^2.0.1",
"https-proxy-agent": "^2.1.1",
"lodash": "^4.17.2",
"request": "^2.56.0",
"vow": "^0.4.9",
Expand Down