Skip to content

Instantly share code, notes, and snippets.

@paramsen
Created April 29, 2019 12:05
Show Gist options
  • Save paramsen/04cec22706d0531e0dcf6c2a12988512 to your computer and use it in GitHub Desktop.
Save paramsen/04cec22706d0531e0dcf6c2a12988512 to your computer and use it in GitHub Desktop.
Slack bot who triggers Bitrise, using Google Cloud Function as a messenger
const rp = require('request-promise-native')
const slackToken = '<SLACK TOKEN>'
const bitriseToken = '<BITRISE API TOKEN>'
const baseBitriseData = {
hook_info: {
type: 'bitrise',
build_trigger_token: bitriseToken
},
build_params: {
branch: 'none',
workflow_id: 'none'
},
triggered_by: 'Slack'
}
const baseBitriseRequest = {
method: 'POST',
uri: 'https://app.bitrise.io/app/<BITRISE APP ID>/build/start.json',
body: 'none',
json: true
}
function validate(req) {
if (req.method !== 'POST') {
const error = new Error('Only POST requests are accepted')
error.code = 405
throw error
}
const body = req.body
// Verify that this request came from Slack
if (!body || body.token !== slackToken) {
const error = new Error('Nope')
error.code = 401
throw error
}
if (!(body.text && /^[A-Za-z0-9._+-]+$/g.exec(body.text))) {
const error = new Error('Nope')
error.code = 400
throw error
}
}
exports.bitrisebuild = (req, res) => {
return Promise.resolve()
.then(() => {
validate(req)
const buildId = req.body.text
const bitriseData = baseBitriseData
const bitriseRequest = baseBitriseRequest
bitriseData.build_params.branch = buildId
bitriseData.build_params.workflow_id = buildId
bitriseRequest.body = bitriseData
return rp(bitriseRequest).catch(err => {
console.error(err)
const error = new Error('Build id not OK')
error.code = 400
return Promise.reject(error)
})
})
.then(() => {
res.send('Building!')
})
.catch(err => {
console.error(err)
res.status(err.code || 500).send(err)
return Promise.reject(err)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment