Add HTTP session options (#46)

Squash and merge PR #46
This commit is contained in:
Slipstream 2025-06-10 20:50:23 -06:00 committed by GitHub
parent a4aa4335a5
commit 36b06c6c7a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 69 additions and 5 deletions

View File

@ -86,6 +86,22 @@ setup_logging(logging.INFO)
setup_logging(logging.DEBUG, file="bot.log") 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` ### Defining Subcommands with `AppCommandGroup`
```python ```python

View File

@ -73,6 +73,9 @@ class Client:
command_prefix (Union[str, List[str], Callable[['Client', Message], Union[str, List[str]]]]): command_prefix (Union[str, List[str], Callable[['Client', Message], Union[str, List[str]]]]):
The prefix(es) for commands. Defaults to '!'. The prefix(es) for commands. Defaults to '!'.
verbose (bool): If True, print raw HTTP and Gateway traffic for debugging. 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__( def __init__(
@ -89,6 +92,7 @@ class Client:
shard_count: Optional[int] = None, shard_count: Optional[int] = None,
gateway_max_retries: int = 5, gateway_max_retries: int = 5,
gateway_max_backoff: float = 60.0, gateway_max_backoff: float = 60.0,
http_options: Optional[Dict[str, Any]] = None,
): ):
if not token: if not token:
raise ValueError("A bot token must be provided.") raise ValueError("A bot token must be provided.")
@ -102,7 +106,11 @@ class Client:
setup_global_error_handler(self.loop) setup_global_error_handler(self.loop)
self.verbose: bool = verbose 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._event_dispatcher: EventDispatcher = EventDispatcher(client_instance=self)
self._gateway: Optional[GatewayClient] = ( self._gateway: Optional[GatewayClient] = (
None # Initialized in run() or connect() None # Initialized in run() or connect()

View File

@ -40,11 +40,26 @@ class HTTPClient:
token: str, token: str,
client_session: Optional[aiohttp.ClientSession] = None, client_session: Optional[aiohttp.ClientSession] = None,
verbose: bool = False, 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.token = token
self._session: Optional[aiohttp.ClientSession] = ( self._session: Optional[aiohttp.ClientSession] = client_session
client_session # Can be externally managed self._session_kwargs: Dict[str, Any] = session_kwargs
)
self.user_agent = f"DiscordBot (https://github.com/Slipstreamm/disagreement, {__version__})" # Customize URL self.user_agent = f"DiscordBot (https://github.com/Slipstreamm/disagreement, {__version__})" # Customize URL
self.verbose = verbose self.verbose = verbose
@ -53,7 +68,7 @@ class HTTPClient:
async def _ensure_session(self): async def _ensure_session(self):
if self._session is None or self._session.closed: if self._session is None or self._session.closed:
self._session = aiohttp.ClientSession() self._session = aiohttp.ClientSession(**self._session_kwargs)
async def close(self): async def close(self):
"""Closes the underlying aiohttp.ClientSession.""" """Closes the underlying aiohttp.ClientSession."""

View File

@ -24,4 +24,5 @@ client.cache.clear()
- [Components](using_components.md) - [Components](using_components.md)
- [Slash Commands](slash_commands.md) - [Slash Commands](slash_commands.md)
- [Voice Features](voice_features.md) - [Voice Features](voice_features.md)
- [HTTP Client Options](http_client.md)

20
docs/http_client.md Normal file
View File

@ -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.

View File

@ -14,3 +14,4 @@ Pass `before` or `after` to control the range of messages returned. The paginato
- [Caching](caching.md) - [Caching](caching.md)
- [Typing Indicator](typing_indicator.md) - [Typing Indicator](typing_indicator.md)
- [HTTP Client Options](http_client.md)

View File

@ -19,6 +19,7 @@ Use `AppCommandGroup` to group related commands. See the [components guide](usin
- [Components](using_components.md) - [Components](using_components.md)
- [Caching](caching.md) - [Caching](caching.md)
- [Voice Features](voice_features.md) - [Voice Features](voice_features.md)
- [HTTP Client Options](http_client.md)
## Command Persistence ## Command Persistence

View File

@ -165,4 +165,5 @@ A container can itself contain layout and content components, letting you build
- [Slash Commands](slash_commands.md) - [Slash Commands](slash_commands.md)
- [Caching](caching.md) - [Caching](caching.md)
- [Voice Features](voice_features.md) - [Voice Features](voice_features.md)
- [HTTP Client Options](http_client.md)

View File

@ -16,4 +16,5 @@ Voice support is optional and may require additional system dependencies such as
- [Components](using_components.md) - [Components](using_components.md)
- [Slash Commands](slash_commands.md) - [Slash Commands](slash_commands.md)
- [Caching](caching.md) - [Caching](caching.md)
- [HTTP Client Options](http_client.md)