pythontwiliotwilio-twimltwilio-click-to-call

Single Outgoing Call + Conference Call


How to implement a single outgoing call and conference call?

I have outgoing call setup working: A POST request hits the /voice endpoint and call goes through, likewise incoming call. I have read the conference code sample and see it hits the same /voice endpoint.

My logic is implementing a system that states whether outgoing call is single or conference then the option gets triggered in an if-else statement.

Pseudocode, kinda:

@app.route('/voice', methods=['POST'])
def voice():
    option = flask.request.get_json()['option']
    if option == 'single':
        #outgoing_call code
    else:
        #conference_call code

my {{domain}}/voice is registered on TWIML app.

Is there a good/better approach on getting this done or am I missing something?


Solution

  • When you make the outbound call, you provide the URL to the /voice endpoint on your server. If you know at the time that you are either making a single or conference call, you can provide different URLs that do different things when the call connects. For example:

    from flask import Flask, Response
    from twilio.twiml.voice_response import VoiceResponse, Dial
    
    @app.route("/conference", methods=["POST"])
    def conference():
        response = VoiceResponse()
        dial = Dial()
        dial.conference("Conference")
        response.append(dial)
        return Response(str(response), mimetype="text/xml")
    
    @app.route("/voice", methods=["POST"])
    def single():
        response = VoiceResponse()
        dial = Dial()
        dial.number("+123456789")
        response.append(dial)
        return Response(str(response), mimetype="text/xml")    
    

    Then, when you create the call, use a different endpoint based on what you want to happen:

    import os
    from twilio.rest import Client
    
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['TWILIO_AUTH_TOKEN']
    client = Client(account_sid, auth_token)
    
    if (SINGLE_CALL_CONDITIONAL):
        url = "https://example.com/voice
    else:
        url = "https://example.com/conference"
    
    call = client.calls.create(
                            url=url,
                            to='+14155551212',
                            from_='+15017122661'
                        )