I am using Twilio in my rails 3.1.3 app and I have got everything basically set up, i.e. a controller for sms and xml builders for the views depending on the response. The only thing I can’t figure out is how to keep track of the conversation. The Twilio docs are pretty bad for using anything other than PHP to do this. I have tried using the Rails session hash, session[:variable], but it doesn’t seem to be saving the session, as I tried redirecting and printing it out and got nothing. Below is the code of the controller.
def receive
# Check for session variable and redirect if necessary
@sms_state = session[:sms_state]
if @sms_state == 'confirmation'
redirect_to 'confirm'
end
if condition
@sms_state = 'confirmation'
session[:sms_state] = @sms_state
render :action => "view.xml.builder", :layout => false
else
@sms_state = 'new_state'
session[:sms_state] = @sms_state
render :action => "error.xml.builder", :layout => false
end
end
# method that should be called after user deals with first part
def confirm
if condition
@sms_state = session[:sms_state] = nil
render :action => "confirm_view.xml.builder", :layout => false
else
@sms_state = 'confirmation'
session[:sms_state] = @sms_state
render :action => "error.xml.builder", :layout => false
end
end
I have now set up a database table to track the current conversation state depending on the phone number contacting my app. The only thing now that I need to do is set an expiration for this conversation, just like a session or cookie. I am not sure how to do this or if its even possible.
This depends on how you define “conversation”, but in general, you are better off using some sort of persistance (would recommend database over a file), and build the structure in accordance with your definition of a conversation.
Suppose the conversation is defined as text messages between two 10-digit phone numbers without a time limit, you can setup a db with a sender and recipient attributes, so if you need to output something in a user interface, you can look for sender and recipient phone numbers, and display all messages coming to them or going from them.
SMS is different from a phone call, since you can set cookies for the session of a phone call. SMS is done when either delivered or sent. When you receive an SMS to a phone number or short code, Twilio will make a request to the URL you provided for SMS, and your app can then respond. If you receive another response, it’s a brand new request, so you have to construct the notion of “conversation”.