Esempio n. 1
0
app.post('/sms', (req, res) => {
  let message = req.body.Body;
  let button = message.toLowerCase();
  let twiml = new twilio.TwimlResponse();
  let buttonText = 'Buttons: a(7), b(9), start(1), select(3), up(2), down(8), left(4), right(6).';

  if(gameboyButtons.indexOf(button) > -1) {
    twiml.message('Thanks for playing Pokemon with me :)');
    if(button === 'a' || button === 'b') {
      button = button.toUpperCase();
    }
    fs.writeFileSync('button.txt', button, 'utf8');
  } else {
    twiml.message('Please send a valid Gameboy button.');
  }

  res.send(twiml.toString());
});
Esempio n. 2
0
app.post('/enqueue_call', function(request, response) {
    const resp = new twilio.TwimlResponse();

    const arr = {account_number: '12345abcdef'};
    const json = JSON.stringify(arr);

    resp.enqueue(
      {workflowSid: 'WW0123456789abcdef0123456789abcdef'}, (node) => {
        node.task(json, {
            priority: '5',
            timeout: '200',
        });
      }
    );

    response.setHeader('Content-Type', 'application/xml');
    response.write(resp.toString());
    response.end();
});
Esempio n. 3
0
server.post('/keyPress', function (req, res) {
    console.log('req.body ', req.body.Digits);
    var key = req.body.Digits;
    if (keys[key]) {
        console.log("IS KEY:", keys[key]);
        FbService.moveCirlce(keys[key]);
    }
    else {
        console.log("NOT KEY");
    }
    var twiml = new twilio.TwimlResponse();
    twiml.gather({
        numDigits: '1',
        action: '/keyPress',
        method: 'POST',
        timeout: '1000'
    });
    res.send(twiml.toString());
});
Esempio n. 4
0
app.post('/enroll_or_authenticate', function(req, res) {
  var digits = req.body.Digits;
  console.log("recieved digits = " + digits);
  var twiml  = new twilio.TwimlResponse();

  // When the caller asked to enroll by pressing `1`, provide friendly
  // instructions, otherwise, we always assume their intent is to authenticate.
  if (digits == 1) {
    twiml.say(
      'You have chosen to create a new account with your voice. You will be ' +
      'asked to say a phrase 3 times, then you will be able to log in with that phrase.'
    );
    twiml.redirect('/enroll');
  } else {
    twiml.redirect('/authenticate');
  }

  res.send(twiml.toString());
});
Esempio n. 5
0
	incomingSubscribe: function(req, cb) {
		var twiml = new twilio.TwimlResponse;
		var phone = req.body.From;
		smsSubscriber.addSubscriber(phone, function(err){
			var successMessage = "We've subscribed you to air quality alerts. Thanks!";
			var message = (err) ? err.message : successMessage;
			twiml.message(message);
		 	cb(null, twiml);
		})
	},
Esempio n. 6
0
	incomingUnsubscribe: function(req, cb) {
		var twiml = new twilio.TwimlResponse;
		var phone = req.body.From;
		smsSubscriber.removeSubscriber(phone, function(err){
			var successMessage = "We've unsubscribed you from air quality alerts. Sorry to see you go!";
			var message = (err) ? err.message : successMessage;
			twiml.message(message);
		 	cb(null, twiml);
		})
	},
Esempio n. 7
0
voiceRouter.get('/response', (req, res) => {
  var phoneResponse = req.query.Digits;
  var lookupMeal;
  if (phoneResponse === '1') {
    lookupMeal = 'Breakfast';
  }
  if (phoneResponse === '2') {
    lookupMeal = 'Lunch';
  }
  if (phoneResponse === '3') {
    lookupMeal = 'Dinner';
  }
  if (phoneResponse === '7') {
    var songUrl =
      'https://ia600805.us.archive.org/27/items/NeverGonnaGiveYouUp/jocofullinterview41.mp3';
    var twiml = new twilio.TwimlResponse();
    twiml.play(songUrl);
    res.header('Content-Type', 'text/xml');
    res.end(twiml.toString());
  }
  location.find({ meal_served: lookupMeal }, (err, data) => {
    if (!err) console.log(data);

    var currentDay = dayFilter.getStringDay();
    var results = dayFilter.matchDay(data, currentDay);
    var resp = new twilio.TwimlResponse();

    resp.say(
      'Result 1. meal served.' + results[0].meal_served
      + '.. Location: ' + results[0].location + '.. Meals Served..'
      + results[0].day_time + '..' + results[0].people_served +
      '.. Result 2. meal served.' + results[1].meal_served
      + '.. Location: ' + results[1].location + '.. Meals Served.'
      + results[1].day_time + '..' + results[1].people_served
      + '.. Thank you for calling Next-Meal. Goodbye.');

    res.writeHead(200, {
      'Content-Type': 'text/xml'
    });
    res.end(resp.toString());
  });
});
Esempio n. 8
0
    webserver.post('/sms/receive', function (req, res) {
      twilioSMS.log('=> Got a message hook')

      let message = {
        text: req.body.Body,
        from: req.body.From,
        to: req.body.To,
        user: req.body.From,
        channel: req.body.From,
        timestamp: Date.now(),
        sid: req.body.MessageSid
      }

      twilioSMS.receiveMessage(bot, message)

      // Send empty TwiML response to Twilio
      let twiml = new twilio.TwimlResponse()
      res.type('text/xml')
      res.send(twiml.toString())
    })
Esempio n. 9
0
app.post('/voice/choose', function (req, res) {
  var rep = new twilio.TwimlResponse();
  if ( Number(req.body.Digits) === 1 ) {
    rep.pause()
      .say('This voice session will start recording for up to 10 seconds after the beep. Press any key to stop the recording.', voiceConfig)
      .record({
        action: '/voice/record',
        maxLength: 10
      })
      .say('Nothing recorded. Thanks for calling MyOrchestra Voice. Have a great day!', voiceConfig)
      .hangup();
  }
  else {
    rep.say('Thanks for calling MyOrchestra Voice. Have a great day!', voiceConfig)
      .hangup();
  }
  res.set('Content-Type', 'text/xml');
  res.send(rep.toString());
  console.log('RESP');
});
Esempio n. 10
0
    .then(server.twiml(result => {
      console.log(result.Digits);

      const select = prefectures
              .filter(pref => pref.area === value.area && pref.number === result.Digits);

      anq.prefecture = select[0].code;

      const resp = new twilio.TwimlResponse();
      resp.say('性別を教えてください', { language: 'ja-JP' });
      resp.gather({
        numDigits: 1,
      }, function () {
        this.say('男性の方は 1 を、' +
                 '女性の方は 2 を、' +
                 '不明な方は 3 を、' +
                 '押してください', { language: 'ja-JP' });
      });
      return resp.toString();
    }))
Esempio n. 11
0
    .then(server.twiml(result => {
      anq.phoneNumber = result.From;

      const resp = new twilio.TwimlResponse();
      resp.say('こんにちわ! お住まいの地方はどちらですか?', { language: 'ja-JP' });
      resp.gather({
        numDigits: 1,
      }, function () {
        this.say('北海道・東北地方は 1 を、' +
                 '関東地方は 2 を、' +
                 '中部地方は 3 を、' +
                 '関西地方は 4 を、' +
                 '中国地方は 5 を、' +
                 '四国地方は 6 を、' +
                 '九州・沖縄地方は 7 を押してください', {
                   language: 'ja-JP',
                 });
      });
      return resp.toString();
    }))
Esempio n. 12
0
	create: function(req, res, sockets) {
		var channel = this.count % this.channelCount;
		if (req.query.channel) channel = req.query.channel >> 0;

		var speaker = new this.Speaker(this.count, channel);


		this.channels[channel].add(speaker);

		launchpad.getButton(channel,this.channels[channel].speakerCount-1).light(Launchpad.colors.green.high);


		this.count++;
		sockets.emit('call',{speaker:speaker, body:req.body.From});
		var twiml = new twilio.TwimlResponse();
		twiml.say("please wait");
		res.send(speaker.response(twiml).toString());

		return speaker;
	},
Esempio n. 13
0
var handleMessage = function(req, reply) {

  var header = req.headers['x-twilio-signature'];
  var token = process.env.TWILIO_AUTH_TOKEN;
  var url_base = 'http://'+req.info.host;
  if (!twilio.validateRequest(token, header, url_base+'/message', req.payload)) {
    reply(Boom.forbidden('Invalid x-twilio-signature'));
    return;
  }

  var from = req.payload.From;
  var to = req.payload.To;
  var mediaUrl = req.payload.MediaUrl0;
  var mediaContentType = req.payload.MediaContentType0;
  var filter = req.payload.Body.toLowerCase().trim();
  var twiml = new twilio.TwimlResponse();

  console.log('Processing MMS: ', mediaUrl, mediaContentType, filter);

  // see if a valid filter was passed
  var filterValid = false;
  for (i in filters) {
    if (filter === filters[i].toLowerCase()) {
      filterValid = true;
      filter = filters[i];
      break;
    }
  }
 
  // check to see that the user has submitted an image
  if (mediaUrl && mediaContentType && mediaContentType.indexOf('image') >= 0) {
    // check to see that a valid filter command was passed
    if (filterValid) {
      // send immediate reply
      twiml.message('Thanks for the awesome photo! Applying filter now..');
      reply(twiml.toString()).type('text/xml');
      
      applyFilter(mediaUrl, filter, from, to, url_base);
    }
    else {
      // else respond with a list of valid filters
      twiml.message('Hmmm, I do not recognize the filter "'+ filter + '".\n\n' +  
        'Valid filters are: ' + filters.join(', '));
      reply(twiml.toString()).type('text/xml');
    }

  }
  else {
    // send instructions for app
    twiml.message('Thanks for trying Phonestagram, the photo filtering ' +
      'and sharing app that works on any phone! Just text a photo to this ' +
      'number and specify the filter you would like.\n\nValid filters are: ' +
      filters.join(', '));
    reply(twiml.toString()).type('text/xml');
  }
};
Esempio n. 14
0
app.post('/message', function (req, res) {

    var resp = new twilio.TwimlResponse();

    var body = req.body.Body;
    console.log("body:", body);

    var clue = body.match(/clue (.*)/i)[1];
    console.log("clue:", clue);

    var hint = config.hints[clue];
    console.log("hint:", hint);

    resp.message('Hint ' + clue + ': ' + hint, {
      from: 'Hen Hint'
    });

    res.set('Content-Type', 'text/xml');

    res.send(resp.toString());
});
Esempio n. 15
0
app.post('/handle-input', (req, res) => {
  const digitPressed = req.body.Digits;
  const player = req.body.To === PLAYER_ONE ? 1
               : req.body.To === PLAYER_TWO ? 2
               : null;

  let twiml = new twilio.TwimlResponse();

  if (digitPressed) {
    io.emit('input', { 'player': player, 'button': digitPressed });
  }

  twiml.gather({
    numDigits: '1',
    action: '/handle-input',
    method: 'POST',
    timeout: '1000'
  });

  res.send(twiml.toString());
});
Esempio n. 16
0
it('should support a flat document with say nodes, with attributes', function() {
        var response = new twilio.TwimlResponse();
        response.say('Obrigado por ligar para a ebopi. Sua ligacao e muito importante para nos. Fique na linha para que direcionamos sua ligacao para um de nossos colaboradores', {
            voice:'woman',
            language:'pt-BR'
        });
	response.dial(
	'+5511983600707');
        var xml = response.toString(),
            test = [
                '<?xml version="1.0" encoding="UTF-8"?>',
                '<Response>',
                '<Say voice="woman" language="pt-BR">Obrigado por ligar para a ebopi. Sua ligacao e muito importante para nos. Fique na linha para que direcionamos sua ligacao para um de nossos colaboradores</Say>',
		'<Dial>', 
			 '+5511983600707',
		'</Dial>',	
                '</Response>'
            ].join('');

        expect(xml).toBe(test);
    });
Esempio n. 17
0
  location.find({ meal_served: lookupMeal }, (err, data) => {
    if (!err) console.log(data);

    var currentDay = dayFilter.getStringDay();
    var results = dayFilter.matchDay(data, currentDay);
    var resp = new twilio.TwimlResponse();

    resp.say(
      'Result 1. meal served.' + results[0].meal_served
      + '.. Location: ' + results[0].location + '.. Meals Served..'
      + results[0].day_time + '..' + results[0].people_served +
      '.. Result 2. meal served.' + results[1].meal_served
      + '.. Location: ' + results[1].location + '.. Meals Served.'
      + results[1].day_time + '..' + results[1].people_served
      + '.. Thank you for calling Next-Meal. Goodbye.');

    res.writeHead(200, {
      'Content-Type': 'text/xml'
    });
    res.end(resp.toString());
  });
Esempio n. 18
0
File: app.js Progetto: syggies/Lott
 Lottery.find({token: req.param('token')}, function(err, docs){
   if(err){
     speak_error_message(res, "エラーが発生しました。通話を終了します");
   }else{
     var l = docs[0];
     if(l.voice_file){
       send_xml(res, resp.play(req.protocol + "://" + req.hostname + "" + l.voice_file.replace(/public/, '').replace(/\\/g, '/')));
     }else{
       speak_error_message(res, l.voice_text);
     }
   }
 });
Esempio n. 19
0
app.post('/dingdong', function(req, res){
  debug('/dingdong');
  if (!validateTwilioRequest(req, res)) return false;

  var response = new twilio.TwimlResponse();

  /*
  response.dial({
          timeout: 30,
          timeLimit: 180,
        }, config.forward_phone);
  res.send(response.toString());
  return;
  */
  response.pause({ length:5 }).gather({
        action: '/passcode',
        finishOnKey: '#',
        timeout: 10,
        numDigits: config.passcode.length
      }, function() {
          if (typeof(config.message) == "string") {
            this.say({
              voice: 'alice'
            }, config.message);
          } else {
            this.play("/message.wav");
          }
      }).dial({
          timeout: 30,
          timeLimit: 180,
        }, config.forward_phone);

  res.send(response.toString());

  client.sendMessage({
    to: '+12403883850',
    from: '+14152363539',
    body: 'Door activated.'
  }, function(){});
});
Esempio n. 20
0
app.post("/text", function(req, res){
    var json = req.body.Body;
    console.log(json);
    var message = "";

   if(json.toLowerCase().indexOf('open') != -1) {
        stat = 1
        message = "Your window has been opened successfully."
    } else if(json.toLowerCase().indexOf('clos') != -1) {
        stat = 0
        message = "Your window has been closed successfully."
    }

    var twiml = new twilio.TwimlResponse();
    twiml.message(message)

    res.type('text/xml');
    res.send(twiml.toString());

    http.request("http://agent.electricimp.com/5lnzpVhsLEK_?status=" + stat, function(){}).end();
    res.send("Ok");
});
Esempio n. 21
0
function basicCall (req, res, at) {
	// Create a TwiML response
	var resp = new twilio.TwimlResponse();

	//greet and record voice
	resp.say({voice:'woman'}, 'Record your tweet, then press any key to continue');
	var recordUrl = req.protocol + "://" + req.get('host') + '/recorded/';
	var transcribeUrl = req.protocol + "://" + req.get('host') + '/transcribed/';
	if(at) {
		transcribeUrl+=at;
		recordUrl+='true/';
	} else {
		recordUrl+='false/';
	}
	resp.record({transcribeCallback:transcribeUrl, action:recordUrl, method:'GET'});

	//Render the TwiML
	res.writeHead(200, {
	'Content-Type':'text/xml'
	});
	res.end(resp.toString());
}
Esempio n. 22
0
app.post('/handle-key', (req, res) => {
  let digitPressed = req.body.Digits;
  let button = keys[digitPressed];

  if(gameboyButtons.indexOf(button) > -1) {
    if(button === 'a' || button === 'b') {
      button = button.toUpperCase();
    }
    fs.writeFileSync('button.txt', button, 'utf8');
  }
  console.log(digitPressed);

  let twiml = new twilio.TwimlResponse();
  twiml.gather({
    numDigits: '1',
    action: '/handle-key',
    method: 'POST',
    timeout: '1000'
  });

  res.send(twiml.toString());
});
Esempio n. 23
0
exports.handler = function(event, context) {
  var twilio = require('twilio');
  var dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10', region: 'ap-northeast-1'});

  /* Make sure we have a valid vote (one of [RED, GREEN, BLUE]) */
  console.log(event);
  var votedFor = event['Body'].toUpperCase().trim();
  if (['RED', 'GREEN', 'BLUE'].indexOf(votedFor) >= 0) {
    /* Add randomness to our value to help spread across partitions */
    var votedForHash = votedFor + "." + Math.floor((Math.random() * 10) + 1).toString();
    /* ...updateItem into our DynamoDB database */
    var tableName = 'VoteApp';
    dynamodb.updateItem({
      'TableName': tableName,
      'Key': { 'VotedFor' : { 'S': votedForHash }},
      'UpdateExpression': 'add #vote :x',
      'ExpressionAttributeNames': {'#vote' : 'Votes'},
      'ExpressionAttributeValues': { ':x' : { "N" : "1" } }
    }, function(err, data) {
      if (err) {
        console.log(err);
        context.fail(err);
      } else {
        var resp = new twilio.TwimlResponse();
        resp.message("Thank you for casting a vote for " + votedFor);
        context.done(null, [resp.toString()]);
        console.log("Vote received for %s", votedFor);
      }
    });
  } else {
    var resp = new twilio.TwimlResponse();
    resp.message(votedFor + " is not a valid option. Please vote for RED, GREEN or BLUE.");
    context.done(null, [resp.toString()]);
    console.log("Invalid vote received %s", votedFor);
    //context.fail("Invalid vote received");
  }

};
Esempio n. 24
0
app.get('/finishedrecording', function (req,res) {
	resp.say('Thank you for using KGB, agent Hunt.', {
		voice:'woman',
		language:'en-gb'
	});
	res.type('text/xml');
	res.send(resp.toString());

	client.recordings.list(function(err, data) {
	    // iterator tracks us as we step through all recordings on the twilio server, for our account
	    var iterator = 0;
	    
	    data.recordings.forEach(function(recording) {
	        
	        console.log("Iteration: "+iterator);
	        //recordingSids.push(recording.sid);
	        recordingURLs.push(recording.uri);
	        
	        // Change recordingURL to map to .wav file, vs .json and push to reocordingWavURLs array
	        var temp = recordingURLs[iterator].slice(0,-4);
	        temp = temp.concat("wav");
	        recordingWavURLs.push(temp);
	        iterator++;
	    });    
	    var file = fs.createWriteStream("recording.wav");        

	    var options = {
	      host: twilioHost,
	      path: recordingWavURLs[0] // request the newest recording from the server (twilio adds newest recordings to the front of the array)
	    };

	    callback = function(response) {
	      response.pipe(file); // wrires the repsonse to the file
	    }

	    https.get(options, callback).end(); // we want to call this only once we know that the recording has completed!
	});
});
Esempio n. 25
0
router.post('/', twilio.webhook(twilio_auth_token), function (req, res) {
  log.info(req.body.MessageSid + '-> sms/')

  var twiml = new twilio.TwimlResponse()

  log.info(req.body.MessageSid + ' QUESTION: ' + req.body.Body)
  doctor.ask(req.body.Body, function (answer) {
    log.info(req.body.MessageSid + ' ANSWER: ' + answer)

    twiml.message("Hear me now: " + answer)
    res.send(twiml)
  })

})
Esempio n. 26
0
app.post('/message', function (request, response) {
	var d = new Date();
	var date = d.toLocaleString();

	messagesRef.push({
		sid: request.param('MessageSid'),
		type:'text',
		direction: "inbound",
		tstamp: date,
		fromNumber:request.param('From'),
		textMessage:request.param('Body'),
		fromCity:request.param('FromCity'),
		fromState:request.param('FromState'),
		fromCountry:request.param('FromCountry')
	});

	var resp = new twilio.TwimlResponse();
	resp.message('Thanks for the message, an agent will get back to you shortly.');
	response.writeHead(200, {
		'Content-Type':'text/xml'
	});
	response.end(resp.toString());
});
Esempio n. 27
0
app.get('/record/', function (req, res) {
	console.log("\nPOST RECORDING: " + req.originalUrl);
	// Create a TwiML response
	var resp = new twilio.TwimlResponse();
	var digits = req.query.Digits;
	var recordUrl = req.protocol + "://" + req.get('host') + '/recorded/false/';

	if (digits[digits.length-1] == '1'){
		//if we have the digit '1', then we are recording again
		resp.say({voice:'woman'}, 'Please record your tweet, then press any key!');
		var transcribeUrl = req.protocol + "://" + req.get('host') + '/transcribed/';
		resp.record({transcribeCallback:transcribeUrl, action:recordUrl, method:'GET'});
	} else {
		//otherwise we can end
		resp.say({voice:'woman'}, 'Thank you.');
	}

	//Render the TwiML
	res.writeHead(200, {
	'Content-Type':'text/xml'
	});
	res.end(resp.toString());
});
Esempio n. 28
0
app.get('/recorded/:direct', function (req, res) {
	console.log("\nRECORDED: " +req.params.direct +" : "+ req.originalUrl);
	// Create a TwiML response
	var resp = new twilio.TwimlResponse();
	var digits = req.query.Digits;
	var recordUrl = req.protocol + "://" + req.get('host') + '/record/';

	//if we have no digits, then we have just recorded
	resp.say({voice:'woman'}, 'Your tweet has been recorded');
	//get user input if they did not text in
	if(req.params.direct == 'false'){
		resp.gather({ timeout:30, method:"GET", numDigits:1, action:recordUrl}, function() {
			this.say({voice:'woman'}, 'Press 1 to record another tweet, or any other key to end the call!');
		});
	}
	resp.say({voice:'woman'}, 'Thank you.');

	//Render the TwiML
	res.writeHead(200, {
	'Content-Type':'text/xml'
	});
	res.end(resp.toString());
});
Esempio n. 29
0
  voicemail.create = function (req, res) {
    var resp = new Twilio.TwimlResponse()
      ;

    //resp.play('http://chunkhost.coolaj86.com:8080/voicemail.wav');
    resp.play('/voicemail.wav');
    resp.record({
      action: '/twilio/voicemail/forward?wait=true'
    , transcribeCallback: '/twilio/voicemail/forward'
    , maxLength: 150
    , transcribe: true
      // TODO remove beep from my recording
    , playBeep: false
      // end recording if the person doesn't speak within 5 seconds
    , timeout: 5
    , method: 'POST'
    });

    // Actually respond
    res.setHeader('Content-Type', 'application/xml');
    res.write(resp.toString());
    res.end();
  };
Esempio n. 30
0
		callsRef.where({"sid": sid}).on('value',function( rec ){
			if( rec.count() !== null ){
				var sidinfo = rec.first().value();
				if( sidinfo ){
					var agent = sidinfo.agent;
					update_agent(agent, {
						'status': 'missed'
					});
				}
				// Change agent status for agents that missed calls
			}
			//	redirect and try to get new agent...
			twiml.redirect('/voice');
		});