docLamer
@docLamer

Как исправить ошибку Django + Telegram telegram.error.NetworkError?

У меня в проекте реализован функционал отправки уведомлений в ТГ канал, при создании в базе данных новой записи. До недавнего времени все работало стабильно, но теперь django выдает следующую ошибку:
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/utils/request.py", line 259, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/request.py", line 68, in request
    return self.request_encode_body(method, url, fields=fields,
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/request.py", line 148, in request_encode_body
    return self.urlopen(method, url, **extra_kw)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/poolmanager.py", line 244, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py", line 691, in urlopen
    return self.urlopen(method, url, body, headers, retries,
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py", line 691, in urlopen
    return self.urlopen(method, url, body, headers, retries,
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py", line 691, in urlopen
    return self.urlopen(method, url, body, headers, retries,
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/vendor/ptb_urllib3/urllib3/connectionpool.py", line 665, in urlopen
    retries = retries.increment(method, url, error=e, _pool=self,
  File "/projects/djangoRequestsApp/venv/lib/python3.10/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: /bot<token>/sendMessage (Caused by NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.connection.VerifiedHTTPSConnection object at 0x7f304c63d510>: Failed to establish a new connection: [Errno 101] Network is unreachable'))

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/asgiref/sync.py", line 451, in thread_handler
    raise exc_info[1]
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 42, in inner
    response = await get_response(request)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 253, in _get_response_async
    response = await wrapped_callback(
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/asgiref/sync.py", line 414, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "/usr/lib/python3.10/asyncio/tasks.py", line 408, in wait_for
    return await fut
  File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/asgiref/sync.py", line 455, in thread_handler
    return func(*args, **kwargs)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/projects/djangoRequestsApp/./request/views.py", line 93, in create_request
    telega(i)
  File "/projects/djangoRequestsApp/./request/tg.py", line 8, in telega
    bot.send_message(chat_id=chat_id, text=message_html, parse_mode=telegram.ParseMode.HTML)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/bot.py", line 130, in decorator
    result = func(*args, **kwargs)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/bot.py", line 522, in send_message
    return self._message(  # type: ignore[return-value]
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/bot.py", line 336, in _message
    result = self._post(endpoint, data, timeout=timeout, api_kwargs=api_kwargs)
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/bot.py", line 295, in _post
    return self.request.post(
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/utils/request.py", line 361, in post
    result = self._request_wrapper(
  File "/projects/djangoRequestsApp/venv/lib/python3.10/site-packages/telegram/utils/request.py", line 265, in _request_wrapper
    raise NetworkError(f'urllib3 HTTPError {error}') from error
telegram.error.NetworkError: urllib3 HTTPError HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot<token>/sendMessage (Caused by NewConnectionError('<telegram.vendor.ptb_urllib3.urllib3.connection.VerifiedHTTPSConnection object at 0x7f304c63d510>: Failed to establish a new connection: [Errno 101] Network is unreachable'))


views.py
if request.method == 'POST':
        form = Create(request.POST, request.FILES)
        if form.is_valid():
            i = Request(**form.cleaned_data)
            i.save()

            # Send message in telegram
            telega(i)
            # ####

            return redirect('/')


telega.py
import telegram
from django.template.loader import render_to_string
from Requests.settings import bot, chat_id


def telega(i):
   message_html = render_to_string('bot/bot.html', {'i': i})
   bot.send_message(chat_id=chat_id, text=message_html, parse_mode=telegram.ParseMode.HTML)
   return i

Помогите пожалуйста решить эту проблему.
  • Вопрос задан
  • 192 просмотра
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы