The way to connect Bitbucket to Slack


I wrote the code to push notification to Slack when someone create an issue, when someone created a comment, etc. in Bitbucket.

Story

The mechanism to send notification to Slack when some action is taken in Bitbucket, is prepared in Bitbucket, called webhooks. It can be turned on in each project setting page.

In Slack, we can connect to Bitbucket easily in setting page. But Slack can only receive push notification of Bitbucket, can’t receive comment or issue notification, at that time ().

I want to be notified issue and comment creation rather than push action, and created such code in Google Apps Script.

Code

Copy the following script to Google Apps Script, and deploy as web app, which is in “publish” menu. Then, it’s url would be shown and set it as webhook url in Bitbucket console panel.

Bitbucket で何らかの操作が行われるたびに Google Apps Script の処理が実行され、 Slack に 投稿されるようになります。

If I had had time, I would’ve create object model and factory, etc. But in real, the code is not so clean.

(And I put the code to Github Bitbucket To Slack Gas. Contribution is welcomed.)

First, Bitbucket send post request to the app and doPost will be executed. Then, it creates message to post to Slack in createSlackMessage function, from the data posted.

After that, it posts to Slack.

Caution

createSlackMessage では、 Issue の場合、 Pull Request の場合などパターン分けしていますが、 上で分けてある以上に 細かくパターンが分かれます。 今回は私の業務上必要だろうと思われる分岐にとどめています。 そのパターンを正確に判断するには Bitbucket から送信されるヘッダの中を確認するのがいいのですが、 Google Apps Script ではリクエストヘッダを確認することができないため ペイロード部分のデータで分岐を行っています。

実際のところ Pull Requestapproved のあたりはまだ検証中のため、 正しく判別できているという保証がないです。

If you can use Heroku or AWS or other hosting service, it would be good to create in PHP, Ruby, etc. which can handle request header.