Capturing Incoming Text

What if you wanted an application to answer differently depending on what was sent? Check out this example; it makes use of the initialText property of the session JSON, which contains the message sent to the application (more information about the contents of the session JSON can be found here). When a text is received, Tropo interprets the value of initialText and tailors the response accordingly. Only the libraries can parse information out of the session JSON, so no plain JSON example is available.

require 'tropo-webapi-ruby'
require 'sinatra'

post '/index.json' do
  
  t = Tropo::Generator.new
  
  v = Tropo::Generator.parse request.env["rack.input"].read
  
  initialText = v[:session][:initial_text]
      
  if initialText == "Yes"
      t.say(:value => "Awesome, I totally agree.")
  elsif initialText == "No"
      t.say(:value => "Well that's just too bad.")
  else
      t.say(:value => "That wasn't an option, sorry.")
  end
    
  t.response

end
var http = require('http');
var tropo_webapi = require('tropo-webapi');

var server = http.createServer(function (request, response) {  
  
	request.addListener('data', function(data){
  		json = data.toString();
	});
    
	request.addListener('end', function() {
	
		var session = JSON.parse(json);
		var tropo = new TropoWebAPI();
	
		var initialText = session.session.initialText;
	
		if(initialText == "Yes")
			tropo.say("Awesome, I totally agree");
		else if(initialText == "No")
			tropo.say("Well that's just too bad.");
		else
			tropo.say("That wasn't an option, sorry.");
	
		response.end(TropoJSON(tropo));
	});

}).listen(8000); 
<?php

require 'tropo.class.php';

$session = new Session(); 

$initialText = $session->getInitialText();

$tropo = new Tropo(); 

if($initialText == "Yes")
	$tropo->say("Awesome, I totally agree!");
elseif($initialText == "No")
	$tropo->say("Well that's just too bad.");
else 
	$tropo->say("That wasn't an option, sorry.");

return $tropo->RenderJson(); 

?> 
from itty import *
from tropo import Tropo, Session

@post('/index.json')

def index(request):

	s = Session(request.body)
	initialText = s.initialText
	t = Tropo()

	if(initialText == "Yes") :
		t.say("Awesome, I totally agree!")
	elif(initialText == "No") :
		t.say("Well that's just too bad.")
	else :
		t.say("That wasn't an option, sorry.")
	
	return t.RenderJson()

run_itty(server='wsgiref', host='0.0.0.0', port=8888)

In the next chapter, we cover asking questions.