Last active
September 30, 2022 13:44
-
-
Save fullstackfool/3a65865b66c1f7af6cd5f361358f70d6 to your computer and use it in GitHub Desktop.
AWS Amplify SNS to Discord Webhook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require('https'); | |
// NOT the full url, just the path. | |
const webhookPath = process.env.WEBHOOK_PATH; | |
// Anything you like. | |
const appName = process.env.APP_NAME; | |
function postRequest(body) { | |
const options = { | |
hostname: 'discord.com', | |
path: webhookPath, | |
method: 'POST', | |
port: 443, | |
headers: { | |
'Content-Type': 'application/json' | |
} | |
}; | |
return new Promise((resolve, reject) => { | |
const req = https.request(options, res => { | |
console.info(res); | |
}); | |
req.on('error', err => { | |
reject(new Error(err)); | |
}); | |
req.write(JSON.stringify(body)); | |
req.end(); | |
}); | |
} | |
exports.handler = async event => { | |
let msg = event.Records?.[0]?.Sns?.Message; | |
if (!msg) { | |
return { | |
statusCode: 400, | |
body: 'No parsable build message' | |
} | |
} | |
let buildStatus = msg.match(/(?<=Your build status is )(.*)(?=\. Go to)/)[0]; | |
const buildUrl = msg.match(/(?<=Go to )(.*)(?= to view)/)[0]; | |
const appUrl = msg.match(/(?<=app: )(.*)(?=\. Your build)/)[0]; | |
const branch = appUrl.match(/(?<=https:\/\/)(.*?)(?=\.)/)[0].toUpperCase(); | |
buildStatus = buildStatus === 'SUCCEED' ? 'SUCCEEDED' : buildStatus; | |
// Black - value must be in decimal. | |
let colour = '15854093'; | |
switch (buildStatus) { | |
case 'STARTED': | |
// Teal | |
colour = '3399167'; | |
break; | |
case 'SUCCEEDED': | |
// Green | |
colour = '2348367'; | |
break; | |
case 'FAILED': | |
// Red | |
colour = '16734003'; | |
break; | |
} | |
// Log to CloudWatch | |
console.info({ appUrl, buildStatus, buildUrl, colour }); | |
try { | |
const result = await postRequest({ | |
"username": "Amplify Build", | |
"avatar_url": "https://pbs.twimg.com/profile_images/1114309924551417856/FKA4cm2x_400x400.png", | |
"content": `${appName} ${branch}: BUILD ${buildStatus}`, | |
"embeds": [ | |
{ | |
"color": colour, | |
"fields": [ | |
{ | |
"name": "App Url", | |
"value": appUrl | |
}, | |
{ | |
"name": "Branch", | |
"value": branch | |
}, | |
{ | |
"name": "Build Status", | |
"value": buildStatus | |
}, | |
{ | |
"name": "Build URL", | |
"value": buildUrl | |
} | |
] | |
} | |
] | |
}); | |
console.log('Result:', result); | |
return { | |
statusCode: 200 | |
}; | |
} catch (error) { | |
console.log('Error:', error); | |
return { | |
statusCode: 400, | |
body: error.message | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Resulting discord message: