Skip to content

Instantly share code, notes, and snippets.

@mnadel
Last active April 5, 2020 19:03
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 mnadel/517becaed9ffb9960049339dec9fdb83 to your computer and use it in GitHub Desktop.
Save mnadel/517becaed9ffb9960049339dec9fdb83 to your computer and use it in GitHub Desktop.
A Twilio app (via a series of Functions) that sends the caller to voicemail, but only if they correctly answer a captcha
const record = (twil) => {
twil.record({
transcribe: true,
transcribeCallback: "/transcribed", // see twilio-vm.js
action: "/call-missed", // see twilio-missed.js
maxLength: 90,
finishOnKey: "*"
})
}
const challenge = (evt) => {
const rand = (max) => Math.floor(Math.random() * max)
const first = rand(9)
const second = rand(9)
const answer = Math.abs(first - second)
return {
gatherOpts: {
numDigits: 1,
action: `/main?expectedAnswer=${encodeURIComponent(answer)}`
},
challenge: `Hello caller from ${evt.FromCity}. To leave a message, first use your keypad to enter the absolute difference between ${first} and ${second}.`
}
}
exports.handler = function(context, event, callback) {
const voice = new Twilio.twiml.VoiceResponse()
if (event.expectedAnswer === undefined) {
const ch = challenge(event)
voice.gather(ch.gatherOpts).say(ch.challenge)
} else if (event.expectedAnswer === event.Digits) {
voice.say("Thank you human, please leave a message after the tone.")
record(voice)
} else {
voice.say(`The answer was ${event.expectedAnswer}. Goodbye.`)
voice.hangup()
}
callback(null, voice)
}
exports.handler = function(context, event, callback) {
context.getTwilioClient().messages.create({
to: process.env.TO,
from: process.env.FROM,
body: `${event.RecordingDuration}s call from ${event.From} (${event.FromCity}, ${event.FromState} ${event.FromZip})`
}).then(msg => {
callback(null, msg.sid)
}).catch(err => callback(err))
}
exports.handler = function(context, event, callback) {
if (event.TranscriptionStatus !== "failed" && event.TranscriptionText) {
context.getTwilioClient().messages.create({
to: process.env.TO,
from: process.env.FROM,
body: `${event.From}\n${event.TranscriptionText}\n${event.RecordingUrl}`
}).then(msg => {
callback(null, msg.sid)
}).catch(err => callback(err))
} else {
callback(null, null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment