How to use the twilio.webhook function in twilio

To help you get started, we’ve selected a few twilio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Twilio-org / open-data-notifications / src / server / controllers / sms.js View on Github external
'use strict'

const config = require('config')
const express = require('express')
const twilio = require('twilio')
const content = require('../../static/content')
const replies = require('../commands/util/replies')

// Create a router for the SMS webhooks
let router = new express.Router()

// Configure Twilio request signature validation for production
let validator = twilio.webhook(config.get('twilio.authToken'), {
  validate: config.get('env') === 'production',
  includeHelpers: false,

  // This needs to be the full webhook URL configured on Twilio
  url: `${config.get('appUrl')}/sms`
})

// Handle incoming Twilio SMS webhook requests
router.post('/', validator, (request, response) => {
  // Create TwiML generation helper
  let twiml = new twilio.twiml.MessagingResponse()

  let user = request.body.From
  let bodyParts = request.body.Body.split(' ')
  let command = bodyParts[0].toLowerCase()
  let args = bodyParts.splice(1)
github TwilioDevEd / api-snippets / rest / voice / generate-twiml-record / twiml-record.2.x.js View on Github external
response.send(twiml);

    } else if (selectedOption == '2') {
      // Record your message
      twiml.say('Record your message after the tone.');
      twiml.record({
        action: '/voice/handle-record',
        maxLength: '30'
      });
      response.send(twiml);
    }
    response.send(redirectWelcome());
});

// POST: '/handle-record'
router.post('/handle-record', twilio.webhook({validate: false}), function (request, response) {
    var twiml = new twilio.TwimlResponse();
    twiml.say('Listen to your recorded message.');
    twiml.play(request.body.RecordingUrl);
    twiml.say('Goodbye.');
    response.send(twiml);
});

var redirectWelcome = function () {
    var twiml = new twilio.TwimlResponse();
    twiml.say("Returning to the main menu", {voice: "alice", language: "en-GB"});
    twiml.redirect("/voice");
    return twiml;
};


module.exports = router;
github TwilioDevEd / api-snippets / rest / voice / generate-twiml-gather / twiml-gather.2.x.js View on Github external
var express = require('express');
var router = express.Router();
var twilio = require('twilio');

// POST: '/voice'
router.post('/voice', twilio.webhook({validate: false}), function (request, response) {
    var twiml = new twilio.TwimlResponse();
    twiml.gather({
        action: "voice/handle-record",
        numDigits: "1",
        method: "POST"
    }, function (node) {
        node.play("http://howtodocs.s3.amazonaws.com/et-phone.mp3", {loop: 3});
    });
    response.send(twiml);
});

module.exports = router;
github kwhinnery / leavejoeamessage / controllers / twilio.js View on Github external
var twilio = require('twilio'),
    Message = require('../models/Message');

// Webhook middleware, check request signature
exports.webhook = twilio.webhook({
    // Only validate requests in production
    validate: process.env.NODE_ENV === 'production',

    // Manually configure the host and protocol used for webhook config - this
    // is the URL our Twilio number will hit in production
    host:'rev-answering-machine.herokuapp.com',
    protocol:'https'
});

