Skip to content

Instantly share code, notes, and snippets.

@claudiahdz
Last active August 11, 2017 10:19
Show Gist options
  • Save claudiahdz/dc607a43662ee6d232d6d1e632a8093a to your computer and use it in GitHub Desktop.
Save claudiahdz/dc607a43662ee6d232d6d1e632a8093a to your computer and use it in GitHub Desktop.
'use latest';
const Twitter = require('twit');
const request = require('request');
let client;
let destination = 'destination';
// Generates random integer
const getRandomInt = (min, max) => {
return ~~(Math.random() * (max - min + 1)) + min;
};
// Gets formatted address from latitude or longitude
// using the Google Maps API
const getAddress = (lat, long, cb) => {
const url = `http://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&sensor=false`;
request(url, (error, response, body) => {
if(error) console.log('Error while converting latitude or longitude: ', error);
body = JSON.parse(body);
// Verifies that there are results
if (body.results.length !== 0) {
const formattedAddress = body.results.shift().address_components.filter((el) => {
return ~el.types.indexOf('route'); // Filters street name
});
destination = formattedAddress.shift().short_name;
}
sendTweet(cb);
});
};
const sendTweet = (cb) => {
const messages = [
`Hey! I safely arrived to ${destination}.`,
`Made it to ${destination}!`,
`What a ride! I'm finally at ${destination}.`,
`I just arrived at ${destination}.`
];
client.post('statuses/update', { status: messages[getRandomInt(0, messages.length-1)] }, (err, data, response) => {
if(err) console.log('Error while sending tweet: ', err);
cb(null, 'Sucesss.');
});
};
module.exports = (ctx, cb) => {
client = new Twitter({
consumer_key: ctx.secrets.TWITTER_CONSUMER_KEY,
consumer_secret: ctx.secrets.TWITTER_CONSUMER_SECRET,
access_token: ctx.secrets.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: ctx.secrets.TWITTER_ACCESS_TOKEN_SECRET
});
getAddress(ctx.data.DropoffLat, ctx.data.DropoffLong, cb);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment