Last active
March 29, 2019 20:00
-
-
Save bdm1981/f432997f5339f8cd418ce85507fb1c84 to your computer and use it in GitHub Desktop.
Twilio Voicemail to Email via SendGrid
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
exports.handler = function(context, event, callback) { | |
const sgMail = require('@sendgrid/mail'); | |
sgMail.setApiKey(context.SG_API_KEY); | |
let spam = 0; | |
if(event.AddOns){ | |
const addOns = JSON.parse(event.AddOns); | |
if (('nomorobo_spamscore' in addOns.results)) { | |
spam = addOns.results.nomorobo_spamscore.result.score; | |
} | |
} | |
// REQUIRED - you must set this | |
let phoneNumber = "sip:uri@dmail.com"; | |
// generate the TwiML to tell Twilio how to forward this call | |
let twiml = new Twilio.twiml.VoiceResponse(); | |
//The caller is sent to voicemail if the function is called by the action handler and the DialCallStatus does not equal completed. | |
if(typeof(event.DialCallStatus) != 'undefined' && event.DialCallStatus !== 'completed'){ | |
twiml.say("Please leave a message and I will call you back as soon as possible."); | |
twiml.record({ | |
timeout: 60, | |
transcribe: true, | |
transcribeCallback: "/deskphone_voicemail" | |
}); | |
// return the TwiML | |
callback(null, twiml); | |
// This code block is only fired when the TranscriptionSid is present in the event. | |
}else if(event.TranscriptionSid){ | |
let client = context.getTwilioClient(); | |
client.transcriptions(event.TranscriptionSid).fetch().then(transcription => { | |
const msg = { | |
to: 'you@example.com', | |
from: 'noreply@example.com', | |
subject: 'new voicemail', | |
templateId: 'd-XXXXXXXXX', | |
dynamic_template_data: { | |
From: event.From, | |
Time: Date(transcription.dateCreated), | |
RecordingUrl: event.RecordingUrl, | |
Transcription: transcription.transcriptionText | |
} | |
}; | |
return sgMail.send(msg); | |
}).then(done => { | |
callback(null); | |
}); | |
// If the call completes successfully this block is called and the the function stops | |
}else if(event.DialCallStatus === 'completed'){ | |
console.log("call complete"); | |
callback(null); | |
// This code block is fired on a new inbound call. If the nomospam addon is present, the spam score will be evaluated. | |
}else{ | |
if (spam === 0) { | |
let dial = twiml.dial({ | |
timeout: 14, | |
method: 'POST', | |
action: '/deskphone_voicemail' | |
}); | |
dial.sip(phoneNumber); | |
}else { | |
twiml.say('Sorry, you are calling from a restricted number. Good bye.'); | |
} | |
// return the TwiML | |
callback(null, twiml); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment