Skip to content

Instantly share code, notes, and snippets.

@hankpillow
Last active May 19, 2020 19:57
Show Gist options
  • Save hankpillow/24b3dbfbe87c48fdff6e7f2d8149a1ae to your computer and use it in GitHub Desktop.
Save hankpillow/24b3dbfbe87c48fdff6e7f2d8149a1ae to your computer and use it in GitHub Desktop.
Lambda for Bitbucket webhook with Google Chat
var https = require('https');
var parse = require("url").parse;
exports.handler = async (data) => {
const chatURL = process.env.CHAT_URL
if (!chatURL){
return {
statusCode: 400,
body: JSON.stringify('missing google chat webhook'),
};
}
if (!data || !data.body){
return {
statusCode: 400,
body: JSON.stringify('missing body', data),
};
}
const body = JSON.parse(data.body);
const pr = body.pullrequest
console.log(body)
if (!pr){
console.log("unexpected body")
return {
statusCode: 400,
body: JSON.stringify('unexpected body format'),
};
}
const team = (pr.participants || []).map(user => {
return user.role != "REVIEWER" ? null : `- ${user.user.display_name} (approved: *${user.approved}*)`
})
const type = data.headers["X-Event-Key"];
let schema = null
switch(type){
case "pullrequest:approved":
schema = `*>> APRROVED by ${body.approval.user.display_name}*
state: *${pr.state}*
branch: *${pr.source.branch.name}*
> *${pr.author.display_name}* check if the PR is ready to be merged!
${pr.links.html.href}`
break
case "pullrequest:fulfilled":
schema = `*>> MERGED: ${pr.source.branch.name} -> ${pr.destination.branch.name}*
@all update your branch with _${pr.destination.branch.name}_ changes.`
break
case "pullrequest:created":
schema = `*+ New Pull Request: ${pr.title}*
description:
${pr.rendered.description.raw}
----
branch: *${pr.source.branch.name} -> ${pr.destination.branch.name}*
owner: *${pr.author.display_name}*
reviewers:
${team && team.length ? team.join("\n") : ''}`
break
case "pullrequest:comment_created":
schema = `*+ New Comment on:* ${pr.source.branch.name}
_${body.comment.user.display_name} says_:
${body.comment.content.raw}
---
${body.comment.links.html.href}
> *${pr.author.display_name.trim()}* check if you have actions to take!`
break
default:
schema = "unexpected type:" + type
break
}
const postData = JSON.stringify({'text': schema.replace(/^\s*\n/gm,'').trim()});
return await new Promise((resolve, reject)=>{
const uri = parse(chatURL)
uri.method = "POST"
const request = https.request(uri, (res) => {
res.setEncoding('utf8');
let resp
res.on('data', (chunk) => { resp = chunk});
res.on('end', () => { resolve(resp)});
});
request.on('error', (e) => { reject(`problem with request: ${e.message}`)});
request.write(postData);
request.end();
})
.then(result => {
return {
statusCode: 200,
body: result,
};
})
.catch(err => {
return {
statusCode: 400,
body: err,
};
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment