aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python
https://docs.aiohttp.org
Other
14.94k stars 1.99k forks source link

aiohttp.client_exceptions.ClientConnectorError when try to connect host api.telegram.org #6984

Closed MykolaBordakov closed 8 months ago

MykolaBordakov commented 1 year ago

Describe the bug

Good day. I try to use aiohttp for sending messages bey telegram bot directly thru telegram API. I test my code on local machine it is works fast and fine. But, when start do it from docker container my code starts to have an error :

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Connect call failed ('149.154.167.220', 443)]

But, that error i does not have all the time. Container can work well, after some time passing it starts to catch errors. My functions code : async def send_msg_asy(text : str,token : str = BOT_TOKEN, chat_id : int = GROUPE_CHAT_ID): async with limit: async with aiohttp.ClientSession() as session: url_req = 'https://api.telegram.org/bot{}/sendMessage'.format(token) data={'chat_id': chat_id, 'text': text} async with session.post(url_req, data= data) as resp: req = await resp.json() if limit.locked(): logging.warning("Concurrency limit reached, waiting ...") await asyncio.sleep(2) if not req['ok']: logging.error('Massage not sent. Error code: "{}".Description: "{}".'.format(req['error_code'], req['description'])) logging.info("Massage was send!") await session.close() Function running by such code :await send_msg_asy(text = text)` My Dockerfile:

`FROM python:3.9.13

WORKDIR /code

COPY ./requirements.txt /code/requirements.txt

# RUN apt-get update RUN pip install --upgrade pip RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt RUN pip3 install pyOpenSSL

COPY ./configs /code/configs RUN mkdir -p /code/logs COPY ./main.py /code COPY ./costum_logging.py /code COPY ./db.py /code COPY ./functions.py /code COPY ./models.py /code COPY ./schemas.py /code COPY ./topik_algo.py /code CMD [ "python", "./main.py"]`

To Reproduce

I`m use explained above function in pare of confluent kafka consumer.

  1. Fist run consumer server.
  2. Send some txt massage to telgram..
  3. After some time you will have an error during sending massages to Telegram.

Expected behavior

Message set to talegarm. :)

Logs/tracebacks

Traceback (most recent call last):
  File "/code/./main.py", line 44, in <module>
    c = init_consuer(topics)
  File "/code/./main.py", line 40, in init_consuer
    asyncio.get_event_loop().run_until_complete(send_msg_asy(text= "Message service started."))
  File "/usr/local/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
    return future.result()
  File "/code/topik_algo.py", line 18, in send_msg_asy
    async with session.post(url_req, data= data) as resp:
  File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 1141, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.9/site-packages/aiohttp/client.py", line 536, in _request
    conn = await self._connector.connect(
  File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 540, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 901, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
    transp, proto = await self._wrap_create_connection(
  File "/usr/local/lib/python3.9/site-packages/aiohttp/connector.py", line 988, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Connect call failed ('149.154.167.220', 443)]
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "cassandra/cluster.py", line 3666, in cassandra.cluster.ControlConnection.shutdown
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1434, in debug
    self._log(DEBUG, msg, args, **kwargs)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1589, in _log
    self.handle(record)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1599, in handle
    self.callHandlers(record)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 1661, in callHandlers
    hdlr.handle(record)
  File "/usr/local/lib/python3.9/logging/__init__.py", line 952, in handle
    self.emit(record)
  File "/code/costum_logging.py", line 24, in emit
    while frame.f_code.co_filename == logging.__file__:
AttributeError: 'NoneType' object has no attribute 'f_code'

Python Version

Python 3.9.13

aiohttp Version

Version: 3.8.3

multidict Version

Version: 6.0.2

yarl Version

Version: 1.8.1

OS

"Debian GNU/Linux 11 (bullseye)" Linux version inside container.

Related component

Client

Additional context

No response

Code of Conduct

Dreamsorcerer commented 1 year ago

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Connect call failed ('149.154.167.220', 443)]

This just looks like a networking issue. Maybe there is a problem with your docker container, or ratelimiting from Telegram? Maybe try running curl or similar inside the docker container when you see the issue, and see if you can reproduce the connection problem outside of the Python program.

This doesn't look like an aiohttp issue.

File "/code/costum_logging.py", line 24, in emit while frame.f_code.co_filename == logging.file: AttributeError: 'NoneType' object has no attribute 'f_code'

That looks like a bug in your code...

MykolaBordakov commented 1 year ago

Thank for reply. So, this one "AttributeError: 'NoneType' object has no attribute 'f_code'" i have becose script on saht down try to close session for cassandra DB. I will fix it.. Also, i found some solution in internet about it. And update my function. Now it is testing now. Here my updates : async def send_msg_asy(text : str,token : str = BOT_TOKEN, chat_id : int = GROUPE_CHAT_ID): async with limit: async with aiohttp.ClientSession(trust_env= True) as http_session: url_req = 'https://api.telegram.org/bot{}/sendMessage'.format(token) data={'chat_id': chat_id, 'text': text} async with http_session.post(url_req, data= data, ssl_context=ssl_context) as resp: req = await resp.json() if limit.locked(): logging.warning("Concurrency limit reached, waiting ...") await asyncio.sleep(2) if not req['ok']: logging.error('Massage not sent. Error code: "{}".Description: "{}".'.format(req['error_code'], req['description'])) logging.info("Massage was send!") await http_session.close()

MykolaBordakov commented 1 year ago

Good day. Yes, you was right. It is not AOIHTTP problem. My updates that i wrote in previous comment did not help. I tried to make curl of https://api.telegram.org from all my containers. But it does not have any results. But, google.com is accessible from any container. I think it is Docker and Telegram problems with proxy. I will try to fin a solution...

Relanit commented 1 year ago

Good day. Yes, you was right. It is not AOIHTTP problem. My updates that i wrote in previous comment did not help. I tried to make curl of https://api.telegram.org from all my containers. But it does not have any results. But, google.com is accessible from any container. I think it is Docker and Telegram problems with proxy. I will try to fin a solution...

Hello, were you able to find a solution? I have the same problem with api.twitch.tv

vikas-credgenics commented 1 year ago

@MykolaBordakov : Did you find any solution. I am also facing the same problem.

SarvarAi commented 1 year ago

@MykolaBordakov : Did you find any solution. I am also facing the same problem.

But how to get proxy_url and proxy_auth

Ishaan1313 commented 8 months ago

Even i am facing the same issue but with discord now

Dreamsorcerer commented 8 months ago

OP said the problem was not aiohttp, so closing. Maybe someone has some ideas that can help you, but I would start by trying to curl or whatever in the docker image to confirm there's network access.