简体   繁体   中英

How do I dynamically generate TwiML from my Rails app?

I have integrated Twilio through twilio-ruby with my Rails app. The basic SMS and voice capabilities are working as expected, but now I want to extend my functionality. I would like to be able to generate TwiML in my controller dynamically, save it somewhere (either locally or to a service), and then have Twilio access this XML. For example, a customer makes an order through my app, TwiML is generated and saved, and then Twilio makes a voice call to my supplier with the new order data. Keeping concurrent orders in mind, what might the solution look like for this? What is the best solution for storing the TwiML/XML and then having Twilio access it? Thank you.

Dynamically generating the TwiML during the call does seem like it would be the preferred method.

An example of generating TwimL content dynamically from the docs where we greet a caller by name:

https://www.twilio.com/docs/quickstart/ruby/twiml/greet-caller-by-name#twiml-quickstartrb

require 'rubygems'
require 'sinatra'
require 'twilio-ruby'

get '/hello-monkey' do
  people = {
    '+14158675309' => 'Curious George',
    '+14158675310' => 'Boots',
    '+14158675311' => 'Virgil',
    '+14158675312' => 'Marcel',
  }
  name = people[params['From']] || 'Monkey'
  Twilio::TwiML::Response.new do |r|
    r.Say "Hello #{name}"
  end.text
end

Instead of a people array your application would have to parse incoming message bodies (if using SMS) for the order and then make the appropriate call to the supplier.

If however, your use case truly requires creating hosted TwiML on the fly, TwiML Bins in the Twilio Console will soon allow you to do this with interpolation.

That means you would be able to do something like:

curl -X POST api.twilio.com/..../Calls -d 'Url=https://hander.twilio.com/EHxxx?message=hello+world' -u Cxxx:yyyy

And your TwiML Bin would contain the necessary TwiML:

<Response><Say>{{message}}</Say></Response>

This way, you would not need to make two rest calls and wouldn't amass thousands (or more) of redundant bins that will be unwieldy to maintain or clean up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM