From 4e6af6636216b9c0d5bff5f02bf6a5a960d304a4 Mon Sep 17 00:00:00 2001 From: hexdev Date: Wed, 15 Jul 2026 14:23:05 +0700 Subject: [PATCH] feat: openai proxying --- .env.example | 2 +- README.md | 4 ++-- bot.py | 3 +++ requirements.txt | 1 + 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index ade77fb..6db95d7 100644 --- a/.env.example +++ b/.env.example @@ -8,7 +8,7 @@ API_BASE_URL=https://api.openai.com/v1 API_TOKEN=sk-replace-me MODEL=gpt-4o-mini -# Optional proxy used by aiogram to reach Telegram API. +# Optional proxy used for both Telegram API and OpenAI-compatible API. # Supports HTTP and SOCKS URLs when aiohttp-socks is installed. # TELEGRAM_PROXY=socks5://user:pass@127.0.0.1:1080 TELEGRAM_PROXY= diff --git a/README.md b/README.md index 110a7e4..926688f 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Minimal aiogram bot that forwards whitelisted Telegram users' text messages to a ## Features - Configurable `API_BASE_URL` and `API_TOKEN` -- Optional proxy for aiogram Telegram API connections +- Optional proxy for Telegram API and OpenAI-compatible API connections - Telegram typing animation while the model response is streaming - Required users whitelist - Persistent per-user context in SQLite @@ -61,7 +61,7 @@ python bot.py ## Proxy -Set `TELEGRAM_PROXY` in `.env` to route aiogram traffic through a proxy: +Set `TELEGRAM_PROXY` in `.env` to route both Telegram API and OpenAI-compatible API traffic through a proxy: ```dotenv TELEGRAM_PROXY=socks5://user:pass@127.0.0.1:1080 diff --git a/bot.py b/bot.py index 6198e81..6bf0c89 100644 --- a/bot.py +++ b/bot.py @@ -14,6 +14,7 @@ from aiogram.exceptions import TelegramBadRequest from aiogram.filters import Command, CommandStart from aiogram.types import Message from dotenv import load_dotenv +from httpx import AsyncClient as HttpxAsyncClient from openai import APIConnectionError, APIError, APITimeoutError, AsyncOpenAI, NotFoundError, RateLimitError @@ -136,11 +137,13 @@ def load_settings() -> Settings: settings = load_settings() +http_client = HttpxAsyncClient(proxy=settings.telegram_proxy) if settings.telegram_proxy else None client = AsyncOpenAI( api_key=settings.api_token, base_url=settings.api_base_url, timeout=settings.api_timeout_seconds, max_retries=settings.api_max_retries, + http_client=http_client, ) user_locks: dict[int, asyncio.Lock] = {} pending_user_messages: dict[int, list[str]] = {} diff --git a/requirements.txt b/requirements.txt index 341b10d..2df6fef 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ aiogram==3.13.1 aiohttp-socks==0.9.0 +httpx[socks]==0.27.0 openai==1.57.0 python-dotenv==1.0.1