GithubHelp home page GithubHelp logo

twilio / twilio-python Goto Github PK

View Code? Open in Web Editor NEW
1.8K 124.0 688.0 151.19 MB

A Python module for communicating with the Twilio API and generating TwiML.

License: MIT License

Makefile 0.02% Python 99.97% Dockerfile 0.01%
twilio twiml twilio-api

twilio-python's Introduction

twilio-python

Tests PyPI PyPI Learn OSS Contribution in TwilioQuest

Documentation

The documentation for the Twilio API can be found here.

The Python library documentation can be found here.

Versions

twilio-python uses a modified version of Semantic Versioning for all changes. See this document for details.

Supported Python Versions

This library supports the following Python implementations:

  • Python 3.7
  • Python 3.8
  • Python 3.9
  • Python 3.10
  • Python 3.11

Installation

Install from PyPi using pip, a package manager for Python.

pip3 install twilio

If pip install fails on Windows, check the path length of the directory. If it is greater 260 characters then enable Long Paths or choose other shorter location.

Don't have pip installed? Try installing it, by running this from the command line:

curl https://bootstrap.pypa.io/get-pip.py | python

Or, you can download the source code (ZIP) for twilio-python, and then run:

python3 setup.py install

Info If the command line gives you an error message that says Permission Denied, try running the above commands with sudo (e.g., sudo pip3 install twilio).

Test your installation

Try sending yourself an SMS message. Save the following code sample to your computer with a text editor. Be sure to update the account_sid, auth_token, and from_ phone number with values from your Twilio account. The to phone number will be your own mobile phone.

from twilio.rest import Client

# Your Account SID and Auth Token from console.twilio.com
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token  = "your_auth_token"

client = Client(account_sid, auth_token)

message = client.messages.create(
    to="+15558675309",
    from_="+15017250604",
    body="Hello from Python!")

print(message.sid)

Save the file as send_sms.py. In the terminal, cd to the directory containing the file you just saved then run:

python3 send_sms.py

After a brief delay, you will receive the text message on your phone.

Warning It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out How to Set Environment Variables for more information.

Use the helper library

API Credentials

The Twilio client needs your Twilio credentials. You can either pass these directly to the constructor (see the code below) or via environment variables.

Authenticating with Account SID and Auth Token:

from twilio.rest import Client

account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token  = "your_auth_token"
client = Client(account_sid, auth_token)

Authenticating with API Key and API Secret:

from twilio.rest import Client

api_key = "XXXXXXXXXXXXXXXXX"
api_secret = "YYYYYYYYYYYYYYYYYY"
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
client = Client(api_key, api_secret, account_sid)

Alternatively, a Client constructor without these parameters will look for TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN variables inside the current environment.

We suggest storing your credentials as environment variables. Why? You'll never have to worry about committing your credentials and accidentally posting them somewhere public.

from twilio.rest import Client
client = Client()

Specify Region and/or Edge

To take advantage of Twilio's Global Infrastructure, specify the target Region and/or Edge for the client:

from twilio.rest import Client

client = Client(region='au1', edge='sydney')

A Client constructor without these parameters will also look for TWILIO_REGION and TWILIO_EDGE variables inside the current environment.

Alternatively, you may specify the edge and/or region after constructing the Twilio client:

from twilio.rest import Client

client = Client()
client.region = 'au1'
client.edge = 'sydney'

This will result in the hostname transforming from api.twilio.com to api.sydney.au1.twilio.com.

Make a Call

from twilio.rest import Client

account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token  = "your_auth_token"
client = Client(account_sid, auth_token)

call = client.calls.create(to="9991231234",
                           from_="9991231234",
                           url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient")
print(call.sid)

Get data about an existing call

from twilio.rest import Client

account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token  = "your_auth_token"
client = Client(account_sid, auth_token)

call = client.calls.get("CA42ed11f93dc08b952027ffbc406d0868")
print(call.to)

Iterate through records

The library automatically handles paging for you. Collections, such as calls and messages, have list and stream methods that page under the hood. With both list and stream, you can specify the number of records you want to receive (limit) and the maximum size you want each page fetch to be (page_size). The library will then handle the task for you.

list eagerly fetches all records and returns them as a list, whereas stream returns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the page method.

Use the list method

from twilio.rest import Client

account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

for sms in client.messages.list():
  print(sms.to)

Asynchronous API Requests

By default, the Twilio Client will make synchronous requests to the Twilio API. To allow for asynchronous, non-blocking requests, we've included an optional asynchronous HTTP client. When used with the Client and the accompanying *_async methods, requests made to the Twilio API will be performed asynchronously.

from twilio.http.async_http_client import AsyncTwilioHttpClient
from twilio.rest import Client

async def main():
    account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    auth_token  = "your_auth_token"
    http_client = AsyncTwilioHttpClient()
    client = Client(account_sid, auth_token, http_client=http_client)

    message = await client.messages.create_async(to="+12316851234", from_="+15555555555",
                                                 body="Hello there!")

asyncio.run(main())

Enable Debug Logging

Log the API request and response data to the console:

import logging

client = Client(account_sid, auth_token)
logging.basicConfig()
client.http_client.logger.setLevel(logging.INFO)

Log the API request and response data to a file:

import logging

client = Client(account_sid, auth_token)
logging.basicConfig(filename='./log.txt')
client.http_client.logger.setLevel(logging.INFO)

Handling Exceptions

Version 8.x of twilio-python exports an exception class to help you handle exceptions that are specific to Twilio methods. To use it, import TwilioRestException and catch exceptions as follows:

from twilio.rest import Client
from twilio.base.exceptions import TwilioRestException

account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token  = "your_auth_token"
client = Client(account_sid, auth_token)

try:
  message = client.messages.create(to="+12316851234", from_="+15555555555",
                                   body="Hello there!")
except TwilioRestException as e:
  print(e)

Generating TwiML

To control phone calls, your application needs to output TwiML.

Use twilio.twiml.Response to easily create such responses.

from twilio.twiml.voice_response import VoiceResponse

r = VoiceResponse()
r.say("Welcome to twilio!")
print(str(r))
<?xml version="1.0" encoding="utf-8"?>
<Response><Say>Welcome to twilio!</Say></Response>

Other advanced examples

Docker Image

The Dockerfile present in this repository and its respective twilio/twilio-python Docker image are currently used by Twilio for testing purposes only.

Getting help

If you need help installing or using the library, please check the Twilio Support Help Center first, and file a support ticket if you don't find an answer to your question.

If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!

twilio-python's People

Contributors

alexcchan avatar alexpayment avatar childish-sambino avatar cjcodes avatar codejudas avatar dougblack avatar dsyang avatar eshanholtz avatar ftobia avatar gbin avatar ilanbiala avatar jennifermah avatar jingming avatar jmctwilio avatar jvankoten avatar kevinburke avatar kyleconroy avatar mattmakai avatar phalt avatar ragil avatar roguelazer avatar ryanhorn avatar shwetha-manvinkurke avatar skimbrel avatar skyl avatar thinkingserious avatar tiwarishubham635 avatar tmconnors avatar twilio-ci avatar twilio-dx 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  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  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

twilio-python's Issues

Bug in listing open conferences?

Hi, I'm trying to get a list of conferences using the code from the read the docs site:

conferences = client.conferences.list()

is throwing the error:

[Fri Jan 06 18:24:25 2012] [error] conferences = client.conferences.list()
[Fri Jan 06 18:24:25 2012] [error] File "/opt/python2.6/lib/python2.6/site-packages/twilio/rest/resources.py", line 1132, in list
[Fri Jan 06 18:24:25 2012] [error] return self.get_instance(params=params, **kwargs)
[Fri Jan 06 18:24:25 2012] [error] TypeError: get_instance() got an unexpected keyword argument 'params'

Is this expected? I have an active conference?

Any feedback would be greatly appreciated!
Thanks

The actual error message is hard to find

Here is an example error message. The actual error is that the user's credentials are invalid.

r = client.caller_ids.validate("+19255551234",status_callback="http://uncurler.heroku.com/v1/c337ff135ab3833f8ad0fec40218685d")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twilio/rest/resources.py", line 778, in validate
    resp, validation = self.request("POST", self.uri, data=params)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twilio/rest/resources.py", line 216, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twilio/rest/resources.py", line 189, in make_twilio_request
    raise TwilioRestException(resp.status_code, resp.url, message)
twilio.TwilioRestException: HTTP ERROR 401: 20003: Authenticate 
 https://api.twilio.com/2010-04-01/Accounts/AC123/OutgoingCallerIds.json

No SMS Examples in Documentation

I see no SMS examples. My code using version ~2 of this API broke when moving to version 3. I got an "AttributeError -- no module named Account"

Please expand the documentation and provide SMS examples.

Return native datetime objects instead of rfc 2822 dates.

I think it would be more natural and useful for Python users if resource queries retured datetime objects instead of RFC 2822 formatted date strings. I was working with the messages resource recently and my first assumption was that this module did return datetimes. But I found that is not the case while investigating why a date sort was failing.

I asked Kevin about submitting a pull request for this on Twitter and he asked me to post an issue here for discussion because it would be a breaking change.

I can think of a few alternatives to this request that would not break existing functionality. One option would be to return two different dates for each field (like date_sent and datetime_sent for example). That seems kind of messy though.

Another option could be to provide a utility in the module for converting string dates. But the standard library already has a simple utility for this, so that doesn't really help much.

Thanks,
Alex

twilio_api_url is undefined

in twilio/rest/init.py:

    if path[0] == '/':
        uri = _TWILIO_API_URL + path
    else:
        uri = _TWILIO_API_URL + '/' + path

ListResource.count method should take parameters

The ListResouce.count() method should either take parameters, or should be chainable to the list() method.

For example:

client.calls.list(to='+15553331234', ended_before= datetime.date.today()).count()

#or

client.calls.count(to='+15553331234', ended_before= datetime.date.today())

Alternatively (or maybe additionally), the list method should return a custom List object, which would be a Python list with a couple of extra properties that would allow you to access the parameters in the XML response (kind of like a Django Queryset object)

<Calls page="0" numpages="3" pagesize="50" total="147" start="0" end="49" uri="/2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls" firstpageuri="/2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls?Page=0&amp;PageSize=50" previouspageuri="" nextpageuri="/2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls?Page=1&amp;PageSize=50" lastpageuri="/2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls?Page=2&amp;PageSize=50">

errors with unicode in outgoing SMS messages

Sending an SMS text via client.sms.messages.create(to=to_phone, from_=from_phone, body=body), if body is a unicode string and has a non-ascii character, we eventually get:

Exception Type: UnicodeEncodeError
Exception Value:
'ascii' codec can't encode character u'\u2014' in position 71: ordinal not in range(128)
Exception Location: /usr/lib/python2.7/urllib.py in urlencode, line 1282

Moreover, if I encode body to utf-8 before the call, the call succeeds, but the recipient (iPhone 4 running iOS 5.0.1) shows ? in place of the character in question (an em-dash in my test). iOS ordinarily handles such characters OK, at least phone-to-phone.

ssl.SSLError: [Errno 185090050] Problems sending messages

Hi,

I'm experiencing problems sending messages on one of my machines in particular so it may not necessarily be a bug. I'm getting the following trace:

Traceback (most recent call last):
File "notify.py", line 13, in
cd.notifyCheck(testhost, test)
File "/vagrant/cloudydave/CloudyDave.py", line 482, in notifyCheck
body=body)
File "/usr/local/lib/python2.7/site-packages/twilio/rest/resources.py", line 1061, in create
return self.create_instance(params)
File "/usr/local/lib/python2.7/site-packages/twilio/rest/resources.py", line 311, in create_instance
resp, instance = self.request("POST", self.uri, data=body)
File "/usr/local/lib/python2.7/site-packages/twilio/rest/resources.py", line 202, in request
resp = make_twilio_request(method, uri, auth=self.auth, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/twilio/rest/resources.py", line 166, in make_twilio_request
resp = make_request(method, uri, *_kwargs)
File "/usr/local/lib/python2.7/site-packages/twilio/rest/resources.py", line 144, in make_request
resp, content = http.request(url, method, headers=headers, body=data)
File "/usr/local/lib/python2.7/site-packages/twilio/contrib/httplib2/init.py", line 1436, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/local/lib/python2.7/site-packages/twilio/contrib/httplib2/init.py", line 1188, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/local/lib/python2.7/site-packages/twilio/contrib/httplib2/init.py", line 1123, in _conn_request
conn.connect()
File "/usr/local/lib/python2.7/site-packages/twilio/contrib/httplib2/init.py", line 890, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "/usr/local/lib/python2.7/site-packages/twilio/contrib/httplib2/init.py", line 76, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/usr/local/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/local/lib/python2.7/ssl.py", line 141, in init
ciphers)
ssl.SSLError: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

Can someone suggest any next steps to try? It's Debian 6.0.4 with the latest pip.

Cheers

Function names with decorators are not showing up in the documentation

For example, the list method of the Calls resource has a decorator.

This Stackoverflow question has more information:

http://stackoverflow.com/questions/3687046/python-sphinx-autodoc-and-decorated-members

It would also be nice if each list() function included information about how to page through the results. We had a question about it on SO as well: http://stackoverflow.com/questions/8392491/twilio-python-helper-library-how-do-you-know-how-many-pages-list-resource-retu/8392813#8392813

Error when filtering SMS messages via on date_sent.

when I run this code:

Error: get_instances() got an unexpected keyword argument 'date_sent'

i get this error:

messages =client.sms.messages.list(date_sent=date(2011,1,1))

It appears that my version 3.3.3 does not have a date sent filter???

Cannot kick a participant

Traceback (most recent call last):
File "confmanager.py", line 36, in <module>
p.kick()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twilio-3.3.6-py2.7.egg/twilio/rest/resources.py", line 1166, in kick
self.delete_instance()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twilio-3.3.6-py2.7.egg/twilio/rest/resources.py", line 251, in delete_instance
return self.parent.delete(self.name)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twilio-3.3.6-py2.7.egg/twilio/rest/resources.py", line 1209, in delete
return self._delete(call_sid)
AttributeError: 'Participants' object has no attribute '_delete'

My code:

for conf in confs:
age = time.mktime(time.gmtime()) - time.mktime(get_time(conf.date_created))
if age > MAX_CONF_AGE:
print "Terminating conference %s" % conf.sid
#while len(conf.participants.list()) > 0:
p = conf.participants.list().pop()
p.kick()
print "\tDisconnected participant %s" % p.call_sid

print

Phone numbers not updating after purchase

I'm having trouble getting changes to purchased phone numbers to save to twilio. I can purchase the numbers and send sms just fine. After purchasing, I check the site and the sms url is not showing and sending a message from my phone to the number does not execute the callback. I get no error from the purchase/update.

Version I'm using: 3.3.2

Code I'm running:
from django.conf import settings
client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_ACCOUNT_TOKEN)
def buy_phone_number(area_code):
numbers = client.phone_numbers.search(area_code=area_code)
if numbers:
new_number = numbers[0].purchase()
new_number.sms_application_sid = settings.TWILIO_APP_SID
new_number.sms_url = settings.TWILIO_SMS_URL
new_number.update()

If I run the code from the docs, then I get an error that indicates I invalid parameters have been passed.
http://readthedocs.org/docs/twilio-python/en/latest/usage/phone-numbers.html#changing-applications

Code I run:
def buy_phone_number(area_code):
numbers = client.phone_numbers.search(area_code=area_code)
if numbers:
new_number = numbers[0].purchase()
number = client.phone_numbers.update(new_number.sid, application="AP123")

Error I get:
update() got an unexpected keyword argument 'application'
Also fails when I try:
number = client.phone_numbers.update(new_number.sid, sms_application_sid="AP123")
with error: update() got an unexpected keyword argument 'sms_application_sid'

The only way I was able to get the attributes I set to be reflected on twilio.com is by passing the kwargs to purchase().
Thanks to https://github.com/saebyn

Bug in TwiML Verb generation

There is a bug in the init() method of Verb class on line 25 that is stripping valid attributes from the XML output.
https://github.com/twilio/twilio-python/blob/master/twilio/twiml.py

The problem is in this loop of init()

for k, v in kwargs.items():
            if k == "sender":
                k = "from"
            if v:
                self.attrs[k] = v

That second conditional on the "v" variable drops all attributes that are False, 0, or an empty string (''). The Conference verb is supposed to accept both boolean values (for attributes such as beep) and emptry strings for waitUrl
http://www.twilio.com/docs/api/twiml/conference

A more correct implementation is probably something like this:

import types

for k, v in kwargs.items():
            if k == "sender":
                k = "from"
            if type(v) is not types.NoneType:
                self.attrs[k] = v

Here is a unit test that demonstrates the problem:
https://gist.github.com/1320881

Additionally, the Verb.xml() method does not handle booleans correctly. All of the Twilio documentation illustrates booleans being expected in all lower case.

The xml() method however uses the following line to generate attributes:

el.set(a, str(self.attrs[a]))

In Python, this converts True into "True" (not "true").

To produce XML output consistent with the Twilio documentation, you should do something like this:

import types

def xml(self):
        el = ET.Element(self.name)

        keys = self.attrs.keys()
        keys.sort()
        for a in keys:
            value = self.attrs[a]
            if type(value) is bool:
                value = str(value).lower()
            elif type(value) is types.NoneType:
                continue #skip attributes with a value of None
            else:
                value = str(value)
            el.set(a, value)

        if self.body:
            el.text = self.body

        for verb in self.verbs:
            el.append(verb.xml())

        return el

Installing the library on app engine is a pain

furthermore the one example that's really prevalent when you google is using an outdated version of the helper library: http://www.twilio.com/blog/2011/05/how-to-send-twilio-sms-messages-using-python-on-google-app-engine.html

we should provide examples of how to zip up the library and include it in app engine, or how to construct basic auth requests yourself.

Furthermore, for version 4 may be worth making the whole library one file for easier includes.

Setting phone number status callback URL

hey,

kind of a weird thing -- I'm noticing that in the docs for PhoneNumber.purchase(), you can pass in a status_callback_method, but not a status_callback url. Is this an oversight? Kind of useless to set the method w/o setting a url :-)

Thanks, I'm just trying to set up a new phone number with all the right particulars, and this certain part seems off to me.

thanks!

Twilio library for Python 3?

Nowadays it is encouraged to develop in Python 3. The library seems to be for Python 2.x version.

How can I install this library in a system running Python 3?

Syntax error submitting application update

Per the example:

from twilio.rest import TwilioRestClient

conn = TwilioRestClient()
url = "http://www.example.com/twiml.xml"
application = conn.applications.update(app_sid, voice_url=url)

Result

File "/Library/Python/2.6/site-packages/twilio/rest/resources.py", line 1269, in update
"SmsFallbackMethod": sms_fallback_method,
NameError: global name 'sms_fallback_method' is not defined

Secondarily

Once this is corrected, there's a secondary issue:

File "/Library/Python/2.6/site-packages/twilio/rest/resources.py", line 1272, in update
return self.update_instance(params)
TypeError: update_instance() takes exactly 3 arguments (2 given)

Unicode encoding errors

Today I got a error when input French in the class Say(Verb). The French input is something like:

Comme pour la validation nécessaire et d'autres, une instance de modèle doit initialiser toutes les propriétés à des choix afin que l'instance n'est pas créée avec des valeurs non valides.

The error message is followed. It seems twilio-python has burp when handles non-ascii characters. When you have a moment, would please take a look?

Traceback (most recent call last):
File &quot;/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py&quot;, line 636, in __call__
    handler.post(*groups)
File &quot;/base/data/home/apps/testcall/1.349351322484055291/handlers/task.py&quot;, line 302, in post
 self.response.out.write(resp)
File &quot;/base/python_runtime/python_dist/lib/python2.5/StringIO.py&quot;, line 217, in write
s = str(s)
File &quot;/base/data/home/apps/testcall/1.349351322484055291/externals/twilio.py&quot;, line 185, in __repr__
    for l in str(v)[:-1].split('\n'):
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 68: ordinal not in range(128)

Missing status_callback_url parameter on client.phone_numbers.update

The REST client doesn't have a status_callback_url parameter for client.phone_numbers.update(). It does however have a status_callback_method parameter. The method for purchasing a number has this parameter, so this seems like a bug, or at the very least an odd inconsistency.

applications.create() ignores sms_url and sms_method

client = TwilioRestClient(account, token,
                          base, version)

client.applications.create(
    friendly_name = "My SMS Test App2",
    api_version = "2010-04-01",
    sms_url = "http://xx.xx.xx.xx:8080/sms_callback2",
    sms_method = "POST",
    voice_url = "http://xx.xx.xx.xx:8080/sms_callback2",
    voice_method = "POST")

will set the voice_url but not the sms_url.

sms_url and sms_method are missing in params for Applications in twilio/rest/resources.py:

        params = transform_params({
                "FriendlyName": friendly_name,
                "ApiVersion": api_version,
                "VoiceUrl": voice_url,
                "VoiceMethod": voice_method,
                "VoiceFallbackUrl": voice_fallback_url,
                "VoiceFallbackMethod": voice_fallback_method,
                "StatusCallback": status_callback,
                "StatusCallbackMethod": status_callback_method,
                "VoiceCallerIdLookup": voice_caller_id_lookup,
                "SmsFallbackUrl": sms_fallback_url,
                "SmsFallbackMethod": sms_fallback_method,
                "SmsStatusCallback": sms_status_callback,
                })

Adding

                "SmsUrl": sms_url,
                "SmsMethod": sms_method,

fixes the problem.

Small problem in the README

Looks like:

    call = client.calls.make(to="9991231234", from_="9991231234",
                             url="http://foo.com/call.xml")

Should be:

    call = client.calls.create(to="9991231234", from_="9991231234",
                             url="http://foo.com/call.xml")

Define a useful __str__ object

When you print a Resource you get back for example

<twilio.rest.resources.calls.Call object at 0x10f0a40d0>

It would be nice if we iterated the properties of the object when you printed it.

con.html cannot be cloned on Windows

CON is a reserved name on Windows, and con.html can't be created during the git clone. Maybe con.html should be renamed or deleted?

$ git clone https://github.com/twilio/twilio-python
Cloning into twilio-python...
remote: Counting objects: 1008, done.
remote: Compressing objects: 100% (509/509), done.
remote: Total 1008 (delta 564), reused 922 (delta 481)
Receiving objects: 100% (1008/1008), 673.42 KiB | 391 KiB/s, done.
Resolving deltas: 100% (564/564), done.
error: unable to create file docs/tmp/tables/con.html (No such file or directory)
$ cd twilio-python
$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       deleted:    docs/tmp/tables/con.html
#
no changes added to commit (use "git add" and/or "git commit -a")

Tab Characters embedded in SMS Body

Hello,

When creating a response with an sms tag, the repr function splits on newlines and then adds tab characters for 'pretty' XML formatting. The problem is that when there are new lines in SMS responses, these are also replaced by \n\t causing a character error in the text message (on my Verizon android the \t shows up as a ?).

Ideally I'd love to have a str function also that has no newlines or tabs between tags, and includes the xml doctype string such as .

Cheers,
Ben

File tree?

Given the various package issues and versions/platforms of Python, I would like to know the official directory structure for the package/egg. I believe others will as well for quick reference and/or custom workarounds/installations.

'phone_numbers' resource unaccessible when using a subaccount via the master account

I am trying the following:

from twilio.rest import TwilioRestClient

# To find these visit https://www.twilio.com/user/account
ACCOUNT_SID = "ACXXXXXXXX"
AUTH_TOKEN = "YYYYYYYYYYY"
SUBACCOUNT_SID = "ACZZZZZZZZZ"

client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

