Forums

Trying to send SMS with Twilio. ConnectionRefusedError: [Errno 111] Connection refused.

I have been trying to send an SMS with Twilio but its not working. It shows this error.

    Traceback (most recent call last):
  File "/home/dhruvsomani/sms.py", line 11, in <module>
    body="Trial is a Trial.",
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/messages.py", line 122, in create
    return self.create_instance(kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 341, in create_instance
    data=transform_params(body))
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 193, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 148, in make_twilio_request
    resp = make_request(method, uri, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 115, in make_request
    resp, content = http.request(url, method, headers=headers, body=data)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1292, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1042, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 966, in _conn_request
    conn.connect()
  File "/usr/lib/python3.4/http/client.py", line 1223, in connect
    super().connect()
  File "/usr/lib/python3.4/http/client.py", line 834, in connect
    self.timeout, self.source_address)
  File "/usr/lib/python3.4/socket.py", line 512, in create_connection
    raise err
  File "/usr/lib/python3.4/socket.py", line 503, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

What should I do? Is this due to the security causes of PythonAnywhere? Please tell me how I should proceed. I am using the lates version of Twilio.

If you're using a free PythonAnywhere account, you'll need to tell the Twilio library to use a proxy. I think the right way to do that is to put code like this in your script, before you try to connect to Twilio:

import os
from urlparse import urlparse
from twilio.rest.resources import Connection
from twilio.rest.resources.connection import PROXY_TYPE_HTTP

host, port = urlparse(os.environ["http_proxy"]).netloc.split(":")
Connection.set_proxy_info(
    host,
    int(port),
    proxy_type=PROXY_TYPE_HTTP,
)

Hello Giles, No, it doesn't work. I pasted the code in my script but it doesn't work. It's still showing the same error.

Traceback (most recent call last):
  File "/home/dhruvsomani/sms.py", line 22, in <module>
    body="Trialing if that's the right word.",
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/messages.py", line 122, in create
    return self.create_instance(kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 341, in create_instance
    data=transform_params(body))
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 193, in request
    resp = make_twilio_request(method, uri, auth=self.auth, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 148, in make_twilio_request
    resp = make_request(method, uri, **kwargs)
  File "/usr/local/lib/python3.4/dist-packages/twilio/rest/resources/base.py", line 115, in make_request
    resp, content = http.request(url, method, headers=headers, body=data)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1292, in request
    (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 1042, in _request
    (response, content) = self._conn_request(conn, request_uri, method, body, headers)
  File "/usr/local/lib/python3.4/dist-packages/httplib2/__init__.py", line 966, in _conn_request
    conn.connect()
  File "/usr/lib/python3.4/http/client.py", line 1223, in connect
    super().connect()
  File "/usr/lib/python3.4/http/client.py", line 834, in connect
    self.timeout, self.source_address)
  File "/usr/lib/python3.4/socket.py", line 512, in create_connection
    raise err
  File "/usr/lib/python3.4/socket.py", line 503, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

That's odd. Can I take a look at your code? We can see it from our side, but always ask permission first.

Hello Giles, Be my guest.

I don't see the proxy stuff in there right now -- perhaps you removed it after trying it? It would be good to see it in place, though.

I've added it again.

Could you try moving it above the line where you create the TwilioRestClient object?

I've moved it above the line. But still the error.

That's really odd. What do you get if you put

print(repr(Connection.proxy_info()))

...just before the creation of the TwilioRestClient, after the proxy setup code?

<httplib2.ProxyInfo object at 0x7f0f32432710>

Sorry, I though that the repr for the proxy_info would be a little more helpful. Could you try again, but with this code to print out the fields separately:

print(Connection.proxy_info().proxy_type)
print(Connection.proxy_info().proxy_host)
print(Connection.proxy_info().proxy_port)
print(Connection.proxy_info().proxy_rdns)
print(Connection.proxy_info().proxy_user)
print(Connection.proxy_info().proxy_pass)

3 proxy.server 3128 None None None

Here it is.

Interesting. Could you try upgrading httplib2 for your account? To do that, run this from a Bash console:

pip3.4 install --user --upgrade httplib2

[edit] added Python version to pip command.

Requirement already up-to-date: httplib2 in ./.local/lib/python2.7/site-packages

Did you use pip3.4? (My initial post omitted the version number, I updated it almost immediately but if you were working from the notification email from the forum you wouldn't have seen it.)

I was using pip 8.1.1 from /home/dhruvsomani/.local/lib/python2.7/site-packages (python 2.7)

Sorry, I just upgraded it.

But the error's still there.

This is really odd. It's just ignoring the proxy completely. Perhaps we can try upgrading the Twilio package? Run this from a bash console:

pip3.4 install --user --upgrade twilio

No Giles, that doesn't work.

What output do you get from

pip3.4 show twilio

...?

Here:

Metadata-Version: 2.0
Name: twilio
Version: 5.4.0
Summary: Twilio API client and TwiML generator
Home-page: https://github.com/twilio/twilio-python/
Author: Twilio
Author-email: help@twilio.com
Installer: pip
License: UNKNOWN
Location: /home/dhruvsomani/.local/lib/python3.4/site-packages
Requires: httplib2, six, pytz, pysocks
Classifiers:
  Development Status :: 5 - Production/Stable
  Intended Audience :: Developers
  License :: OSI Approved :: MIT License
  Operating System :: OS Independent
  Programming Language :: Python
  Programming Language :: Python :: 2.5
  Programming Language :: Python :: 2.6
  Programming Language :: Python :: 2.7
  Programming Language :: Python :: 3.2
  Programming Language :: Python :: 3.3
  Programming Language :: Python :: 3.4
  Programming Language :: Python :: 3.5
  Topic :: Software Development :: Libraries :: Python Modules
  Topic :: Communications :: Telephony

Should I try entering a proxy_user and password? http://twilio-python.readthedocs.org/en/latest/usage/basics.html#proxies

I tried it but it doesn't work even after that.

No, that shouldn't be necessary -- our proxy doesn't need either.

What happens if you try doing

curl http://www.google.com/

...from a Bash console?

<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and m ore. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/logos/doodles/2016/doodle-4-google-2016-us-winner-5664555055185920-hp.jpg" itemprop="image"><meta content="http://www.google.com/logos/doodles/2016/doodle-4-google-2016-us-winner-5664555055185920-thp.png" property="og:image">###DELETED### </script></div></body></html>17:59 ~ $

It shows the source code I think. I've deleted some of it.

OK, so the proxy is definitely working for you. But the Twilio library is inexplicably ignoring it and trying to connect directly to their servers.

Hmm.

Is your code compatible with Python 2.7? If so, perhaps you could try running it using that Python version from the bash prompt:

python2.7 sms.py

Giles! It worked.

I received a message on my mobile.

Thanks.

But why did Python 2.7 work?

Hooray!

After much digging around, I finally found a comment on the wiki for httplib2 (bottom of the page) saying that its proxy support doesn't work for Python 3, "until the third-party socks module is ported to" it. The particular proxy we use on PythonAnywhere isn't a socks proxy, it's an HTTP one, but I guess they've just disabled all of the proxy stuff until the socks stuff works.

So, if you're OK using Python 2.7 to do this stuff, you can put a hashbang at the top of your script file to make it always work with that Python version:

#!/usr/bin/env python2.7

I suspect you can also get rid of all of the proxy setup code -- try removing it, and see if the script still works with Python 2.7.

Was facing the same problem. Worked without a problem. Thanks for the solution

Hi Guys i am facing same issue with flask framework, i am able to call by using "TwilioCapability", but "TwilioRestClient" client function failing with : [Errno 111] Connection refused

I tried with python2.7 also but no use.

Did you setup twilio with the correct proxy?

If twiliorestclient isn't working but other twilio functions are working with the proxy, then maybe that particular library/function that you are using isn't obeying the proxy settings.

If it's their code, then you will need to upgrade to use it. (or dig into their code base and submit a pull request to them)

could you please send me your code ? Im trying something similar

My issue was resolved. Please tell what code you want?

how did you resolve this? I have this same problem

I used Python 2.7 to resolve the error.

Twillo perfectly works with Python 2.7, and use the bellow line at the starting.

1
#!/usr/bin/env python2.7

[edit by admin: formatting]

Just for clarity: Twilio should work fine in all Python versions in paid accounts. There is a problem with Python 3 versions of their package that stops it working from free accounts.

Hi GIles, I was having a similar issue and finally found this post. Can you help me understand what is the difference between 'pip' and 'pip3.4'? Why use 'pip3.4' over 'pip'?

The difference is the version of Python that it installs the package for. Each version of Python has a different set of installed packages, so pip2.7 will install packages for Python 2.7, pip3.4 will install packages for Python 3.4, and so on.

pip on its own is just an alias for pip2.7, and pip3 is an alias for a version of Python 3.x (which specific version of 3.x depends on your account settings).

Giles,

You are an amazingly helpful person. I am new to PythonAnywhere and very excited and impressed with the platform.

I was hoping to be able to solve this issue with the information above, thus sparing you the (potential) need to provide additional help, but alas I cannot get this to work.

If it wouldn't be too much trouble, I was hoping to get some help running through similar diagnostics as the user above.

I am trying to run this example on Twilio at: https://www.twilio.com/docs/quickstart/python/sms#send-an-outbound-sms-with-python. I have a free PythonAnywhere account and a trial Twilio account.

I have copy-pasted the code from Twilio SDK 6.x. Then, I updated the acct_sid, auth_token, to, and from numbers.

I feel I am missing something relatively simple from a lack of core understanding. I don't know where to start providing information other than this is my error:

Traceback (most recent call last):
  File "/home/alash/scripts/send_sms.py", line 15, in <module>
body="Hello there!")
  File "/home/alash/.local/lib/python2.7/site-packages/twilio/rest/api/v2010/account/message/__init__.py", line 92, in create
data=data,
  File "/home/alash/.local/lib/python2.7/site-packages/twilio/base/version.py", line 205, in create
allow_redirects=allow_redirects,
  File "/home/alash/.local/lib/python2.7/site-packages/twilio/base/version.py", line 47, in request
allow_redirects=allow_redirects
  File "/home/alash/.local/lib/python2.7/site-packages/twilio/base/domain.py", line 46, in request
allow_redirects=allow_redirects
  File "/home/alash/.local/lib/python2.7/site-packages/twilio/rest/__init__.py", line 122, in request
allow_redirects=allow_redirects
  File "/home/alash/.local/lib/python2.7/site-packages/twilio/http/http_client.py", line 68, in request
timeout=timeout,
  File "/home/alash/.local/lib/python2.7/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
  File "/home/alash/.local/lib/python2.7/site-packages/requests/adapters.py", line 508, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.twilio.com', port=443): Max retries exceeded with url: /2010-04-01/Acc
ounts/ACd87a80584c51eba667672d9aa18577b3/Messages.json (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object 
at 0x7f884d3323d0>: Failed to establish a new connection: [Errno 111] Connection refused',))

From a bash console:

$ pip2.7 list --user
asn1crypto (0.24.0)
certifi (2018.1.18)
cffi (1.11.4)
chardet (3.0.4)
cryptography (2.1.4)
httplib2 (0.10.3)
idna (2.6)
ipaddress (1.0.19)
pycparser (2.18)
PyJWT (1.5.3)
pyOpenSSL (17.5.0)
pytz (2017.3)
requests (2.18.4)
six (1.11.0)
twilio (6.10.2)
urllib3 (1.22)

If anything looks odd it is because I have been trying lots of things with lines of logic that may not have been sound. Thank you for any support you can provide.

Did you include the code from further up in the post that configures the twilio library to use the proxy?

Hi Glenn, Thanks for responding. With your comment, I got it to work!

One of Giles' comments in this feed seemed to say we could remove that if Python 2.7 was used. I probably misunderstood based on your related posts I have recently found.

The issue that I ran into was that I confirmed with twilio support that proxy support (e.g. the twilio.rest.resources module) has been removed in twilio 6.x. In lieu of trying to get twilio 6.10.2 to work, I used some of both your and Giles' related posts to find the solution that uses twilio 5.x and python 2.7.

--------------------------------

For others in case you are lost like I was, this is what worked for me (Glenn, please correct me here if I am still misunderstanding something). If you are using a free PythonAnywhere account:

Use twilio 5.4 (as of this writing, this version is already installed for all PythonAnywhere accounts)

Use python 2.7 (copy-paste the below shebang at the top of your code helps)

1
#!/usr/bin/env python2.7

Use proxy code (copy-paste the below code after imports but before doing anything else; proxy modules only available in twilio 5.x)

import os
from urlparse import urlparse
from twilio.rest.resources import Connection
from twilio.rest.resources.connection import PROXY_TYPE_HTTP

host, port = urlparse(os.environ["http_proxy"]).netloc.split(":")
Connection.set_proxy_info(
    host,
    int(port),
    proxy_type=PROXY_TYPE_HTTP,
)

Related help from Giles and Glenn on this topic:

https://www.pythonanywhere.com/forums/topic/7021/

https://www.pythonanywhere.com/forums/topic/1139/

https://www.pythonanywhere.com/forums/topic/2103/

Full code (with personal info removed):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env python2.7

from twilio.rest import TwilioRestClient

import os
from urlparse import urlparse
from twilio.rest.resources import Connection
from twilio.rest.resources.connection import PROXY_TYPE_HTTP

host, port = urlparse(os.environ["http_proxy"]).netloc.split(":")
Connection.set_proxy_info(
host,
int(port),
proxy_type=PROXY_TYPE_HTTP,
)

# put your own credentials here
ACCOUNT_SID = "**********************************"
AUTH_TOKEN = "********************************"

client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

# put personal phone numbers here
client.messages.create(
    to="+***********",
    from_="+***********",
    body="We did it.",
)

Good luck out there.

Great! glad to hear you figured it out!

Hi there, we now have a specific help page on setting up twilio to use the pythonanywhere proxy