HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot
Packages: pyTelegramBotAPI==3.6.3 requests==2.19.1 PySocks==1.6.8 urllib3==1.23
OS: MacOS or Ubuntu 16 (via docker)
Python: Python 3.5.3 or PyPy3 (also 3.5.3)
Problem: I successfully ran a bot some hours ago but after some time it starts to throw an error. I have to use a proxy (and it worked with a proxy at the beginning). I tried HTTPS, SOCKS5 proxies and I'm sure that they are working ones but I still get this error and I suppose that Telegram servers are fine right now. There are many posts in the internet with the same error but they have no information and solutions to the problem (beside the fact that people switch to some other packages).
Don't know if this is a bug or not, but as there are no answers in other places I decided to put it here.
Code:
import os
import time
import logging
import telebot
from telebot import apihelper
# Logger
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)
# Configuration
TG_PROXY = 'https://103.241.156.250:8080'
TG_BOT_TOKEN = 'xxxxxxxx'
# Set proxy
apihelper.proxy = {'http': TG_PROXY}
# Init bot
bot = telebot.TeleBot(TG_BOT_TOKEN)
# /start
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Howdy, how are you doing?")
# Plain message
@bot.message_handler(func=lambda m: True)
def echo_all(message):
bot.reply_to(message, message.text)
# Polling
while True:
try:
bot.polling(none_stop=True)
except Exception as e:
logger.error(e)
time.sleep(15)
Traceback:
2018-07-05 14:33:26,589 (__init__.py:276 MainThread) INFO - TeleBot: "Started polling."
2018-07-05 14:33:26,590 (util.py:56 PollingThread) DEBUG - TeleBot: "Received task"
2018-07-05 14:33:26,590 (apihelper.py:45 PollingThread) DEBUG - TeleBot: "Request: method=get url=https://api.telegram.org/bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates params={'offset': 1, 'timeout': 20} files=None"
2018-07-05 14:33:26,962 (util.py:65 PollingThread) ERROR - TeleBot: "SSLError occurred, args=(MaxRetryError("HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates?offset=1&timeout=20 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed'),))",),)
Traceback (most recent call last):
File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 849, in _validate_conn
conn.connect()
File "/Users/max/Documents/env/site-packages/urllib3/connection.py", line 356, in connect
ssl_context=context)
File "/Users/max/Documents/env/site-packages/urllib3/util/ssl_.py", line 359, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/Users/max/pypy3/lib-python/3/ssl.py", line 385, in wrap_socket
_context=self)
File "/Users/max/pypy3/lib-python/3/ssl.py", line 760, in __init__
self.do_handshake()
File "/Users/max/pypy3/lib-python/3/ssl.py", line 996, in do_handshake
self._sslobj.do_handshake()
File "/Users/max/pypy3/lib-python/3/ssl.py", line 641, in do_handshake
self._sslobj.do_handshake()
File "/Users/max/pypy3/lib_pypy/_cffi_ssl/_stdssl/__init__.py", line 354, in do_handshake
raise pyssl_error(self, ret)
_cffi_ssl._stdssl.error.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/max/Documents/env/site-packages/requests/adapters.py", line 445, in send
timeout=timeout
File "/Users/max/Documents/env/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/Users/max/Documents/env/site-packages/urllib3/util/retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates?offset=1&timeout=20 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed'),))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/max/Documents/env/site-packages/telebot/util.py", line 59, in run
task(*args, **kwargs)
File "/Users/max/Documents/env/site-packages/telebot/__init__.py", line 158, in __retrieve_updates
updates = self.get_updates(offset=(self.last_update_id + 1), timeout=timeout)
File "/Users/max/Documents/env/site-packages/telebot/__init__.py", line 128, in get_updates
json_updates = apihelper.get_updates(self.token, offset, limit, timeout, allowed_updates)
File "/Users/max/Documents/env/site-packages/telebot/apihelper.py", line 180, in get_updates
return _make_request(token, method_url, params=payload)
File "/Users/max/Documents/env/site-packages/telebot/apihelper.py", line 54, in _make_request
timeout=(connect_timeout, read_timeout), proxies=proxy)
File "/Users/max/Documents/env/site-packages/requests/sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "/Users/max/Documents/env/site-packages/requests/sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "/Users/max/Documents/env/site-packages/requests/adapters.py", line 511, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getUpdates?offset=1&timeout=20 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14007086:SSL routines:CONNECT_CR_CERT:certificate verify failed'),))
UPD:
Tried my former code that uses python-telegram-bot with the same TG_PROXY and TG_BOT_TOKEN and everything works ok. So it's not a proxy / telegram servers or "ban" problem.
@vashchukmaksim
I had similar problem. One of the solutions of this problem can be increasing timeout value in polling function. I use value '123' and everything is ok.
bot.polling(none_stop=True, timeout=123
@M1LKYWVY Unfortunately it didn't help. And actually I got a strange behaviour right now. If I set timeout to 123, it crashes with 409 error because thinks that multiple getUpdates running. If I remove while cycle (and keep 123 timeout) it repeats the initial error. Also if I remove polling and trying to call just bot.get_me() it still crashes with the initial error.
I simplified everything just to:
bot.py
import os
import time
import logging
import telebot
from telebot import apihelper
# Logger
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)
# Set proxy
apihelper.proxy = {'http': TG_PROXY}
# Init bot
bot = telebot.TeleBot(TG_BOT_TOKEN)
app.py
from flask import Flask, jsonify
from bot import bot
@app.route('/healthcheck')
def any():
result = bot.get_me()
if result:
return jsonify(result)
return jsonify({'result': None})
I tried to turn off a proxy since on my current network I can use telegram directly but I still get the same error (and with proxy enabled I still got the same)
bot_1 | 2018-07-06 09:40:21,611 (apihelper.py:45 MainThread) DEBUG - TeleBot: "Request: method=get url=https://api.telegram.org/bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getMe params=None files=None"
bot_1 | [2018-07-06 09:40:21 +0000] [48] [ERROR] Socket error processing request.
bot_1 | Traceback (most recent call last):
bot_1 | File "/usr/local/site-packages/urllib3/connectionpool.py", line 600, in urlopen
bot_1 | chunked=chunked)
bot_1 | File "/usr/local/site-packages/urllib3/connectionpool.py", line 343, in _make_request
bot_1 | self._validate_conn(conn)
bot_1 | File "/usr/local/site-packages/urllib3/connectionpool.py", line 849, in _validate_conn
bot_1 | conn.connect()
bot_1 | File "/usr/local/site-packages/urllib3/connection.py", line 356, in connect
bot_1 | ssl_context=context)
bot_1 | File "/usr/local/site-packages/urllib3/util/ssl_.py", line 359, in ssl_wrap_socket
bot_1 | return context.wrap_socket(sock, server_hostname=server_hostname)
bot_1 | File "/usr/local/lib-python/3/ssl.py", line 385, in wrap_socket
bot_1 | _context=self)
bot_1 | File "/usr/local/lib-python/3/ssl.py", line 760, in __init__
bot_1 | self.do_handshake()
bot_1 | File "/usr/local/lib-python/3/ssl.py", line 996, in do_handshake
bot_1 | self._sslobj.do_handshake()
bot_1 | File "/usr/local/lib-python/3/ssl.py", line 641, in do_handshake
bot_1 | self._sslobj.do_handshake()
bot_1 | File "/usr/local/lib_pypy/_cffi_ssl/_stdssl/__init__.py", line 354, in do_handshake
bot_1 | raise pyssl_error(self, ret)
bot_1 | _cffi_ssl._stdssl.error.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
bot_1 |
bot_1 | During handling of the above exception, another exception occurred:
bot_1 |
bot_1 | Traceback (most recent call last):
bot_1 | File "/usr/local/site-packages/requests/adapters.py", line 445, in send
bot_1 | timeout=timeout
bot_1 | File "/usr/local/site-packages/urllib3/connectionpool.py", line 638, in urlopen
bot_1 | _stacktrace=sys.exc_info()[2])
bot_1 | File "/usr/local/site-packages/urllib3/util/retry.py", line 398, in increment
bot_1 | raise MaxRetryError(_pool, url, error or ResponseError(cause))
bot_1 | urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getMe (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed'),))
bot_1 |
bot_1 | During handling of the above exception, another exception occurred:
bot_1 |
bot_1 | Traceback (most recent call last):
bot_1 | File "/usr/local/site-packages/gunicorn/workers/sync.py", line 135, in handle
bot_1 | self.handle_request(listener, req, client, addr)
bot_1 | File "/usr/local/site-packages/gunicorn/workers/sync.py", line 191, in handle_request
bot_1 | six.reraise(*sys.exc_info())
bot_1 | File "/usr/local/site-packages/gunicorn/six.py", line 625, in reraise
bot_1 | raise value
bot_1 | File "/usr/local/site-packages/gunicorn/workers/sync.py", line 176, in handle_request
bot_1 | respiter = self.wsgi(environ, resp.start_response)
bot_1 | File "/usr/local/site-packages/flask/app.py", line 2309, in __call__
bot_1 | return self.wsgi_app(environ, start_response)
bot_1 | File "/usr/local/site-packages/werkzeug/contrib/fixers.py", line 152, in __call__
bot_1 | return self.app(environ, start_response)
bot_1 | File "/usr/local/site-packages/flask/app.py", line 2295, in wsgi_app
bot_1 | response = self.handle_exception(e)
bot_1 | File "/usr/local/site-packages/flask/app.py", line 1741, in handle_exception
bot_1 | reraise(exc_type, exc_value, tb)
bot_1 | File "/usr/local/site-packages/flask/_compat.py", line 35, in reraise
bot_1 | raise value
bot_1 | File "/usr/local/site-packages/flask/app.py", line 2292, in wsgi_app
bot_1 | response = self.full_dispatch_request()
bot_1 | File "/usr/local/site-packages/flask/app.py", line 1815, in full_dispatch_request
bot_1 | rv = self.handle_user_exception(e)
bot_1 | File "/usr/local/site-packages/flask/app.py", line 1718, in handle_user_exception
bot_1 | reraise(exc_type, exc_value, tb)
bot_1 | File "/usr/local/site-packages/flask/_compat.py", line 35, in reraise
bot_1 | raise value
bot_1 | File "/usr/local/site-packages/flask/app.py", line 1813, in full_dispatch_request
bot_1 | rv = self.dispatch_request()
bot_1 | File "/usr/local/site-packages/flask/app.py", line 1799, in dispatch_request
bot_1 | return self.view_functions[rule.endpoint](**req.view_args)
bot_1 | File "/usr/src/server/app/__init__.py", line 36, in any
bot_1 | result = bot.get_me()
bot_1 | File "/usr/local/site-packages/telebot/__init__.py", line 360, in get_me
bot_1 | result = apihelper.get_me(self.token)
bot_1 | File "/usr/local/site-packages/telebot/apihelper.py", line 93, in get_me
bot_1 | return _make_request(token, method_url)
bot_1 | File "/usr/local/site-packages/telebot/apihelper.py", line 54, in _make_request
bot_1 | timeout=(connect_timeout, read_timeout), proxies=proxy)
bot_1 | File "/usr/local/site-packages/requests/sessions.py", line 512, in request
bot_1 | resp = self.send(prep, **send_kwargs)
bot_1 | File "/usr/local/site-packages/raven/breadcrumbs.py", line 326, in send
bot_1 | resp = real_send(self, request, *args, **kwargs)
bot_1 | File "/usr/local/site-packages/requests/sessions.py", line 622, in send
bot_1 | r = adapter.send(request, **kwargs)
bot_1 | File "/usr/local/site-packages/requests/adapters.py", line 511, in send
bot_1 | raise SSLError(e, request=request)
bot_1 | requests.exceptions.SSLError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot607551944:AAG08U8uEnj-ERDmLOCWUl2Yaa80Q3eXHVw/getMe (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed'),))
Hm, I think I found out a problem but I don't know how to solve it. The case I suppose in setting a proxy because when I tried to access a telegram.org in the browser I got an SSL error, and when I turn on a VPN it works.
So now I think that telebot just ignores apihelper.proxy = {'http': TG_PROXY} and don't know how to make it use a proxy.
Found solution here, thanks for @kostykoff https://github.com/eternnoir/pyTelegramBotAPI/issues/499#issuecomment-387101672 You just need to install version 2.10.0 of requests
@Onefivefournine sorry, but receipt does not work properly
Experiening the same issue. The environment is:
- Ubuntu 16.04 running on MacBook Pro Mid 2012.
- pyTelegramBotAPI==3.6.6
- requests==2.20.0
- six==1.10.0
- Bot is started using systemd. It constantly crashes and gets restarted with the following error:
окт 28 20:05:34 ubuntubook bot.py[3614]: Traceback (most recent call last):
окт 28 20:05:34 ubuntubook bot.py[3614]: File "/home/kesha/smarthomebot/bot.py", line 24, in
Please assist to sort this out.
Are you solve this program?
The same problem
Found solution here, thanks for @kostykoff #499 (comment) You just need to install version 2.10.0 of requests
Does not solve my problem
Unfortunately no. I moved to python-telegram-bot.
I have the same problem :( no solution right now
i have same problem, please update me
and I have the same problem :( Perhaps this problem is connected with the struggle of Roskomnadzor and telegram? if so, what are the solutions?
@ivin-v no it’s not the case here since we trying to use a proxy to get over the problem you mentioned but we can’t because of this issue.
@vashchukmaksim Максим, значит дело не только в блокировке? Мой бот перестал работать 11.01.19 я использую telepot
@ivin-v
- Если бот не работает без прокси, то 99% виновата блокировка
- Берем прокси, проверяем что он рабочий сам по себе, устанавливаем его боту в качестве прокси.
- Если не работает (как раз этот issue), то делаем тестовый простой бот с python-telegram-bot и устанавливаем ему рабочий прокси. Здесь почти 100% что он заработает.
Как вы видите, этот issue возникает у многих, а ни ответов, ни решений на уровне библиотеки нет, я даже думал покапаться и сделать PR, но пересел на python-telegram-bot и вполне доволен, очень внятная документация и все работает.
i want to scrap wikipedia, and this problem happened too
+1 not work (exp: echo bot): Failed to establish a new connection: [Errno 101] Network is unreachable',)) with http proxy (valid)
VPN solves the issue for me. Seems like the issue is on Internet Provider’s side in my case. Maybe it’s related to Telegram ban in Russia. As another proof of that idea my bot also perfectly works on Heroku.
Conclusion: Try to use free VPN to check if it’s related to Telegram ban.