Skip to content

Instantly share code, notes, and snippets.

@9bic
Created April 24, 2015 02:30
Show Gist options
  • Save 9bic/07c5cc7bf27d7926edf6 to your computer and use it in GitHub Desktop.
Save 9bic/07c5cc7bf27d7926edf6 to your computer and use it in GitHub Desktop.
Backlog Webhookで受け取った更新をTypetalkに流す
var http = require('http');
var https = require('https');
var fs = require('fs');
var queryString = require('querystring');
// configs
var enableHttps = true;
var port = {
http: 8080,
https: 8443
};
var files = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
var backlog = {
space : 'ENTER your backlog space',
getHost : function() {return 'https://' + backlog.space + ".backlog.jp";}
};
var typetalk = {
host : 'typetalk.in',
token : 'ENTER your backlog bot token',
topicId : 0 // ENTER YOUR TYPETALK TOPICID
};
// create server
if (enableHttps) {
https.createServer(onReceive).listen(port.https);
console.log('start server on port ' + port.https);
} else {
http.createServer(onReceive).listen(port.http);
console.log('start server on port ' + port.http);
}
// callback function
function onReceive(req, res) {
var body = '', type, content, json, message;
req.setEncoding('utf8');
if (req.method == 'POST') {
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
var json = JSON.parse(body);
type = json.type;
message = createMessage(type, json);
postTypetalk(message);
});
}
res.writeHead(200, 'text/plain');
}
// parse backlog "Recent Updates" and create message
function createMessage(type, json) {
var message, content, project;
content = json.content;
project = json.project;
user = json.createdUser;
url = backlog.getHost() + '/view/' + project.projectKey + '-' + project.id
// more details, https://developer.nulab-inc.com/docs/backlog/api/2/get-activities
switch(type) {
case 1:
message = "Issue created : " + content.summary + " [" + url + "]" + " by " + user.name;
break;
case 2:
message = "Issue updated : " + content.summary + " [" + url + "]" + " by " + user.name;
break;
}
return message;
}
// send to typetalk
// https://developer.nulab-inc.com/ja/docs/typetalk/samples#tt_node
function postTypetalk(message) {
var options, req, postData;
options = {
hostname: typetalk.host,
path: '/api/v1/topics/' + typetalk.topicId,
method: 'POST',
headers: {
'X-Typetalk-Token' : typetalk.token,
'Content-Type' : 'application/x-www-form-urlencoded'
}
};
req = https.request(options, function(res) {
res.on('data', function(data) {
console.log('[res: ' + res.statusCode + '] ' + data);
});
req.on('error', function(e) {
console.log('[err: ' + res.statusCode + '] ' + e.mesage);
});
});
postData = queryString.stringify({'message' : message});
req.write(postData);
req.end();
}
// global error handler
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment