Add Webhook.from_url utility (#14)
This commit is contained in:
parent
7f0b03fa69
commit
09fae8a489
@ -6,6 +6,7 @@ Data models for Discord objects.
|
||||
|
||||
import json
|
||||
import asyncio
|
||||
import aiohttp # pylint: disable=import-error
|
||||
from typing import Optional, TYPE_CHECKING, List, Dict, Any, Union
|
||||
|
||||
from .errors import DisagreementException, HTTPException
|
||||
@ -1225,6 +1226,33 @@ class Webhook:
|
||||
def __repr__(self) -> str:
|
||||
return f"<Webhook id='{self.id}' name='{self.name}'>"
|
||||
|
||||
@classmethod
|
||||
def from_url(
|
||||
cls, url: str, session: Optional[aiohttp.ClientSession] = None
|
||||
) -> "Webhook":
|
||||
"""Create a minimal :class:`Webhook` from a webhook URL.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
url:
|
||||
The full Discord webhook URL.
|
||||
session:
|
||||
Unused for now. Present for API compatibility.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Webhook
|
||||
A webhook instance containing only the ``id``, ``token`` and ``url``.
|
||||
"""
|
||||
|
||||
parts = url.rstrip("/").split("/")
|
||||
if len(parts) < 2:
|
||||
raise ValueError("Invalid webhook URL")
|
||||
token = parts[-1]
|
||||
webhook_id = parts[-2]
|
||||
|
||||
return cls({"id": webhook_id, "token": token, "url": url})
|
||||
|
||||
|
||||
# --- Message Components ---
|
||||
|
||||
|
@ -31,3 +31,14 @@ from disagreement.models import Webhook
|
||||
|
||||
print(webhook.id, webhook.name)
|
||||
```
|
||||
|
||||
## Create a Webhook from a URL
|
||||
|
||||
You can construct a `Webhook` object from an existing webhook URL without any API calls:
|
||||
|
||||
```python
|
||||
from disagreement.models import Webhook
|
||||
|
||||
webhook = Webhook.from_url("https://discord.com/api/webhooks/123/token")
|
||||
print(webhook.id, webhook.token)
|
||||
```
|
||||
|
@ -138,3 +138,14 @@ async def test_client_delete_webhook_calls_http():
|
||||
await client.delete_webhook("1")
|
||||
|
||||
http.delete_webhook.assert_awaited_once_with("1")
|
||||
|
||||
|
||||
def test_webhook_from_url_parses_id_and_token():
|
||||
from disagreement.models import Webhook
|
||||
|
||||
url = "https://discord.com/api/webhooks/123/token"
|
||||
webhook = Webhook.from_url(url)
|
||||
|
||||
assert webhook.id == "123"
|
||||
assert webhook.token == "token"
|
||||
assert webhook.url == url
|
||||
|
Loading…
x
Reference in New Issue
Block a user