Skip to content

Instantly share code, notes, and snippets.

@m2wasabi
Last active July 4, 2020 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m2wasabi/a334aff1e59f97e14b820950b7cded4f to your computer and use it in GitHub Desktop.
Save m2wasabi/a334aff1e59f97e14b820950b7cded4f to your computer and use it in GitHub Desktop.
Google Cloud Functions で SendGridの Inbound Parse Webhook を受けて Discordに投げる

SendGrid - Discord

Relay SendGrid Inbound Parse Webhook to Discord

Environment Variables

Key Description
WEBHOOK_DISCORD Discord Webhook URL
const fetch = require('node-fetch');
const htmlToText = require('html-to-text');
const Busboy = require('busboy');
// const inspect = require('util').inspect;
const webhookUrl = process.env.WEBHOOK_DISCORD;
function create_message(fields){
message = "From: "+ fields.from + "\n"
+ "To: "+ fields.to + "\n"
+ "Subject: "+ fields.subject + "\n"
+ "Body: "+ (fields.text || htmlToText.fromString(fields.html)) + "\n";
return message
}
async function send_message(fields){
const url = webhookUrl;
const body = {
content: create_message(fields)
};
const options = {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
};
return await fetch(url, options);
}
/**
* HTTP Cloud Function that makes an HTTP request
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.makeRequest = async (req, res) => {
if (req.method != 'POST') return res.sendStatus(405); // method not allowed
// console.log("Mail coming");
var fields = {};
var busboy = new Busboy({ headers: req.headers });
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
// console.log('Field [' + fieldname + ']: value: ' + inspect(val));
fields[fieldname] = val;
});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
// console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
// console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
// console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('finish', async () => {
// console.log('Done parsing form!');
const externalRes = await send_message(fields);
res.sendStatus(externalRes.ok ? 200 : 500);
});
busboy.end(req.rawBody);
};
{
"name": "sendgrid-discode",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npx @google-cloud/functions-framework --target=makeRequest"
},
"author": "m2wasabi@gmail.com",
"license": "MIT",
"dependencies": {
"busboy": "^0.3.1",
"html-to-text": "^5.1.1",
"node-fetch": "^2.6.0"
},
"devDependencies": {
"@google-cloud/functions-framework": "^1.6.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment