twilio / twilio-python Goto Github PK
View Code? Open in Web Editor NEWA Python module for communicating with the Twilio API and generating TwiML.
License: MIT License
A Python module for communicating with the Twilio API and generating TwiML.
License: MIT License
The really long method params feel like a smell to me.
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&PageSize=50" previouspageuri="" nextpageuri="/2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls?Page=1&PageSize=50" lastpageuri="/2010-04-01/Accounts/AC5ef877a5fe4238be081ea6f3c44186f3/Calls?Page=2&PageSize=50">
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?
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???
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.
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.
Saw this happen again today, and it's really confusing when it does happen. Example: http://stackoverflow.com/questions/8887927/import-error-in-twilio
Possible solutions:
import Twilio
(would that even work?)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.
The number transfer method appears to be misspelled ("trasfer") and does not appear to be working.
Reported by GetSatisfaction user here:
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.
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
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)
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
Can you give an example of how to query the details for a specific phone number with "class twilio.rest.resources.PhoneNumber(parent, sid)"?
I'm not sure what 'parent' should be.
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.
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
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
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
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!
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
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
For instance, test_get
is redefined in test_notifications, so a case with a typo that would cause an error is getting discarded:
twilio-python/tests/test_notifications.py
Line 32 in ab2f5d7
there is another like this (sans typo) in test_recordings.
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.
http://readthedocs.org/docs/twilio-python/en/latest/usage/token-generation.html
TwilioCability -> TwilioCapability
When validating a new caller id, I am not able to specify a status callback url. It's listed as an optional parameter here: http://www.twilio.com/docs/api/rest/outgoing-caller-ids
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.
making a note for myself
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 validatesimplylisted-production/0-5-3.353796244180529246/lib/twilio/util.py", line 33, in compute_signature
return self.compute_signature(uri, params) == signature
File "/base/data/home/apps/s
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.
The only nouns that are supported in are and
It would be great to add support for as well so this library could be used to construct TwiML used for Twilio Client applications.
When the library returns a 400 the error message should include a link to the twilio site, which has a more informative error message.
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.
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")
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")
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.
in twilio/rest/init.py:
if path[0] == '/':
uri = _TWILIO_API_URL + path
else:
uri = _TWILIO_API_URL + '/' + path
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 "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__
handler.post(*groups)
File "/base/data/home/apps/testcall/1.349351322484055291/handlers/task.py", line 302, in post
self.response.out.write(resp)
File "/base/python_runtime/python_dist/lib/python2.5/StringIO.py", line 217, in write
s = str(s)
File "/base/data/home/apps/testcall/1.349351322484055291/externals/twilio.py", 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)
I tried just putting the @normalize_dates decorator above the iter() method and all of the tests pass, which indicates we probably need better test coverage for this case. I don't believe any other changes would be necessary.
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
The code should be flexible, but the documentation thorough.
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.
the code issues:
return self.update(sid, status=Call.CANCELED)
which has no affect on in-progress calls
Document the parameters.
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
Not all method parameters are documented on this page: http://readthedocs.org/docs/twilio-python/en/latest/api/twiml.html#twilio.twiml.Dial
Furthermore verbs like Say could use a little more documentation or a link to the API docs.
The following code should work
from twilio import twiml
r = twiml.Response()
r.say("hello")
with r.gather(finishOnKey=4) as g:
g.say("world")
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.
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.