D
D
Denis2019-09-14 18:29:59
Python
Denis, 2019-09-14 18:29:59

How to make python-telegram-bot work with proxy?

I'm trying to get the bot to work, but ConnectTimeoutError crashes. I do, it seems, everything in accordance with the working begin proxy from python-telegram-bot, but it does not work. Due to inexperience, I do not understand why. Tested both on random socks5 proxies, and 100% verified working. Code and errors are attached.
The code:

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler
from telegram import InlineQueryResultArticle, InputTextMessageContent, Chat
import logging


logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                     level=logging.INFO)

TOKEN='Условный токен'

REQUEST_KWARGS={
    'proxy_url': 'socks5://138.197.145.103:1080',
    }

updater = Updater(token='Условный токен", use_context=True, request_kwargs=REQUEST_KWARGS)
dispatcher = updater.dispatcher


def start(update, context):
    context.bot.send_message(chat_id=update.message.chat_id, text="I'm a bot, please talk to me!")

start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)


def echo(update, context):
    context.bot.send_message(chat_id=update.message.chat_id, text=update.message.text)

echo_handler = MessageHandler(Filters.text, echo)
dispatcher.add_handler(echo_handler)


def unknown(update, context):
    context.bot.send_message(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command.")

unknown_handler = MessageHandler(Filters.command, unknown)
dispatcher.add_handler(unknown_handler)

updater.start_polling()

Mistake:

C:\Users\user\PycharmProjects\twst001\venv\Scripts\python.exe C:/Users/user/PycharmProjects/twst001/twst001.py
2019-09-14 18:14:15,551 - telegram.vendor.ptb_urllib3.urllib3 .connectionpool - WARNING - Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(, 'Connection to api.telegram.org timed out. (connect timeout=5.0 )')': /botConditionalToken/getMe
2019-09-14 18:14:20,552 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=1, connect=None, read=None, redirect= None)) after connection broken by 'ConnectTimeoutError(, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')': /botConditionalToken/getMe
2019-09-14 18:14:25,554 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError (, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')': /botConditionalToken/getMe
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\twst001\venv\ lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "C:\Users\user \PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\connection.py", line 83, in create_connection
raise err
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\connection.py", line 73, in create_connection
sock.connect(sa)
socket.timeout : timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3 \connectionpool.py", line 617, in urlopen
chunked=chunked)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 360, in _make_request
self._validate_conn(conn)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 857, in _validate_conn
super(HTTPSConnectionPool, self)._validate_conn(conn)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 289, in _validate_conn
conn.connect()
File "C:\Users \user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connection.py", line 284, in connect
conn = self._new_conn()
File "C:\Users\user\PycharmProjects \twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connection.py", line 146, in _new_conn
(self.host, self.timeout))
telegram.vendor.ptb_urllib3.urllib3.exceptions.ConnectTimeoutError: (, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')
During handling of the above exception, another exception occurred:
Traceback (most recent call last ):
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\utils\request.py", line 218, in _request_wrapper
resp = self._con_pool.request(*args, ** kwargs)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 66, in request
**urlopen_kw)
File "C:\ Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 87, in request_encode_url
return self.urlopen(method, url, **extra_kw)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py ", line 695, in urlopen
**response_kw)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 695, in urlopen
**response_kw)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 695, in urlopen
**response_kw)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 666, in urlopen
_stacktrace=sys.exc_info() [2])
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 376, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
telegram.vendor.ptb_urllib3.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /botConditionalToken/getMe (Caused by ConnectTimeoutError(, 'Connection to api.telegram.org timed out. (connect timeout=5.0)'))
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/twst001/twst001.py", line 42, in
updater.start_polling()
File "C:\Users\user\PycharmProjects\twst001\venv\ lib\site-packages\telegram\ext\updater.py", line 213, in start_polling
self.job_queue.start()
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\ ext\jobqueue.py", line 291, in start
name="Bot:{}:job_queue".format(self._dispatcher.bot.id))
File "C:\Users\user\PycharmProjects\twst001\venv\lib \site-packages\telegram\bot.py", line 52, in decorator
self.get_me()
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\bot.py", line 66,in decorator
result = func(self, *args, **kwargs)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\bot.py", line 199, in get_me
result = self. _request.get(url, timeout=timeout)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\utils\request.py", line 270, in get
result = self._request_wrapper ('GET', url, **urlopen_kwargs)
File "C:\Users\user\PycharmProjects\twst001\venv\lib\site-packages\telegram\utils\request.py", line 224, in _request_wrapper
raise NetworkError(' urllib3 HTTPError {0}'.format(error))
telegram.error.NetworkError: urllib3 HTTPError HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /botConditionalToken/getMe (Caused by ConnectTimeoutError(, 'Connection to api.telegram.org timed out.(connect timeout=5.0)'))
Process finished with exit code 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg, 2019-09-14
@Gawaken

Now, in order to legalize a Telegram bot through a proxy, two conditions must be met:
Try like this. I just checked - my bot with this config normally connects and sends a message with a picture.

REQUEST_KWARGS={
    'proxy_url': 'socks4://171.103.9.22:4145/',
    # Optional, if you need authentication:
    'urllib3_proxy_kwargs': {
        'assert_hostname': 'False',
        'cert_reqs': 'CERT_NONE'
        # 'username': 'user',
        # 'password': 'password'
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question