Twilio: Ruby: Callback url for concurrent calls: which call completed?
I have a list of phones that need to be called by the Twilio app so often. I have a cron job that runs every minute, which makes a list of all phones that are scheduled to be called in the next minute. The list includes calls that are scheduled to start in the next minute, as well as calls that have not been completed properly in the last hour.
For each phone in the list, I have a code that looks like this (in Ruby) to start a list of phone calls (the "phones" list) that will run in parallel, and this snippet runs every minute.
phones.each do |phone|
callbackurl="http://myapp.com/twiliocallback?phone=#{phone.id}"
data={:from=>'16135551234',
:to=>phone.number,
:url=>callbackurl
}
client=Twilio::REST::Client.new(ACCOUNT_SID, ACCOUNT_TOKEN, :ssl_verify_peer => false)
client.account.calls.create data
end
However, if the phone call takes more than a minute, I don't want the cron job to call the same number when it is already talking to Twilio. Also, if a person hangs up in the middle of a call before I can update the status, I want that number to be called again, triggered by the subsequent cron.
I know I need a status attribute for a phone call (like phone.status) with NOT_STARTED, IN_PROGRESS, and SUCCESSFULLY_COMPLETED values ββand a twilio_status attribute (like phone.twilio_status) with TWILIO_NOT_STARTED, TWILIO_IN_PROGRESS values
The call starts with
phone.status="NOT_STARTED"
phone.twilio_status="TWILIO_NOT_STARTED"
and, and as soon as I create a phone call, I can update the call status:
phone.status="IN_PROGRESS"
phone.twilio_status="TWILIO_IN_PROGRESS"
If the call completed correctly in the success path, I can set the status
phone.status="SUCCESSFULLY_COMPLETED"
If I can figure out when the call is disconnected from Twilio, I can tell if the caller was canceled by doing this
is_aborted? = twilio.status=="IN_PROGRESS" && twilio.twilio_status=="TWILIO_COMPLETED"
However, I don't know how to run the code
phone.twilio_status="TWLIO_COMPLETED"
for a specific phone call when a phone call hangs in the middle of a Twilio workflow, or even at the end of a workflow.
Twilio seems to have a callback url that can be called when the phone call completes, but it is unclear how the callback handler can determine which of the concurrent calls has completed. Is there a way to do this so that I can mark the correct call with the correct status?
source to share
In every request to your server across the entire request and in the status callback url request, Twilio passes a unique CallSid value to your server to identify the call. This is also returned to you in the XML or JSON data that you return when you first initiate the call.
https://www.twilio.com/docs/api/twiml/twilio_request
https://www.twilio.com/docs/api/rest/making-calls
You can store this CallSid value for state tracking throughout the call lifecycle.
source to share