@Anther
Начинающий

Почему не работает proxi?

Пытаюсь запусить бота с прокси, но выдаёт ошибку

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://144.217.163.138:1080',
}

updater = Updater(token='*********:***********************************', use_context=True, request_kwargs=REQUEST_KWARGS)
dispatcher = updater.dispatcher


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()


логи

2019-09-14 09:04:49,669 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x03A0F350>: Failed to establish a new connection: Connection closed unexpectedly')': /bot*********:***********************************/getMe
2019-09-14 09:04:50,070 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x03A0F4B0>: Failed to establish a new connection: Connection closed unexpectedly')': /bot*********:***********************************/getMe
2019-09-14 09:04:50,494 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x03A0F5D0>: Failed to establish a new connection: Connection closed unexpectedly')': /bot*********:***********************************/getMe
Traceback (most recent call last):
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 809, in connect
    negotiate(self, dest_addr, dest_port)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 444, in _negotiate_SOCKS5
    self, CONNECT, dest_addr)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 524, in _SOCKS5_request
    resp = self._readall(reader, 3)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 278, in _readall
    raise GeneralProxyError("Connection closed unexpectedly")
socks.GeneralProxyError: Connection closed unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\contrib\socks.py", line 88, in _new_conn
    **extra_kw
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 209, in create_connection
    raise err
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 199, in create_connection
    sock.connect((remote_host, remote_port))
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 47, in wrapper
    return function(*args, **kwargs)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\socks.py", line 814, in connect
    raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: Connection closed unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 617, in urlopen
    chunked=chunked)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 360, in _make_request
    self._validate_conn(conn)
  File "C:\Users\135nn\PycharmProjects\narabotki\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\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 289, in _validate_conn
    conn.connect()
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connection.py", line 284, in connect
    conn = self._new_conn()
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\contrib\socks.py", line 110, in _new_conn
    "Failed to establish a new connection: %s" % error
telegram.vendor.ptb_urllib3.urllib3.exceptions.NewConnectionError: <telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x03A0F6F0>: Failed to establish a new connection: Connection closed unexpectedly

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\utils\request.py", line 218, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 66, in request
    **urlopen_kw)
  File "C:\Users\135nn\PycharmProjects\narabotki\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\135nn\PycharmProjects\narabotki\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\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 695, in urlopen
    **response_kw)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 695, in urlopen
    **response_kw)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 695, in urlopen
    **response_kw)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 666, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Users\135nn\PycharmProjects\narabotki\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: SOCKSHTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot*********:***********************************/getMe (Caused by NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x03A0F6F0>: Failed to establish a new connection: Connection closed unexpectedly'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/135nn/PycharmProjects/narabotki/test.py", line 23, in <module>
    updater.start_polling()
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\ext\updater.py", line 213, in start_polling
    self.job_queue.start()
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\ext\jobqueue.py", line 291, in start
    name="Bot:{}:job_queue".format(self._dispatcher.bot.id))
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\bot.py", line 52, in decorator
    self.get_me()
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\bot.py", line 66, in decorator
    result = func(self, *args, **kwargs)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\bot.py", line 199, in get_me
    result = self._request.get(url, timeout=timeout)
  File "C:\Users\135nn\PycharmProjects\narabotki\venv\lib\site-packages\telegram\utils\request.py", line 270, in get
    result = self._request_wrapper('GET', url, **urlopen_kwargs)
  File "C:\Users\135nn\PycharmProjects\narabotki\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 SOCKSHTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot*********:***********************************/getMe (Caused by NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x03A0F6F0>: Failed to establish a new connection: Connection closed unexpectedly'))

Как починить?
  • Вопрос задан
  • 843 просмотра
Пригласить эксперта
Ответы на вопрос 2
devalone
@devalone
̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻
Так прокси же не рабочий

curl ipinfo.io --proxy "socks5://144.217.163.138:1080"
Ответ написан
@OlegPyatakov
pyatakov.com
Сейчас, чтобы законнектить Телеграм бота через прокси, нужно выполнить два условия:

  • Используемый Socks прокси должен поддерживать SSL. Далеко не каждый прокси в интернете его поддерживает - нужно проверять. Указанный в вашем конфиге - не поддерживает или делает это как-то необычно.
  • Боту нужно передавать дополнительно параметры для библиотеки коннекта, чтобы та игнорировала ошибки сертификатов. В вашем случае, нужны параметры для Urllib3.


Попробуйте вот так. Я только что проверил - мой бот с таким конфигом нормально коннектится и посылает сообщение с картинкой.

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'
    }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы