Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Created February 15, 2016 22:41
Show Gist options
  • Save brennanMKE/1f7bee9a2863c7a2433e to your computer and use it in GitHub Desktop.
Save brennanMKE/1f7bee9a2863c7a2433e to your computer and use it in GitHub Desktop.
SlackBot message posting with TypeScript
import https = require('https');
import * as Constants from './constants';
import * as qs from 'qs';
export class SlackBot {
options = {
token: '',
channel: '',
username: '',
icon_url: ''
}
constructor() {
let pkg = require('./package.json');
if (pkg.slackbot) {
this.options = pkg.slackbot;
}
}
postTextWithCode(text: string, code: string) : Promise.IThenable<JSON> {
let message = text + '\n```' + code + '```\n';
return this.postMessage(message);
}
postMessage(text: string) : Promise.IThenable<JSON> {
let p = new Promise((resolve, reject) => {
let queryString = qs.stringify({
token: this.options.token,
channel: this.options.channel,
username: this.options.username,
icon_url: this.options.icon_url,
text: text
});
let options = {
host: 'slack.com',
port: 443,
path: '/api/chat.postMessage?' + queryString,
method: 'POST'
};
let data = [];
let req = https.request(options, function(res) {
res.on('data', function(chunk) {
data.push(chunk);
});
res.on('end', () => {
try {
let text = Buffer.concat(data).toString();
var json = JSON.parse(text);
resolve(json);
}
catch (e) {
var error = new Error('Failed to handle response');
let thrownError: Error = e;
error.stack = thrownError.stack;
reject(error);
}
});
});
req.on('error', (e) => {
console.error(e);
reject(e);
})
req.end();
});
return p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment