Search code examples
pythonflasktwiliotwilio-programmable-voice

How do I run more code in Twilio/Flask after enqueuing an incoming caller?


I want to have my Twilio/Flask app put an incoming caller on hold while I run more code to contact the person to connect them to.

The relevant part of my code:

@app.route('/ivr', methods=['POST'])
def welcome():
    response = VoiceResponse()
    with response.gather(
        num_digits=1, action=url_for('router'), method="POST"
    ) as g:
        g.say('if this is an emergency press 1, otherwise press 2')
    return twiml(response)

@app.route('/ivr/router', methods=['POST'])
def status_router():
    selected_option = request.form['Digits']
    if selected_option == '1':
        return redirect('/ivr/queue')

    elif selected option == '2':
        return redirect('/ivr/voicemail')

@app.route('/ivr/queue', methods=['POST', 'GET'])
def queue_connect():
    response = VoiceResponse()
    response.say("we are connecting you to our team")
    response.enqueue('otg')
    return twiml(response)

@app.route('/ivr/call_circle', methods=['POST'])
def call_circle():
    callCircle(on_call=True)
    return

The idea is to send the caller to /ivr/queue while I run callCircle() to contact someone. As is, I don't know how to get anything to run after returning the queue_connect() TWiML. I could run callCircle() as part of /ivr/queue but then the TWiML wouldn't run until the rest of the code ran, defeating the purpose of putting them on hold in the first place.


Solution

  • I think you have two options here:

    • You could switch from the queue approach to using Twilio conferences, i.e. in queue_connect dial the caller in a new conference instead and then connect webhooks via statusCallback and statusCallbackEvent. For a list of events see the doc. I think relevant here is join which should fire immediately once the caller has been connected to the conference and thus solve your problem and just give you a hook to continue your business logic.
    • You could use an asynchronous HTTP request in queue_connect before returning the TwiML to your user. Because effectively you don't care about the response to your /ivr/call_circle so you can just fire and forget. You could use requests-futures or similar.