Giter Club home page Giter Club logo

plivo-python's Introduction

plivo-python

UnitTests PyPI PyPI codecov PyPI

The Plivo Python SDK makes it simpler to integrate communications into your Python applications using the Plivo REST API. Using the SDK, you will be able to make voice calls, send SMS and generate Plivo XML to control your call flows.

Installation

Install the SDK using pip

pip install plivo

If you have the 0.11.3 version (a.k.a legacy) already installed, you will have to first uninstall it before installing the new version. pip install --upgrade plivo might not work depending on your system status.

Alternatively, you can download the source code from this repo(master branch) and run

python setup.py install

For features in beta, use the beta branch:

pip install plivo==4.2.0b1

Alternatively, you can download the source code from this repo(beta branch) 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.

Getting started

Authentication

To make the API requests, you need to create a RestClient and provide it with authentication credentials (which can be found at https://manage.plivo.com/dashboard/).

We recommend that you store your credentials in the PLIVO_AUTH_ID and the PLIVO_AUTH_TOKEN environment variables, so as to avoid the possibility of accidentally committing them to source control. If you do this, you can initialise the client with no arguments and it will automatically fetch them from the environment variables:

import plivo

client = plivo.RestClient()

Alternatively, you can specifiy the authentication credentials while initializing the RestClient.

import plivo

client = plivo.RestClient(auth_id='your_auth_id', auth_token='your_auth_token')

If you expect to make a large number of API requests, re-use the same client instance, but if you expect to create a client on an on-demand basis, you can use a context manager to automatically frees all resources used by the client

import plivo

with plivo.RestClient() as client:
  pass # Do something with the client

The basics

The SDK uses consistent interfaces to create, retrieve, update, delete and list resources. The pattern followed is as follows:

client.resources.create(*args, **kwargs) # Create
client.resources.get(id=resource_identifier) # Get
client.resources.update(id=resource_identifier, *args, **kwargs) # Update
client.resources.delete(id=resource_identifier) # Delete
client.resources.list() # List all resources, max 20 at a time

You can also use the resource directly to update and delete it. For example,

resource = client.resources.get(id=resource_identifier)
resource.update(*args, **kwargs) # update the resource
resource.delete() # Delete the resource

Also, using client.resources.list() would list the first 20 resources by default (which is the first page, with limit as 20, and offset as 0). To get more, you will have to use limit and offset to get the second page of resources.

To list all resources, you can simply use the following pattern that will handle the pagination for you automatically, so you won't have to worry about passing the right limit and offset values.

for resource in client.resources:
    print(resource.id)

Examples

Send a message

import plivo

client = plivo.RestClient()
message_created = client.messages.create(
    src='the_source_number',
    dst='the_destination_number',
    text='Hello, world!'
)

Make a call

import plivo

client = plivo.RestClient()
call_made = client.calls.create(
    from_='the_from_number',
    to_='the_to_number',
    answer_url='https://answer.url'
)

Lookup a number

import plivo

client = plivo.RestClient(auth_id='', auth_token='')
resp = client.lookup.get("<insert-number-here>")
print(resp)

Generate Plivo XML

from plivo import plivoxml

xml_response = plivoxml.ResponseElement()
xml_response.add_speak('Hello, world!') # or add(plivoxml.SpeakElement(text))

print(xml_response.to_string())

This generates the following XML:

<Response>
  <Speak>Hello, world!</Speak>
</Response>

Run a PHLO

import plivo

auth_id = '<auth_id>'
auth_token = '<auth_token>'
phlo_id = '<phlo_id' # https://console.plivo.com/phlo/list/
phlo_client = plivo.phlo.RestClient(auth_id=auth_id, auth_token=auth_token)
phlo = phlo_client.phlo.get(phlo_id)
response = phlo.run()
print(response)

WhatsApp Messaging

Plivo's WhatsApp API allows you to send different types of messages over WhatsApp, including templated messages, free form messages and interactive messages. Below are some examples on how to use the Plivo Go SDK to send these types of messages.

Templated Messages

Templated messages are a crucial to your WhatsApp messaging experience, as businesses can only initiate WhatsApp conversation with their customers using templated messages.

WhatsApp templates support 4 components: header , body, footer and button. At the point of sending messages, the template object you see in the code acts as a way to pass the dynamic values within these components. header can accomodate text or media (images, video, documents) content. body can accomodate text content. button can support dynamic values in a url button or to specify a developer-defined payload which will be returned when the WhatsApp user clicks on the quick_reply button. footer cannot have any dynamic variables.

Example:

import plivo
from plivo.utils.template import Template

client = plivo.RestClient('<auth_id>','<auth_token>')

template=Template(**{ 
            "name": "template_name",
            "language": "en_US",
            "components": [
                {
                    "type": "header",
                    "parameters": [
                        {
                            "type": "media",
                            "media": "https://xyz.com/s3/img.jpg"
                        }
                    ]
                },
                {
                    "type": "body",
                    "parameters": [
                        {
                            "type": "text",
                            "text": "WA-Text"
                        }
                    ]
                }
            ]
          }
       )
response = client.messages.create(   
        src="the_from_number",
        dst="the_to_number",
        type_="whatsapp",
        template=template,
        url="https://foo.com/wa_status/"
    )
print(response)

Free Form Messages

Non-templated or Free Form WhatsApp messages can be sent as a reply to a user-initiated conversation (Service conversation) or if there is an existing ongoing conversation created previously by sending a templated WhatsApp message.

Free Form Text Message

Example:

import plivo
client = plivo.RestClient('<auth_id>','<auth_token>')
response = client.messages.create(
         src="the_from_number",
         dst="the_to_number",
         type_="whatsapp",
         text="Hello, from Python!"
       )
print(response)

Free Form Media Message

Example:

import plivo
client = plivo.RestClient('<auth_id>','<auth_token>')
response = client.messages.create(
         src="the_from_number",
         dst="the_to_number",
         type_="whatsapp",
         text="whatsapp_video",
         media_urls=["https://sample-videos.com/img/Sample-png-image-1mb.png"]
        )
print(response)

Interactive Messages

This guide shows how to send non-templated interactive messages to recipients using Plivo’s APIs.

Quick Reply Buttons

Quick reply buttons allow customers to quickly respond to your message with predefined options.

Example:

import plivo
from plivo.utils.interactive import Interactive

client = plivo.RestClient('<auth_id>','<auth_token>')

interactive=Interactive(**{
        "type": "button",
        "header": {
            "type": "media",
            "media": "https://xyz.com/s3/img.jpg"
        },
        "body": {
            "text": "Make your selection"
        },
        "action": {
            "buttons": [
                {
                    "title": "Click here",
                    "id": "bt1"
                },
                {
                    "title": "Know More",
                    "id": "bt2"
                },
                {
                    "title": "Request Callback",
                    "id": "bt3"
                }
            ]
        }
    })

response= client.messages.create(
    src="the_from_number",
    dst="the_to_number",
    type_="whatsapp",
    interactive=interactive
)
print(response)

Interactive Lists

Interactive lists allow you to present customers with a list of options.

Example:

import plivo
from plivo.utils.interactive import Interactive

client = plivo.RestClient('<auth_id>','<auth_token>')

interactive=Interactive(**{
        "type": "list",
        "header": {
            "type": "text",
            "text": "Welcome to Plivo"
        },
        "body": {
            "text": "You can review the list of rewards we offer"
        },
        "footer": {
            "text": "Yours Truly"
        },
        "action": {
            "buttons": [{
                "title": "Click here"
            }],
            "sections": [
                {
                    "title": "SECTION_1_TITLE",
                    "rows": [
                        {
                            "id": "SECTION_1_ROW_1_ID",
                            "title": "SECTION_1_ROW_1_TITLE",
                            "description": "SECTION_1_ROW_1_DESCRIPTION"
                        },
                        {
                            "id": "SECTION_1_ROW_2_ID",
                            "title": "SECTION_1_ROW_2_TITLE",
                            "description": "SECTION_1_ROW_2_DESCRIPTION"
                        }
                    ]
                },
                {
                    "title": "SECTION_2_TITLE",
                    "rows": [
                        {
                            "id": "SECTION_2_ROW_1_ID",
                            "title": "SECTION_2_ROW_1_TITLE",
                            "description": "SECTION_2_ROW_1_DESCRIPTION"
                        },
                        {
                            "id": "SECTION_2_ROW_2_ID",
                            "title": "SECTION_2_ROW_2_TITLE",
                            "description": "SECTION_2_ROW_2_DESCRIPTION"
                        }
                    ]
                }
            ]
        }
    })

response= client.messages.create(
    src="the_from_number",
    dst="the_to_number",
    type_="whatsapp",
    interactive=interactive
)
print(response)

Interactive CTA URLs

CTA URL messages allow you to send links and call-to-action buttons.

Example:

import plivo
from plivo.utils.interactive import Interactive

client = plivo.RestClient('<auth_id>','<auth_token>')

interactive=Interactive(**{
        "type": "cta_url",
        "header": {
            "type": "media",
            "media": "https://xyz.com/s3/img.jpg"
        },
        "body": {
            "text": "Know More"
        },
        "footer": {
            "text": "Plivo"
        },
        "action": {
            "buttons": [
                {
                    "title": "Click here",
                    "cta_url": "https:plivo.com"
                }
            ]
        }
    })

response= client.messages.create(
    src="the_from_number",
    dst="the_to_number",
    type_="whatsapp",
    interactive=interactive
)
print(response)

Location Messages

This guide shows how to send templated and non-templated location messages to recipients using Plivo’s APIs.

Templated Location Messages

Example:

import plivo
from plivo.utils.template import Template

client = plivo.RestClient('<auth_id>','<auth_token>')

template=Template(**{
        "name": "plivo_order_pickup",
        "language": "en_US",
        "components": [
            {
                "type": "header",
                "parameters": [
                    {
                        "type": "location",
                        "location": {
                            "longitude": "122.148981",
                            "latitude": "37.483307",
                            "name": "Pablo Morales",
                            "address": "1 Hacker Way, Menlo Park, CA 94025"
                        }
                    }
                ]
            }
        ]
    })

response= client.messages.create(
    src="the_from_number",
    dst="the_to_number",
    type_="whatsapp",
    template=template
)
print(response)

Non-Templated Location Messages

Example:

import plivo
from plivo.utils.location import Location

client = plivo.RestClient('<auth_id>','<auth_token>')

location=Location(**{
        "longitude": "122.148981",
        "latitude": "37.483307",
        "name": "Pablo Morales",
        "address": "1 Hacker Way, Menlo Park, CA 94025"
    })

response= client.messages.create(
    src="the_from_number",
    dst="the_to_number",
    type_="whatsapp",
    location=location
)
print(response)

More examples

Refer to the Plivo API Reference for more examples. Also refer to the guide to setting up dev environment on Plivo Developers Portal to setup a Flask server & use it to test out your integration in under 5 minutes. to get started with Plivo.

Reporting issues

Report any feedback or problems with this version by opening an issue on Github.

plivo-python's People

Contributors

abhishek-plivo avatar abinaya-shunmugavel avatar abrolnalin avatar ajay-kg avatar ajay-plivo avatar anukul avatar ashutoshkumar-plivo avatar huzaif-plivo avatar kalyan-plivo avatar kanishka2104 avatar kaushikdas-plivo avatar koushik-ayila avatar kritarth-plivo avatar kunal-plivo avatar lsaitharun avatar manas-plivo avatar manjunath-plivo avatar mohsin-plivo avatar narayana-plivo avatar nikhil-plivo avatar nirmitijain avatar nixonsam avatar ppai-plivo avatar rajneeshkatkam-plivo avatar ramey-plivo avatar renoldthomas-plivo avatar saurabhnewatiya-plivo avatar shubham-plivo avatar sreyantha-plivo avatar varshit97plivo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plivo-python's Issues

Campaign resource does not appear to support limit or offset

The docs say:

"To list all resources, you can simply use the following pattern that will handle the pagination for you automatically, so you won't have to worry about passing the right limit and offset values."

for resource in client.resources:
    print(resource.id)

However, when we try this with the campaign resource with this code:

import plivo

auth_id = '*************'
auth_token = '*********************'

def main():
    client = plivo.RestClient(auth_id=auth_id, auth_token=auth_token)
    for resource in client.campaign:
        print(resource)
        
main()

We get the following error:

Traceback (most recent call last):
  File "/home/krypterro/PyApps/cbplivo/get_campaigns_test.py", line 13, in <module>
    main()
  File "/home/krypterro/PyApps/cbplivo/get_campaigns_test.py", line 10, in main
    for resource in client.campaign:
  File "/home/krypterro/PyApps/cbplivo/.venv/lib/python3.8/site-packages/plivo/base.py", line 238, in gen
    response = self.list(limit=limit, offset=offset)
TypeError: list() got an unexpected keyword argument 'limit'

Does the campaign resource not support limit and/or offset, or are we doing something wrong here?

[Question] No module named plivo

Exception has occurred: ModuleNotFoundError

No module named 'plivo'
  File "$USER/sample/mypythonapp/trigger_phlo.py", line 1, in <module>
    import plivo

Very first line tells me the above, but when pip3.9 list:

(.venv) pip3.9 list
plivo             4.15.2

Any facing the face issue? Thank you

I'm having an issue installing Plivo

i'm having a problem installing it and i'm getting this error:


Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?


error: command 'arm-linux-gnueabihf-gcc' failed with exit status 1


Command "/usr/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-GVzrek/lxml/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-S_g0er-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /tmp/pip-build-GVzrek/lxml/

Hope you can help

Fix failing tests

  1. Fix failing travis CI builds due to --use-mirrors
  2. Tests currently need real Auth credentials to work. Come up with infrastructure to do this or use mock tests.

digitsMatchBLeg parameter doesnt work for addDial | invalid attribute digitsMatchBLeg for Dial

when tried to use digitsMatchBLeg parameter for addDial method, it shows error:

invalid attribute digitsMatchBLeg for Dial

PlivoError at /plivotest/ivr-answer/
invalid attribute digitsMatchBLeg for Dial
Request Method: POST
Request URL: http://subdomain.ngrok.io/plivotest/ivr-answer/
Django Version: 1.9.5
Exception Type: PlivoError
Exception Value: invalid attribute digitsMatchBLeg for Dial
Exception Location: myvirtualenv/local/lib/python2.7/site-packages/plivoxml.py in init, line 18
Python Executable: myvirtualenv/bin/python2
Python Version: 2.7.13

to use this parameter, I had to construct the Dial response xml on myself

AttributeError: module 'plivo' has no attribute 'RestAPI' + module 'plivo' has no attribute 'Client'

I am trying to use Plivo for an URGENT prototype and I am getting the following error messages related to Plivo libraries

(1) AttributeError: module 'plivo' has no attribute 'RestAPI'
(2) AttributeError: module 'plivo' has no attribute 'Client'

HERE IS HOW I GET ERROR (1)

at python3 console

import plivo

auth_id = 'xxxx'
auth_token = 'xxxxx'
p = plivo.RestAPI(auth_id, auth_token)
Traceback (most recent call last):
File "", line 1, in
AttributeError: module 'plivo' has no attribute 'RestAPI'

HERE IS HOW I GET ERROR (2)

def usePlivo(msg, dst):
client = plivo.Client('xxxxx', 'xxxx')
try:
response = client.messages.create(
src= '16132222222',
dst= dst,
text= msg,
)
print(response.dict)
except plivo.exceptions.PlivoRestError as e:
print(e)
return;

usePlivo(msg, dst)
Traceback (most recent call last):
File "", line 1, in
File "", line 2, in usePlivo
AttributeError: module 'plivo' has no attribute 'Client'

ADDITIONAL INFO

Running python3 in a venv

dir (plivo)
['RestClient', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'base', 'exceptions', 'plivoxml', 'resources', 'rest', 'utils', 'version', 'xml']

print (plivo.file)
/home/clout/repo/emily/env/lib/python3.5/site-packages/plivo/init.py

contents of version.py
version = '4.1.3'

contents of version init.py
from . import exceptions
from .rest import Client as RestClient
from . import xml as plivoxml

(env) clout@tubu:~/repo/emily$ pip install plivo
Requirement already satisfied: plivo in ./env/lib/python3.5/site-packages (4.1.3)
Requirement already satisfied: decorator<5,>=4 in ./env/lib/python3.5/site-packages (from plivo) (4.3.0)
Requirement already satisfied: six<2,>=1 in ./env/lib/python3.5/site-packages (from plivo) (1.11.0)
Requirement already satisfied: lxml<5,>=3 in ./env/lib/python3.5/site-packages (from plivo) (4.2.5)
Requirement already satisfied: requests<3,>=2 in ./env/lib/python3.5/site-packages (from plivo) (2.19.1)
Requirement already satisfied: idna<2.8,>=2.5 in ./env/lib/python3.5/site-packages (from requests<3,>=2->plivo) (2.7)
Requirement already satisfied: urllib3<1.24,>=1.21.1 in ./env/lib/python3.5/site-packages (from requests<3,>=2->plivo) (1.23)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in ./env/lib/python3.5/site-packages (from requests<3,>=2->plivo) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in ./env/lib/python3.5/site-packages (from requests<3,>=2->plivo) (2018.8.24)

Your help will be appreciated!

Thank you

How to get call_uuid from a call placed

Hi,

I have the following code and it works fine.

client = plivo.RestClient('**', '**')
call_made = client.calls.create( from_ = '**', to_ = '**', answer_url = 'http://s3.amazonaws.com/static.plivo.com/answer.xml', answer_method = 'GET',)

I checked this link (https://www.plivo.com/docs/getting-started/get-details-of-a-single-call/) and other links. However I was unable to understand how on line 9 ('call_uuid': '55309cee-821d-11e4-9a73-498d468c930b) the author was able to get the value for call_uuid ?? How in the first place should one be able to get that value?

Support for python3

I did some minor changes to plivoxml so it could run on python3. Would that be useful?

plivoxml bug after moving from Python2 to Python3

The PlivoXMLElement.py module is attempting to decode a __proxy__ object in Python 3, which is not allowed.

The __proxy__ object is used by Django to provide translations and lazy evaluation of strings. In Python 3, strings are Unicode by default, so you shouldn't need to call decode() on them.

python2: (works)
<class 'django.utils.functional.__proxy__'>

python3: (breaks)
<class 'django.utils.functional.lazy.<locals>.__proxy__'>

Error log:

  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/plivo/xml/PlivoXMLElement.py", line 39, in _to_element
    e.text = self.content.decode()
AttributeError: '__proxy__' object has no attribute 'decode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = get_response(request)
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/share/newfies/plivo_cloud/views.py", line 727, in app_answer_handler
    return HttpResponse(xml_response.to_string(), content_type='application/xml')
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/plivo/xml/PlivoXMLElement.py", line 26, in to_string
    s = self.continue_speak(etree.tostring(self._to_element(), pretty_print=pretty, encoding='unicode'))
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/plivo/xml/PlivoXMLElement.py", line 43, in _to_element
    child._to_element(parent=e)
  File "/usr/share/virtualenvs/max/lib/python3.5/site-packages/plivo/xml/PlivoXMLElement.py", line 41, in _to_element
    e.text = self.content
  File "src/lxml/etree.pyx", line 1042, in lxml.etree._Element.text.__set__
  File "src/lxml/apihelpers.pxi", line 748, in lxml.etree._setNodeText
  File "src/lxml/apihelpers.pxi", line 736, in lxml.etree._createTextNode
  File "src/lxml/apihelpers.pxi", line 1539, in lxml.etree._utf8
TypeError: Argument must be bytes or unicode, got '__proxy__' 

Plivo is not supporting pip3

Command "/usr/local/opt/python/bin/python3.7 -u -c "import setuptools, tokenize;file='/private/var/folders/fc/lcypm16j63gddb7mq3s15x_00000gn/T/pip-install-ygunk1h4/lxml/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/fc/lcypm16j63gddb7mq3s15x_00000gn/T/pip-record-04fedc8b/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/fc/lcypm16j63gddb7mq3s15x_00000gn/T/pip-install-ygunk1h4/lxml/

screen shot 2018-08-23 at 5 40 10 pm

Can't make a call. | Received status code 403 for the HTTP method "POST"

Hello I'm getting this error
File "C:\Users\crike\AppData\Local\Programs\Python\Python310\lib\site-packages\plivo\rest\client.py", line 201, in process_response raise PlivoRestError( plivo.exceptions.PlivoRestError: Received status code 403 for the HTTP method "POST"
This is my code:
response = Client.calls.create( from_='+1BOUGHT_NUMBER', to_='+56BMY_NUMBER', answer_url='https://s3.amazonaws.com/static.plivo.com/answer.xml', answer_method='GET', ) print(response)

AttributeError: 'module' object has no attribute 'RestClient'

Using the example code:

import plivo

client = plivo.RestClient('xxxx', 'yyyy')
try:
  response = client.messages.create(
    src='1630zzzzzzzz',
    dst='1630qqqqqqq',
    text='Hello, world!',
  )
  print(response.__dict__)
except plivo.exceptions.PlivoRestError as e:
    print(e)

receive:

Traceback (most recent call last):
  File "plivo.py", line 1, in <module>
    import plivo
  File "/home/gio/plivo.py", line 3, in <module>
    client = plivo.RestClient('xxxxxx', 'yyyyyy')
AttributeError: 'module' object has no attribute 'RestClient'

Pretty much a direct copy from your site.

Pilvo.py - Request.post for sms does not handle 401 responses

p.send_message(message_params)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in
p.send_message(message_params)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/plivo.py", line 496, in send_message
return self._request('POST', '/Message/', data=params)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/plivo.py", line 78, in _request
response = json.loads(content)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/init.py", line 312, in loads
s.class.name))
TypeError: the JSON object must be str, not 'bytes'

Add Python 3.9 support

Remove base64.encodestring() and base64.decodestring() aliases, deprecated since Python 3.1 https://bugs.python.org/issue39351

Error traceback

File "C:\dev\venv\lib\site-packages\plivo\__init__.py", line 3, in <module>
  from .rest import Client as RestClient
File "C:\dev\venv\lib\site-packages\plivo\rest\__init__.py", line 2, in <module>
  from .client import Client
File "C:\dev\venv\lib\site-packages\plivo\rest\client.py", line 14, in <module>
  from plivo.resources import (Accounts, Addresses, Applications, Calls,
File "C:\dev\venv\lib\site-packages\plivo\resources\__init__.py", line 2, in <module>
  from .accounts import Accounts, Subaccounts
File "C:\dev\venv\lib\site-packages\plivo\resources\accounts.py", line 9, in <module>
  from plivo.utils import to_param_dict
File "C:\dev\venv\lib\site-packages\plivo\utils\__init__.py", line 6, in <module>
  from base64 import encodestring
ImportError: cannot import name 'encodestring' from 'base64' (C:\Python39\lib\base64.py)

Mismatch between setup.py and requirements.txt for pyjwt lib

The setup.py file specifies: 'PyJWT==1.7.1'
The requirements.txt specifies: PyJWT==2.1.0

This is creating problems with other libraries that have moved to pyjwt 2.0 and no longer support earlier versions.
Was this intentional and is there an expected time when pyjwt >= 2.0 will be supported?

How to create a call and add stream audio programmatically?

Hi,

I'm looking for an example to:

  1. Create a call
  2. Stream audio

From the docs, it seems plivo takes in an answer_url to create a call and for creating a stream I need call_uuid. But since I'm already creating a call, I'm not getting any call_uuid. Below is what I've tried as of now:

async def make_call():
    plivo_client = plivo.RestClient('auth_id', 'auth_token')
    response = plivo_client.calls.create(
        from_='from_number',
        to_='to_number',
        answer_url=f"{app_callback_url}/plivo_callback?ws_url={websocket_url}",
        answer_method='POST')


@app.post('/plivo_callback')
async plivo_callback(request: Request, ws_url: str, CallUUID: str):
    websocket_plivo_route = f'{ws_url}/ws/'
    response = plivo_client.calls.start_stream(call_uuid=CallUUID,
                                         service_url=websocket_plivo_route, bidirectional=True)

I have a server running and listening to /ws/ websocket endpoint.

The initial call get created with the response:

{'api_id': '34e56af1-739d-4b54-9861-613a2db7546d',
 'message': 'call queued',
 'request_uuid': '1b08512d-3fff-4b4d-ada2-c956cdaa70b1'}

And I get Exception occurred in plivo_callback: Stream consumed as the exception and the call gets disconnected shortly.

Call drops immediately; cannot hear the message

Hi,

I've been trying to work with Pivlo and a Raspberry Pi 4 B model. Using the code below, I was able to receive a phone call. However, the call dropped immediately and i couldn't hear the message. Bulks calls are also not working.

It would be really appreciated if you'd update the documentation on the website - there's a lot of confusing regarding RestAPI and RestClient.

`import plivo

client = plivo.RestClient(auth_id='XXX',auth_token='XXX')

call_made = client.calls.create(
    from_='XXX',
    to_='XXX',
    answer_url='https://s3.amazonaws.com/static.plivo.com/answer.xml'
    )`

TypeError when listing all endpoints

Server SDK should handle pagination automatically.
Code snippet:

with plivo.RestClient(auth_id = auth_id, auth_token = auth_token) as client:
    for e in client.endpoints:
        print e['_name']

Result is traceback:

TypeError                                 
Traceback (most recent call last)
<ipython-input-5-7acc734a5550> in <module>()
      1 with plivo.RestClient(auth_id = auth_id, auth_token = auth_token) as client:
----> 2     for e in client.endpoints:
      3         print e['_name']

~/venv/local/lib/python2.7/site-packages/plivo/base.pyc in gen()
    216             offset = 0
    217             while True:
--> 218                 response = self.list(limit=limit, offset=offset)
    219                 if not response.objects:
    220                     return

TypeError: list() got an unexpected keyword argument 'limit'

Not sure what i'm doing wrong

Hi thanks for sorting out the installation problem I had, I've managed to get it installed properly now.
I've made an account on the dashboard and I have an auth ID and auth token. I created a file called make_calls.py which has the following in:
from plivo import plivoxml

auth_id = ""
auth_token = "
****"

p = plivo.RestAPI(auth_id, auth_token)

params = {
'to': '+44********',
'from' : '1111111111',
'answer_url' : "https://s3.amazonaws.com/static.plivo.com/answer.xml",
'answer_method' : "GET",
}

response = p.make_call(params)
print str(response)


But i'm not sure what I need to do to get this to work? Do you mind explaining step by step and how to do it as I've never really done anything like this before and am struggling to understand what I'm required to do to get Plivo to work properly :(.

Thanks

Publish this package as a Pure Python Wheel

AFAIK this package does not support Python 3 in its current form and it also doesn't have any C extensions, meaning that it can be distributed as a Pure Python Wheel w/ python setup.py bdist_wheel. This, while not a game-changer, would potentially make builds of the projects relying on this package a tad bit faster.

As a refresher, a wheel is a built package that can be installed without needing to go through the "build" process. Installing wheels is substantially faster for the end user than installing from a source distribution.

Call Recording on live call

how can I get the recorded audio meanwhile the call is on going? I can't find any details for the recording call and get the audio file while the call is on going.

Fix the "Mutable Default Argument"

Most of the calls have this signature:

def get_subaccounts(self, params={}):

This has bug in that params is evluated (and defaulted) only one. So any changes to params will persist between calls.

Please see:

http://stackoverflow.com/questions/2639915/why-the-mutable-default-argument-fix-syntax-is-so-ugly-asks-python-newbie
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values

This shouldn't cause a problem unless you are modifying the params dict. You are doing this at two places:

https://github.com/plivo/plivo-python/blob/master/plivo.py#L177
https://github.com/plivo/plivo-python/blob/master/plivo.py#L173

These should have the the signature:

def get_live_calls(self, params=None):
        if not params: params = {}

search_number

search_numbers and rent_number should be making a call to AvailableNumberGroup, they are making a call to AvailableNumber.

Poor documentation around modifying a PHLO with python

I wish to programmatically update the number I'm forwarding calls and texts to (to rotate an on-call shift).

I am trying to use the PHLO api to get the relevant nodes and update the recipient, however, getting a node in a PHLO requires a node_type and node_id. Nowhere can I find what a valid node_type is, and I am assuming the node_id is the name of the node, but again, I can't find documentation supporting this.

Integer is not accepted as 'content' param for plivoxml.DialElement().add_number() method

Snippet to produce the error:

from plivo import plivoxml
response = plivoxml.ResponseElement()

dial_params = {
            'action': 'action_url',
            'caller_id': 'caller_id',
            'time_limit': 43000,
            'timeout': 100,
            'dial_music': 'real',
            'sip_headers': {},
        }
dial_element = plivoxml.DialElement(**dial_params)
dial_element.add_number(content=number, send_digits='1', send_on_preanswer=None)
response.add(dial_element)
response.to_string()

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<python_base_location>/lib/python2.7/site-packages/plivo/plivoxml.py", line 31, in to_string
    s = etree.tostring(self._to_element(), pretty_print=True)
  File "<python_base_location>/lib/python2.7/site-packages/plivo/plivoxml.py", line 41, in _to_element
    child._to_element(parent=e)
  File "<python_base_location>/lib/python2.7/site-packages/plivo/plivoxml.py", line 41, in _to_element
    child._to_element(parent=e)
  File "<python_base_location>/lib/python2.7/site-packages/plivo/plivoxml.py", line 39, in _to_element
    e.text = self.content
  File "src/lxml/lxml.etree.pyx", line 1031, in lxml.etree._Element.text.__set__ (src/lxml/lxml.etree.c:53677)
  File "src/lxml/apihelpers.pxi", line 715, in lxml.etree._setNodeText (src/lxml/lxml.etree.c:24779)
  File "src/lxml/apihelpers.pxi", line 703, in lxml.etree._createTextNode (src/lxml/lxml.etree.c:24642)
  File "src/lxml/apihelpers.pxi", line 1441, in lxml.etree._utf8 (src/lxml/lxml.etree.c:31836)
TypeError: Argument must be bytes or unicode, got 'int'

On passing str(number), this error does not come up.

'ResponseObject' object has no attribute 'to_string'

I'm following this (https://www.plivo.com/docs/sms/quickstart/python-flask#api-send-your-first-outbound-sms-mms-message) doc for sending SMS. I'm using the exact source code(shared below), which has been mentioned in the doc. But when executing the "send_sms" endpoint, I get the following error.

File "/Users/skm/Documents/Projects/Python/Flask/sms/send_sms.py", line 17, in outbound_sms
    return Response(response.to_string())
                    ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ResponseObject' object has no attribute 'to_string'

Source code -

from flask import Flask, Response
import plivo

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

@app.route('/send_sms/', methods=['GET', 'POST'])
def outbound_sms():
    client = plivo.RestClient('<auth_id>','<auth_token>')
    response = client.messages.create(
    src='<sender_id>',
    dst='<destination_number>',
    text='Hello, from Flask!')
    return Response(response.to_string())

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

I'm using "Python 3.11.4"

dependencies in "requirements.txt"
blinker==1.6.2
certifi==2023.5.7
charset-normalizer==3.2.0
click==8.1.5
decorator==4.4.2
Flask==2.3.2
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
lxml==4.9.3
MarkupSafe==2.1.3
plivo==4.37.0
PyJWT==2.7.0
requests==2.31.0
six==1.16.0
urllib3==2.0.3
Werkzeug==2.3.6

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.