From 36b06c6c7abe82ab0b4a0cffa682a000f21cf852 Mon Sep 17 00:00:00 2001 From: Slipstream Date: Tue, 10 Jun 2025 20:50:23 -0600 Subject: [PATCH] Add HTTP session options (#46) Squash and merge PR #46 --- README.md | 16 ++++++++++++++++ disagreement/client.py | 10 +++++++++- disagreement/http.py | 23 +++++++++++++++++++---- docs/caching.md | 1 + docs/http_client.md | 20 ++++++++++++++++++++ docs/message_history.md | 1 + docs/slash_commands.md | 1 + docs/using_components.md | 1 + docs/voice_features.md | 1 + 9 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 docs/http_client.md diff --git a/README.md b/README.md index cc88d4d..df44da5 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,22 @@ setup_logging(logging.INFO) setup_logging(logging.DEBUG, file="bot.log") ``` +### HTTP Session Options + +Pass additional keyword arguments to ``aiohttp.ClientSession`` using the +``http_options`` parameter when constructing :class:`disagreement.Client`: + +```python +client = disagreement.Client( + token=token, + http_options={"proxy": "http://localhost:8080"}, +) +``` + +These options are forwarded to ``HTTPClient`` when it creates the underlying +``aiohttp.ClientSession``. You can specify a custom ``connector`` or any other +session parameter supported by ``aiohttp``. + ### Defining Subcommands with `AppCommandGroup` ```python diff --git a/disagreement/client.py b/disagreement/client.py index 79e5757..e43401b 100644 --- a/disagreement/client.py +++ b/disagreement/client.py @@ -73,6 +73,9 @@ class Client: command_prefix (Union[str, List[str], Callable[['Client', Message], Union[str, List[str]]]]): The prefix(es) for commands. Defaults to '!'. verbose (bool): If True, print raw HTTP and Gateway traffic for debugging. + http_options (Optional[Dict[str, Any]]): Extra options passed to + :class:`HTTPClient` for creating the internal + :class:`aiohttp.ClientSession`. """ def __init__( @@ -89,6 +92,7 @@ class Client: shard_count: Optional[int] = None, gateway_max_retries: int = 5, gateway_max_backoff: float = 60.0, + http_options: Optional[Dict[str, Any]] = None, ): if not token: raise ValueError("A bot token must be provided.") @@ -102,7 +106,11 @@ class Client: setup_global_error_handler(self.loop) self.verbose: bool = verbose - self._http: HTTPClient = HTTPClient(token=self.token, verbose=verbose) + self._http: HTTPClient = HTTPClient( + token=self.token, + verbose=verbose, + **(http_options or {}), + ) self._event_dispatcher: EventDispatcher = EventDispatcher(client_instance=self) self._gateway: Optional[GatewayClient] = ( None # Initialized in run() or connect() diff --git a/disagreement/http.py b/disagreement/http.py index ee1e47c..f41e61e 100644 --- a/disagreement/http.py +++ b/disagreement/http.py @@ -40,11 +40,26 @@ class HTTPClient: token: str, client_session: Optional[aiohttp.ClientSession] = None, verbose: bool = False, + **session_kwargs: Any, ): + """Create a new HTTP client. + + Parameters + ---------- + token: + Bot token for authentication. + client_session: + Optional existing :class:`aiohttp.ClientSession`. + verbose: + If ``True``, log HTTP requests and responses. + **session_kwargs: + Additional options forwarded to :class:`aiohttp.ClientSession`, such + as ``proxy`` or ``connector``. + """ + self.token = token - self._session: Optional[aiohttp.ClientSession] = ( - client_session # Can be externally managed - ) + self._session: Optional[aiohttp.ClientSession] = client_session + self._session_kwargs: Dict[str, Any] = session_kwargs self.user_agent = f"DiscordBot (https://github.com/Slipstreamm/disagreement, {__version__})" # Customize URL self.verbose = verbose @@ -53,7 +68,7 @@ class HTTPClient: async def _ensure_session(self): if self._session is None or self._session.closed: - self._session = aiohttp.ClientSession() + self._session = aiohttp.ClientSession(**self._session_kwargs) async def close(self): """Closes the underlying aiohttp.ClientSession.""" diff --git a/docs/caching.md b/docs/caching.md index cd5fa38..2a1f7b0 100644 --- a/docs/caching.md +++ b/docs/caching.md @@ -24,4 +24,5 @@ client.cache.clear() - [Components](using_components.md) - [Slash Commands](slash_commands.md) - [Voice Features](voice_features.md) +- [HTTP Client Options](http_client.md) diff --git a/docs/http_client.md b/docs/http_client.md new file mode 100644 index 0000000..57c76fb --- /dev/null +++ b/docs/http_client.md @@ -0,0 +1,20 @@ +# HTTP Client Options + +Disagreement uses `aiohttp` for all HTTP requests. Additional options for the +underlying `aiohttp.ClientSession` can be provided when constructing a +`Client` or an `HTTPClient` directly. + +```python +import aiohttp +from disagreement import Client + +connector = aiohttp.TCPConnector(limit=50) +client = Client( + token="YOUR_TOKEN", + http_options={"proxy": "http://localhost:8080", "connector": connector}, +) +``` + +These options are passed through to `aiohttp.ClientSession` when the session is +created. You can set a proxy URL, provide a custom connector, or supply any +other supported session argument. diff --git a/docs/message_history.md b/docs/message_history.md index 7994000..7c7c5df 100644 --- a/docs/message_history.md +++ b/docs/message_history.md @@ -14,3 +14,4 @@ Pass `before` or `after` to control the range of messages returned. The paginato - [Caching](caching.md) - [Typing Indicator](typing_indicator.md) +- [HTTP Client Options](http_client.md) diff --git a/docs/slash_commands.md b/docs/slash_commands.md index 31f526c..888a344 100644 --- a/docs/slash_commands.md +++ b/docs/slash_commands.md @@ -19,6 +19,7 @@ Use `AppCommandGroup` to group related commands. See the [components guide](usin - [Components](using_components.md) - [Caching](caching.md) - [Voice Features](voice_features.md) +- [HTTP Client Options](http_client.md) ## Command Persistence diff --git a/docs/using_components.md b/docs/using_components.md index ac508b0..a5cb942 100644 --- a/docs/using_components.md +++ b/docs/using_components.md @@ -165,4 +165,5 @@ A container can itself contain layout and content components, letting you build - [Slash Commands](slash_commands.md) - [Caching](caching.md) - [Voice Features](voice_features.md) +- [HTTP Client Options](http_client.md) diff --git a/docs/voice_features.md b/docs/voice_features.md index 82265f6..4391862 100644 --- a/docs/voice_features.md +++ b/docs/voice_features.md @@ -16,4 +16,5 @@ Voice support is optional and may require additional system dependencies such as - [Components](using_components.md) - [Slash Commands](slash_commands.md) - [Caching](caching.md) +- [HTTP Client Options](http_client.md)