// Handle incoming voice calls
exports.voice = function(request, response) {
    var twiml = new twilio.TwimlResponse();

    twiml.say('Hi there! Thanks for calling to wish Joe good luck this season. Please leave your message after the beep - you can end the message by pressing any button. Get ready!')
        .record({
            maxLength:120,
github TwilioDevEd / api-snippets / guides / request-validation-express / example-1 / example-1.3.x.js View on Github external
// You can find your Twilio Auth Token here: https://www.twilio.com/console
// Set at runtime as follows:
// $ TWILIO_AUTH_TOKEN=XXXXXXXXXXXXXXXXXXX node index.js
//
// This will not work unless you set the TWILIO_AUTH_TOKEN environment
// variable.

const twilio = require('twilio');
const app = require('express')();
const bodyParser = require('body-parser');
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const MessagingResponse = require('twilio').twiml.MessagingResponse;

app.use(bodyParser.urlencoded({ extended: false }));

app.post('/voice', twilio.webhook(), (req, res) => {
  // Twilio Voice URL - receives incoming calls from Twilio
  const response = new VoiceResponse();

  response.say(
    `Thanks for calling!
     Your phone number is ${req.body.From}. I got your call because of Twilio´s
     webhook. Goodbye!`
  );

  res.set('Content-Type', 'text/xml');
  res.send(response.toString());
});

app.post('/message', twilio.webhook(), (req, res) => {
  // Twilio Messaging URL - receives incoming messages from Twilio
  const response = new MessagingResponse();
github TwilioDevEd / api-snippets / rest / voice / generate-twiml-gather-input / twiml-gather-record.3.x.js View on Github external
const http = require('http');
const express = require('express');
const router = express.Router();
const app = express();
const twilio = require('twilio');
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const bodyParser = require('body-parser');

app.use(bodyParser.json());

// POST: '/voice/handle-gather'
router.post(
  '/handle-gather',
  twilio.webhook({ validate: false }),
  (req, res) => {
    const selectedOption = req.body.Digits;
    const twiml = new VoiceResponse();

    if (selectedOption == '1') {
      // Dial a new person
      twiml.dial('+13105551212');

      twiml.say('The call failed or the remote party hung up. Goodbye.');

      return res.send(twiml);
    } else if (selectedOption == '2') {
      // Record your message
      twiml.say('Record your message after the tone.');

      twiml.record({
github MoveOnOrg / Spoke / src / server / api / lib / twilio.js View on Github external
function webhook() {
  log.warn("twilio webhook call"); // sky: doesn't run this
  if (twilio) {
    return Twilio.webhook();
  } else {
    log.warn("NO TWILIO WEB VALIDATION");
    return function(req, res, next) {
      next();
    };
  }
}
github ethanresnick / twilio-ivr / lib / index.ts View on Github external
export default function(states: State.UsableState[], config: config): Express {
  // Set up express
  const app = express();

  // Parse twilio POST payloads, which come as urlencoded strings...
  // TODO: handle pre-parsed bodies
  app.use(bodyParser.urlencoded({ extended: false }));

  // Verify that incoming requests are coming from twilio by default or if set.
  // Note: this requires the properties on express's req object to match the
  // properties of the request as twilio sent it (i.e., protocol, host, etc.
  // can't have been rewritten internally).
  const { validate = true } = config.twilio;
  app.use(twilioWebhook(config.twilio.authToken, { validate: validate }));

  // Create a function we'll pass to makeMiddlewareAndFurl,
  // as it needs to be able to make a urlFor function too.
  const createUrlFor = createUrlForFromConfig(config.urlFor);

  // Set up our url fingerprinter. This will stay undefined if the user doesn't
  // opt in to any of our static file handling; if they do, we'll fill it with
  // the fingerprinting function returned by the static files module.
  let urlFingerprinter: fingerprintUrl | undefined;

  if (config.staticFiles) {
    // Create the middleware and url fingerprinter function that we're going
    // to use to serve static files. Save the calculated fingerprinting function.
    let serveStaticMiddlewares: Handler[];
    [serveStaticMiddlewares, urlFingerprinter] =
      makeMiddlewareAndFurl(config.staticFiles, createUrlFor);
github IBM-Cloud / doctor-watson / routes / calls.js View on Github external
res.send(twiml)
})

router.post('/recording', twilio.webhook(twilio_auth_token), function (req, res) {
  log.info(req.body.CallSid + '-> calls/recording')
  log.debug(req.body)

  var twiml = new twilio.TwimlResponse()

  enqueue_question(req.body)

  twiml.say('Let me think about that.').redirect('/calls/holding')
  res.send(twiml)
})

router.post('/answer', twilio.webhook(twilio_auth_token), function (req, res) {
  log.info(req.body.CallSid + '-> calls/answer')
  log.debug(req.body)

  var twiml = new twilio.TwimlResponse()

  twiml.say(answers[req.body.CallSid])
    .say('Do you have another question?')
    .record({timeout: 60, action: '/calls/recording'})

  res.send(twiml)
})

module.exports = router
github ethanresnick / twilio-ivr / build / lib / index.js View on Github external
function default_1(states, config) {
    const app = express();
    app.use(bodyParser.urlencoded({ extended: false }));
    const { validate = true } = config.twilio;
    app.use(twilio_1.webhook(config.twilio.authToken, { validate: validate }));
    const createUrlFor = urlFor_1.createUrlForFromConfig(config.urlFor);
    let urlFingerprinter;
    if (config.staticFiles) {
        let serveStaticMiddlewares;
        [serveStaticMiddlewares, urlFingerprinter] =
            staticFiles_1.default(config.staticFiles, createUrlFor);
        app.use(config.staticFiles.mountPath || "", serveStaticMiddlewares);
    }
    const createUrlForFromReq = createUrlFor(urlFingerprinter);
    states.forEach(thisState => {
        if (!State.isValidState(thisState)) {
            const stateAsString = State.stateToString(thisState);
            throw new Error("Invalid state provided: " + stateAsString);
        }
        if (State.isRoutableState(thisState)) {
            app.post(thisState.uri, function (req, res, next) {