Created
September 26, 2016 00:49
-
-
Save hassansin/5e95ed1eb30e16ca966d0ee66873569e to your computer and use it in GitHub Desktop.
Send Joke with AWS SNS
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
#!/usr/bin/env node | |
/** | |
* Send a Joke to your mobile using AWS SNS service | |
* Usage: | |
* ./send.js phoneNumber [firstName] [lastName] | |
* | |
*/ | |
const http = require('http'); | |
const parse = require('url').parse; | |
const querystring = require('querystring'); | |
const aws2 = require('aws2'); | |
const AWS_REGION = 'us-west-2'; | |
const AWS_ACCESS_KEY = ''; | |
const AWS_SECRET_KEY = ''; | |
const getName = () => { | |
return Promise.resolve({ | |
firstName: process.argv[3] || 'Chuck', | |
lastName: process.argv[4] || 'Norris' | |
}); | |
} | |
const request = (options) => { | |
options.body = options.body || ''; | |
//console.log(options); | |
return new Promise((resolve, reject) => { | |
let req = http.request(options); | |
req.once('response', res => { | |
res.setEncoding('utf8'); | |
let data = ''; | |
res.on('data', chunk => { | |
data += chunk; | |
}); | |
res.on('end', () => { | |
resolve(data); | |
}); | |
}); | |
req.once('error', reject); | |
req.write(options.body); | |
req.end(); | |
}); | |
}; | |
const getJoke = opts => { | |
//opts.limitTo = '[nerdy]'; | |
let url = 'https://api.icndb.com/jokes/random/?' + querystring.stringify(opts); | |
let {hostname, port, path} = parse(url); | |
let options = { | |
hostname, | |
port, | |
path, | |
}; | |
return request(options) | |
.then(res => JSON.parse(res).value.joke); | |
}; | |
const sendSMS = (phoneNumber, msg) => { | |
let date = new Date(Date.now() + 10000).toISOString(); | |
let postData = { | |
Action: 'Publish', | |
AWSAccessKeyId: AWS_ACCESS_KEY, | |
Message: msg, | |
PhoneNumber: phoneNumber, | |
}; | |
postData = querystring.stringify(postData); | |
let {hostname, port, path} = parse(`http://sns.${AWS_REGION}.amazonaws.com/`); | |
let options = { | |
hostname, | |
port, | |
path, | |
method: 'POST', | |
}; | |
options = aws2.sign(Object.assign(options, {body: postData }), { | |
secretAccessKey: AWS_SECRET_KEY, | |
accessKeyId: AWS_ACCESS_KEY | |
}); | |
return request(options); | |
} | |
getName() | |
.then(getJoke) | |
.then(msg => sendSMS(process.argv[2], msg)) | |
.then(data => { | |
console.log('Sent!'); | |
}) | |
.catch(err => { | |
console.log(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment