mirror of
https://github.com/TehPeGaSuS/GitBot.git
synced 2026-06-27 01:45:44 +02:00
Update shlink.py
This commit is contained in:
@@ -1,10 +1,7 @@
|
||||
"""Shlink short-URL client.
|
||||
|
||||
"""
|
||||
Shlink short-URL client.
|
||||
Provides a single async helper, ``shorten(url)``, that calls the Shlink
|
||||
REST API and returns the shortened URL. Returns the original URL unchanged
|
||||
on any error.
|
||||
|
||||
Requires: httpx
|
||||
REST API via httpx. Returns the original URL unchanged on any error.
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -23,23 +20,44 @@ class ShlinkClient:
|
||||
|
||||
async def shorten(self, url: str) -> str:
|
||||
"""Return a shortened URL, or ``url`` unchanged on failure."""
|
||||
payload = {"longUrl": url, "findIfExists": True}
|
||||
payload = {
|
||||
"longUrl": url,
|
||||
"findIfExists": True
|
||||
}
|
||||
if self._domain:
|
||||
payload["domain"] = self._domain
|
||||
|
||||
headers = {"X-Api-Key": self._api_key, "Content-Type": "application/json"}
|
||||
headers = {
|
||||
"X-Api-Key": self._api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
||||
resp = await client.post(self._endpoint, json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
return resp.json()["shortUrl"]
|
||||
data = resp.json()
|
||||
|
||||
short = data["shortUrl"]
|
||||
log.debug("Shortened %s → %s", url, short)
|
||||
return short
|
||||
except Exception as e:
|
||||
log.warning("Shlink error for %s: %s", url, e)
|
||||
return url
|
||||
|
||||
def from_config(cfg: dict) -> "ShlinkClient | None":
|
||||
if not cfg.get("enabled", True): return None
|
||||
base, api_key = cfg.get("url", "").strip(), cfg.get("api_key", "").strip()
|
||||
if not base or not api_key: return None
|
||||
return ShlinkClient(base, api_key, int(cfg.get("timeout", 5)), cfg.get("domain"))
|
||||
"""Build a ShlinkClient from the [shlink] config section."""
|
||||
if not cfg.get("enabled", True):
|
||||
return None
|
||||
base = cfg.get("url", "").strip()
|
||||
api_key = cfg.get("api_key", "").strip()
|
||||
if not base or not api_key:
|
||||
if base or api_key:
|
||||
log.warning("[shlink] Both 'url' and 'api_key' are required — disabling")
|
||||
return None
|
||||
return ShlinkClient(
|
||||
base_url=base,
|
||||
api_key=api_key,
|
||||
timeout=int(cfg.get("timeout", 5)),
|
||||
domain=cfg.get("domain") or None,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user