if SUBACCOUNT_SID:
    client = client.accounts.get(SUBACCOUNT_SID)

for number in client.phone_numbers.iter():
    print number.sid

Which results in the following error: AttributeError: 'Account' object has no attribute 'phone_numbers'

caller_ids also seem to have this problem, but resources like calls, sms.messages and applications do not.

Unicode Encoding Errors on Validating POST Bodies

I've been using Twilio-python for a little while now to process incoming SMS messages to my server. The other day a user tried sending a Russian character and it resulted in a 500 error. The code blew up in the python hmac routine which is called in the compute_signature() method of the util module.

Here's the end of my stack trace:

File "/base/data/home/apps/ssimplylisted-production/0-5-3.353796244180529246/lib/twilio/util.py", line 46, in validate
return self.compute_signature(uri, params) == signature
File "/base/data/home/apps/s
simplylisted-production/0-5-3.353796244180529246/lib/twilio/util.py", line 33, in compute_signature
computed = base64.encodestring(hmac.new(self.token, s, sha1).digest())
File "/base/python_runtime/python_dist/lib/python2.5/hmac.py", line 121, in new
return HMAC(key, msg, digestmod)
File "/base/python_runtime/python_dist/lib/python2.5/hmac.py", line 71, in init
self.update(msg)
File "/base/python_runtime/python_dist/lib/python2.5/hmac.py", line 79, in update
self.inner.update(msg)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 202-203: ordinal not in range(128)

After some quick research, I found that the solution to this problem to prevent the code from blowing up and still ensure that messages pass validation is to add the following line immediately before passing the post body 's' to the hmac method:

s = unicode(s).encode("utf-8")

This correctly converts a unicode string to an ascii bytestring using the utf-8 encoding. I've verified that this fixes the problem.

More informative 'Authenticate' error message

here's the current error message if someone provides incorrect accountsid/password combo:

Traceback (most recent call last):
  File "test_sms.py", line 8, in <module>
    body="Hello there!")
  File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/twilio/rest/resources.py", line 1022, in create
    return self.create_instance(params)
  File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/twilio/rest/resources.py", line 295, in create_instance
    resp, instance = self.request("POST", self.uri, data=body)
  File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/twilio/rest/resources.py", line 195, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/twilio/rest/resources.py", line 168, in make_twilio_request
    raise TwilioRestException(resp.status_code, resp.url, message)
twilio.TwilioRestException: HTTP ERROR 401: 20003: Authenticate 
 https://api.twilio.com/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXX/SMS/Messages.json

It would be great if we could provide some more context or a more informative message here.

Number transfer misnamed and not working

The number transfer method appears to be misspelled ("trasfer") and does not appear to be working.

Reported by GetSatisfaction user here:

http://getsatisfaction.com/twilio/topics/number_transfer_implementation_missing_in_twilio_python?do=reply&amp;utm_content=reply_link&amp;utm_medium=email&amp;utm_source=new_topic

Quoted from ticket:

"The implementation for transferring numbers in the official Python Twilio Helper library is missing. The function exists (named "trasfer" [sic]) in both the PhoneNumber and PhoneNumbers classes, however, calling it in the PhoneNumber class will do nothing and the PhoneNumbers.trasfer will through an exception.

If you guys could please implement this, it would be much appreciated. I can do it without the library, but it makes it much easier to use it."

I've reproduced the issue on my testbench.

Resource objects should support json.dumps

Or, some kind of object.to_json() method which would give you the original JSON. Right now trying to make a server-side API request and just pass through the JSON response is difficult, without resorting to Requests or similar.

It would also be nice if printing a message returned its JSON representation. Right now you get

>>>> msg = client.sms.messages.get('SM123')
>>>> msg
<twilio.rest.resources.SmsMessage at 0x101fa6a90>

Which doesn't tell you much at a glance.

Should be able to dequeue an individual Member instance

As I understand the only way to do so is to get the member's sid, then call dequeue on the queue_members resource. As you are usually iterating over the members like

for member in queue.queue_members:
    # do something

it makes sense to call actions directly on that member object.

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.