Skip to content

Instantly share code, notes, and snippets.

@jarodreyes
Last active October 18, 2017 01:25
Show Gist options
  • Save jarodreyes/2e9b003a734de340184629093568cb22 to your computer and use it in GitHub Desktop.
Save jarodreyes/2e9b003a734de340184629093568cb22 to your computer and use it in GitHub Desktop.
functions.js
// Handles incoming messages. Goal is to pair random people who have texted the number. Like anonymous comms.
let _ = require('lodash');
exports.handler = function(context, event, callback) {
let client = context.getTwilioClient();
let createPair = require(Runtime.getFunctions()['pair-friends'].path);
let twilioNumber = event.To;
console.log(`Incoming: ${event.Body} - ${event.From}`)
client.messages.list({to: twilioNumber }).then((list) => {
let cleanedList = _.uniqBy(list, 'from');
newFriendMsg = _.sample(cleanedList);
console.log(event.From, newFriendMsg.from);
createPair.pair(event.From, newFriendMsg.from, (friend) => {
client.messages.create({
to: friend,
from: twilioNumber,
body: event.Body
}).done(callback(null, 'Your message is enroute to your friend!'))
})
})
.catch(err => console.log(err));
};
// Route 'pair-friends'
let _ = require('lodash');
exports.pair = function(from, to, callback) {
let data = {};
Runtime.getSync().documents('Twilio-Friends-demo').fetch().then((doc) => {
var friend = _.has(doc, from);
if (!friend) {
friend = to;
data[from] = to;
data[to] = from;
console.log(data);
doc.update(data);
}
console.log('Friends have been connected!');
callback(friend);
})
.catch(err => console.log(err));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment