Skip to content

Instantly share code, notes, and snippets.

@gdiggs
Created August 5, 2016 17:56
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 gdiggs/55f29c5627badb759824b1efae3344c4 to your computer and use it in GitHub Desktop.
Save gdiggs/55f29c5627badb759824b1efae3344c4 to your computer and use it in GitHub Desktop.
What should I listen to? Lambda
process.env.NODE_CONFIG_DIR = "/var/task/config";
const https = require("https")
, queryString = require("querystring");
// Twilio Credentials
const accountSid = ""
, authToken = ""
, fromNumber = ""
, toNumber = "";
const getRecord = function(callback) {
const url = "https://rayons.info/items/random.json";
https.get(url, function(res){
var body = "";
res.on("data", function(chunk) {
body += chunk;
});
res.on("end", function(){
var item = JSON.parse(body);
const itemURL = `https://rayons.info/items/${item.id}`;
callback(`You should listen to "${item.title}" by ${item.artist}: ${itemURL}`);
});
}).on("error", function(e){
console.log("Got an error: ", e);
callback(null)
});
};
// Based on https://gist.github.com/stevebowman/7cff9dd80b227c899728
const sendSMS = function(message, callback) {
const text = {
To: toNumber,
From: fromNumber,
Body: message
};
const messageString = queryString.stringify(text);
const options = {
host: "api.twilio.com",
port: 443,
path: "/2010-04-01/Accounts/" + accountSid + "/Messages.json",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(messageString),
"Authorization": "Basic " + new Buffer(accountSid + ":" + authToken).toString("base64")
}
};
// Setup the HTTP request
var req = https.request(options, function (res) {
res.setEncoding("utf-8");
// Collect response data as it comes back.
var responseString = "";
res.on("data", function (data) {
responseString += data;
});
// Log the responce received from Twilio.
// Or could use JSON.parse(responseString) here to get at individual properties.
res.on("end", function () {
console.log("Twilio Response: " + responseString);
callback("API request sent successfully.");
});
});
// Handler for HTTP request errors.
req.on("error", function (e) {
console.error("HTTP error: " + e.message);
callback("API request completed with error(s).");
});
console.log("Twilio API call: " + messageString);
req.write(messageString);
req.end();
};
exports.handler = function (event, context) {
getRecord(function(message) {
if (message) {
sendSMS(message, function(status) {
context.done(null, status);
});
} else {
context.done();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment