Record Calls using Python

    Overview

    Conversation with your customers is a crucial piece of information. Call recording is essential in businesses where reviews can help improve customer experience and business processes. You can record any outgoing or incoming calls from/to the Plivo Voice Platform using the various APIs and XML elements provided for different scenarios. Plivo Voice Platform allows you to record, store, retrieve, and delete recordings on the cloud.

    This guide will help you learn about initiating call recordings for outbound API calls, dial XML-connected calls, conference calls, recording features, and aspects of managing call recordings.

    Set Up Your Python Dev Environment

    In this section, we’ll walk you through how to set up a Flask server in under five minutes and start handling incoming calls & callbacks.

    Install Plivo Python Package

    • Create a project directory, run the following command:

      $ mkdir mypythonapp
      
    • Change the directory to our project directory in the command line:

      $ cd mypythonapp
      
    • Install the SDK using pip

      $ pip install plivo
      
    • Alternatively, you can download the source code from this repo and run

      $ python setup.py install
      

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Initiate a Call Recording

    There are several ways to start recording a call. You can start a call recording as per your use-case and business requirements. For example, if you want to record a complete call session, you can use Dial XML and enable the complete call session to be recorded (this will be explained further in this guide). You can find all possible ways to record a call in detail in the sections below.

    Record a call using API

    You can start and stop voice recordings for outbound API calls, dial XML-connected calls, and conference calls using the Record calls & Record conference APIs. Recording a call using the API will be done in use-cases when you want to record a specific portion of a call. It will also be helpful in use-cases where you want to make multiple recordings on the same call.

    Record a Call API

    To start voice recording using the record calls API, you need to use the callUUID of the particular call that you want to record.

    Retrieve CallUUID You can get the callUUID of a call connected via the Outbound API & Dial XML from:

    • ring_url: Plivo sends a webhook callback to ring url used in the Outbound Call API request as soon as the destination number starts ringing.
    • answer_url: Plivo sends a webhook callback to answer url when the destination number answers the call.
    • fallback_url: If you have defined the fallback url argument in the API request or the application attached to the Plivo number, and if your application server defined in the answer url is unavailable, then Plivo will try to retrieve the XML document from fallback url to process the call, and during that time Plivo will send a webhook callback to the fallback url.
    • callback_url: If you have used the callback_url param in the dial XML, Plivo will send a callback to your web server configured in callback_url once the number specified in the dial XML answers the call.

    Start Recording If you have the callUUID you want to record, you can start the record call API by specifying the callUUID in the payload. You can stop recording a call in the same way by using the CallUUID if you want to stop recording halfway or if you want to record different sections of the same call.

    For example, if you want to record an outbound API call, you can follow the implementation below to record the call once the destination number answers the call, and the recording will stop automatically once the call is completed.

    Callbacks You can use the callback_url param and set the URL of your application server. Plivo will post the call recording information to the callback url with recording_url, recording_duration, and recording_id.

    Create a Flask App to Record a Call using API

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    
    from flask import Flask, Response, request, url_for
    from plivo import plivoxml
    import plivo
    import
    
    app = Flask(__name__)
    
    # When the call is answered, a text is played which prompts the user to press 1 to record the call.
    # Once the digit is pressed, the Record API request is made and the recording starts.
    
    
    @app.route('/record_api/', methods=['POST', 'GET'])
    def record_api():
    
        response = plivoxml.ResponseElement()
        getinput_action_url = "http://www.foo.com/firstbranch/"
        response.add(plivoxml.GetInputElement().
                     set_action('https://www.foo.com/result').
                     set_method('POST').
                     set_input_type('dtmf').
                     set_digit_end_timeout(5).
                     set_redirect(True).add(
            plivoxml.SpeakElement('Press 1 to record this call')))
        return Response(response.to_string(), mimetype='application/xml')
    
    # The Record API is invoked by the Get Digits action URL
    
    
    @app.route('/record_api_action/', methods=['POST', 'GET'])
    def record_action():
        digit = request.args.get('Digits')
        call_uuid = request.args.get('CallUUID')
        print "Call UUID is : %s " % (call_uuid)
        print "Digit pressed is : %s " % (digit)
    
        client = plivo.RestClient("Your AUTH_ID", "Your AUTH_TOKEN")
        if digit == "1":
            response = client.calls.record(
                call_uuid=call_uuid, )
        else:
            print "Wrong Input"
            response = "Error"
        return Response(response.to_string(), mimetype='text/plain')
    
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug='True')
    

    Save this code in any file (name the file something like record_call.py). To run this file on the server, go to the folder where this file resides and use the following command:

    $ python record_call.py
    

    And you should see your basic server app in action on http://localhost:5000/record_api/

    Record Conference API

    To start recording conference calls using the Record Conference API, you should use the “Conference Name” of the particular conference you want to record. For example, If you want to start recording a conference call once the participant has entered the conference room, you can follow the implementation below.

    Callbacks You can use the callback_url param and set the URL of your application server. Plivo will post the call recording information to the callback url with recording_url, recording_duration, and recording_id.

    Code

    1
    2
    3
    4
    5
    6
    
    import plivo
    
    client = plivo.RestClient('<auth_id>','<auth_token>')
    response = client.conferences.record(
        conference_name='testing', )
    print(response)
    

    Record a call using XML

    You can record calls using XML in many ways. You can record a complete call session using record XML in conjunction with dial XML. Recording a call using XML will be helpful in use-cases where you want to record the complete call session for voice or conference calls. It will also be useful in applications such as virtual voicemail boxes, automated speech surveys, etc.

    Record a Voice Call

    You can record the complete session of a dial XML-connected call by using a Dial XML response like below:

    <Response>
      <Record action="http://foo.com/get_recording/" startOnDialAnswer="true" redirect="false" maxLength="3600" />
      <Dial>
        <Number>15551234567</Number>
      </Dial>
    </Response>
    

    The call connected via XML above will record the complete call session once the number specified in the dial XML answers the call. Recording details will be sent to the action URL as soon as the recording starts. You can use the various attributes available in the record XML to control the recording behavior.

    Callbacks You can either use the action or callback_url attribute of the record XML to receive HTTP callbacks related to the call recording on your application server. Plivo will send details such as RecordUrl, RecordingDuration, RecordingDurationMs, RecordingStartMs, RecordingEndMs, RecordingID in the HTTP callback.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    from plivo import plivoxml
    
    response = plivoxml.ResponseElement()
    response.add(
        plivoxml.RecordElement(
            action='http://foo.com/get_recording/',
            start_on_dial_answer=True,
            redirect=False))
    response.add(plivoxml.DialElement().add(plivoxml.NumberElement('15551234567')))
    print(response.to_string())
    

    Record a Conference Call

    You can record a conference call initiated using a Conference XML by using an XML response like below:

    <Response>
        <Conference callbackUrl="https://www.foo.com/confevents/" callbackMethod="POST" record="true" recordFileFormat="wav">My Room</Conference>
    </Response>
    

    The audio of the conference members connected via XML above will get recorded. Recording details will be sent to the action URL, callback URL as soon as the recording starts. You will also get an event to the callback URL, i.e, ConferenceAction as “record” when the recording starts.

    You can use the recordFileFormat attribute available in the conference XML to record the conference call in wav or mp3 format as you wish.

    Callbacks You can either use the action or callback_url attribute of the conference XML to receive HTTP callbacks related to the conference recording on your application server. Plivo will send details such as RecordUrl, RecordingDuration, RecordingDurationMs, RecordingStartMs, RecordingEndMs, RecordingID in the HTTP callback.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    from plivo import plivoxml
    
    response = plivoxml.ResponseElement()
    response.add(
        plivoxml.ConferenceElement(
            'My Room',
            record=True,
            callback_url='http://foo.com/confevents/',
            callback_method='POST',
            wait_sound='http://www.foo.com/waitmusic/'))
    
    print(response.to_string())
    

    Recording Features

    In this section, we will walk you through the features associated with recording on the Plivo Voice Platform:

    • File formats: You can choose the file format as per your wish. We recommend using the attributes such as “file_format” for Record a Call API & Record a Conference API, and “recordFileFormat” for Conference XML & “fileFormat” for Record XML.
    • Channel: Plivo records the conference calls in the Mono channel and normal calls in the Stereo channel.
    • Recording length: You can set the maximum duration of recording using the respective arguments & attributes such as “time_limit” for Record a Call API and “maxLength” for Record XML.

    Manage recordings

    • Downloading Recordings: You can store and retrieve the recording details of the voice calls and conference calls using the HTTP callbacks received on the action and callback URLs. Also, you can fetch the recording details from your Plivo Console.
    • Deleting Recordings: You can delete the recordings using the Delete a Recording API. To delete a specific recording using this API, you need the recordingID. You can retrieve the same from the HTTP callback details stored on your database. Also, you can delete the recordings from your Plivo Console.

    Authentication for Recordings

    Recordings hosted on Plivo servers are only accessible via unique, hard to guess, long URLs. These URLs are shared with you in Recording callbacks and API responses. By default, authentication is not enforced on GET recording media requests. This allows for easier implementation of use cases that involve playing recordings on a web/mobile frontend.

    For enhanced security, we recommend enabling Plivo Auth Id and Token-based Basic Auth on Retrieve Recording Media requests made for recordings in your Plivo account. You can enable Basic Auth for Recording URLs from your Other Voice Settings section of the Plivo console.

    Note: Please note that only account admins (users with the role Admin) have the required privileges to update recording auth preference.