Есть сервер, на котором исходящие запросы наружу могут быть только с определенного локального хоста и порта.
Я попытался переопределить стандартный метод класса AiohttpSession, как то так:
from aiogram.client.session.aiohttp import AiohttpSession
from aiohttp import ClientSession
from aiohttp.hdrs import USER_AGENT
from aiohttp.http import SERVER_SOFTWARE
from aiogram.__meta__ import __version__
class CustomSession(AiohttpSession):
def __init__(self, local_ip: str, local_port: int, *args, **kwargs):
super().__init__(*args, **kwargs)
self.local_ip = local_ip
self.local_port = local_port
async def create_session(self) -> ClientSession:
if self._should_reset_connector:
await self.close()
if self._session is None or self._session.closed:
self._connector_init.update({
'local_addr': (self.local_ip, self.local_port)
})
self._session = ClientSession(
connector=self._connector_type(**self._connector_init),
headers={
USER_AGENT: f"{SERVER_SOFTWARE} aiogram/{__version__}",
},
)
self._should_reset_connector = False
return self._session
Потом я создаю бот вот так:
bot = Bot(token=item['token'],
session=CustomSession(local_ip=TG_HOST, local_port=TG_PORT),
default=DefaultBotProperties(parse_mode=ParseMode.HTML))
Но все равно ловлю ошибку:
Traceback (most recent call last):
File "/Users/macbook/Dev/merchant/venv/lib/python3.10/site-packages/starlette/routing.py", line 732, in lifespan
async with self.lifespan_context(app) as maybe_state:
File "/opt/homebrew/Cellar/python@3.10/3.10.14/Frameworks/Python.framework/Versions/3.10/lib/python3.10/contextlib.py", line 199, in __aenter__
return await anext(self.gen)
File "/Users/macbook/Dev/merchant/merchant/files_v2/main.py", line 81, in lifespan
secret_token = await set_webhook(bot)
File "/Users/macbook/Dev/merchant/merchant/files_v2/main.py", line 44, in set_webhook
await bot.set_webhook(webhook_uri,
File "/Users/macbook/Dev/merchant/venv/lib/python3.10/site-packages/aiogram/client/bot.py", line 3776, in set_webhook
return await self(call, request_timeout=request_timeout)
File "/Users/macbook/Dev/merchant/venv/lib/python3.10/site-packages/aiogram/client/bot.py", line 482, in __call__
return await self.session(self, method, timeout=request_timeout)
File "/Users/macbook/Dev/merchant/venv/lib/python3.10/site-packages/aiogram/client/session/base.py", line 254, in __call__
return cast(TelegramType, await middleware(bot, method))
File "/Users/macbook/Dev/merchant/venv/lib/python3.10/site-packages/aiogram/client/session/aiohttp.py", line 188, in make_request
raise TelegramNetworkError(method=method, message=f"{type(e).__name__}: {e}")
aiogram.exceptions.TelegramNetworkError: HTTP Client says - ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Can't assign requested address]
Подскажите, есть ли какие-то способы отправлять запросы с заданного адреса?