pyTelegramBotAPI icon indicating copy to clipboard operation
pyTelegramBotAPI copied to clipboard

HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot

Open maxsiml opened this issue 8 years ago • 33 comments

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.

maxsiml avatar Jul 05 '18 11:07 maxsiml

@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 avatar Jul 05 '18 15:07 M1LKYWVY

@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.

maxsiml avatar Jul 06 '18 08:07 maxsiml

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'),))

maxsiml avatar Jul 06 '18 09:07 maxsiml

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.

maxsiml avatar Jul 06 '18 10:07 maxsiml

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 avatar Jul 15 '18 19:07 Onefivefournine

@Onefivefournine sorry, but receipt does not work properly

mrkeuz avatar Oct 15 '18 05:10 mrkeuz

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 окт 28 20:05:34 ubuntubook bot.py[3614]: bot = SmartHomeBot(TOKEN) окт 28 20:05:34 ubuntubook bot.py[3614]: File "/home/kesha/smarthomebot/bot.py", line 16, in init окт 28 20:05:34 ubuntubook bot.py[3614]: self.send_message(ADMIN_ID, 'I've just got restarted.') окт 28 20:05:34 ubuntubook bot.py[3614]: File "/home/kesha/smarthomebot/bot.py", line 21, in send_message окт 28 20:05:34 ubuntubook bot.py[3614]: parse_mode, disable_notification) окт 28 20:05:34 ubuntubook bot.py[3614]: File "/usr/local/lib/python3.5/dist-packages/telebot/init.py", line 598, in send_message окт 28 20:05:34 ubuntubook bot.py[3614]: reply_markup, parse_mode, disable_notification)) окт 28 20:05:34 ubuntubook bot.py[3614]: File "/usr/local/lib/python3.5/dist-packages/telebot/apihelper.py", line 140, in send_message окт 28 20:05:34 ubuntubook bot.py[3614]: return _make_request(token, method_url, params=payload, method='post') окт 28 20:05:34 ubuntubook bot.py[3614]: File "/usr/local/lib/python3.5/dist-packages/telebot/apihelper.py", line 54, in _make_request окт 28 20:05:34 ubuntubook bot.py[3614]: timeout=(connect_timeout, read_timeout), proxies=proxy) окт 28 20:05:34 ubuntubook bot.py[3614]: File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 524, in request окт 28 20:05:34 ubuntubook bot.py[3614]: resp = self.send(prep, **send_kwargs) окт 28 20:05:34 ubuntubook bot.py[3614]: File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 637, in send окт 28 20:05:34 ubuntubook bot.py[3614]: r = adapter.send(request, **kwargs) окт 28 20:05:34 ubuntubook bot.py[3614]: File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py", line 516, in send окт 28 20:05:34 ubuntubook bot.py[3614]: raise ConnectionError(e, request=request) окт 28 20:05:34 ubuntubook bot.py[3614]: requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /BOTAPI/sendMessage?reply_markup=%7B%22resize_keyboard%22%3A+true%2C+%22keyboard%22%3A+%5B%5B%7B%22text%22%3A+%22%5Cu0422%5Cu043e%5Cu0440%5Cu0440%5Cu0435%5Cu043d%5Cu0442%5Cu044b+%5Cu2195%5Cufe0f%22%7D%5D%2C+%5B%7B%22text%22%3A+%22%5Cu041f%5Cu043e%5Cu0438%5Cu0441%5Cu043a+%5Cud83d%5Cudd0d%22%7D%5D%5D%7D&text=I%27ve+just+got+restarted.&chat_id=70044128 (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f98d4d10ef0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',)) окт 28 20:05:34 ubuntubook systemd[1]: smarthomebot.service: Main process exited, code=exited, status=1/FAILURE окт 28 20:05:34 ubuntubook systemd[1]: smarthomebot.service: Unit entered failed state. окт 28 20:05:34 ubuntubook systemd[1]: smarthomebot.service: Failed with result 'exit-code'. окт 28 20:05:39 ubuntubook systemd[1]: smarthomebot.service: Service hold-off time over, scheduling restart.

Please assist to sort this out.

keshamin avatar Oct 28 '18 17:10 keshamin

Are you solve this program?

ghost avatar Dec 03 '18 04:12 ghost

The same problem

thc2018 avatar Dec 05 '18 19:12 thc2018

Found solution here, thanks for @kostykoff #499 (comment) You just need to install version 2.10.0 of requests

Does not solve my problem

thc2018 avatar Dec 05 '18 19:12 thc2018

Unfortunately no. I moved to python-telegram-bot.

maxsiml avatar Dec 06 '18 18:12 maxsiml

I have the same problem :( no solution right now

akirasan avatar Jan 03 '19 23:01 akirasan

i have same problem, please update me

tarek-vader avatar Jan 23 '19 15:01 tarek-vader

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 avatar Jan 31 '19 07:01 ivin-v

@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.

maxsiml avatar Jan 31 '19 09:01 maxsiml

@vashchukmaksim Максим, значит дело не только в блокировке? Мой бот перестал работать 11.01.19 я использую telepot

ivin-v avatar Feb 01 '19 05:02 ivin-v

@ivin-v

  1. Если бот не работает без прокси, то 99% виновата блокировка
  2. Берем прокси, проверяем что он рабочий сам по себе, устанавливаем его боту в качестве прокси.
  3. Если не работает (как раз этот issue), то делаем тестовый простой бот с python-telegram-bot и устанавливаем ему рабочий прокси. Здесь почти 100% что он заработает.

Как вы видите, этот issue возникает у многих, а ни ответов, ни решений на уровне библиотеки нет, я даже думал покапаться и сделать PR, но пересел на python-telegram-bot и вполне доволен, очень внятная документация и все работает.

maxsiml avatar Feb 01 '19 07:02 maxsiml

i want to scrap wikipedia, and this problem happened too

Trianamonikaa avatar Apr 05 '19 13:04 Trianamonikaa

+1 not work (exp: echo bot): Failed to establish a new connection: [Errno 101] Network is unreachable',)) with http proxy (valid)

jekeam avatar Apr 15 '19 08:04 jekeam

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.

keshamin avatar Apr 19 '19 16:04 keshamin