Skip to content

Commit

Permalink
Use custom user-agent for Mastodon calls
Browse files Browse the repository at this point in the history
  • Loading branch information
russss committed Dec 7, 2024
1 parent 1858ae3 commit 3b87ef1
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions polybot/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
from atproto import Client, models # type: ignore
from atproto_client.exceptions import RequestException # type: ignore
from mastodon import Mastodon as MastodonClient # type: ignore
from importlib.metadata import version
import httpx

from .image import Image

POLYBOT_VERSION = version("polybot")


class PostError(Exception):
"""Raised when there was an error posting"""
Expand All @@ -29,6 +32,9 @@ def __init__(self, config, live: bool) -> None:
self.log = logging.getLogger(__name__)
self.config = config
self.live = live
self.user_agent = (
f"polybot/{POLYBOT_VERSION} (https://github.com/russss/polybot)"
)

def auth(self) -> None:
raise NotImplementedError()
Expand Down Expand Up @@ -212,6 +218,10 @@ class Mastodon(Service):
max_length_image = 500
max_image_size = int(16e6)

def __init__(self, config, live: bool):
super().__init__(config, live)
self.http = httpx.Client(headers={"User-Agent": self.user_agent})

def auth(self):
self.update_instance_info()

Expand All @@ -224,6 +234,7 @@ def auth(self):
"mastodon", "version_check_mode", fallback="none"
),
api_base_url=base_url,
user_agent=self.user_agent,
)
self.log.info("Connected to %s at %s", self.software, base_url)
self.log.info(
Expand All @@ -236,7 +247,7 @@ def fetch_endpoint(self, path):
base_url = self.config.get("mastodon", "base_url")
if base_url is None:
return None
res = httpx.get(base_url + path)
res = self.http.get(base_url + path)
if res.status_code != 200:
return None
return res.json()
Expand All @@ -254,7 +265,7 @@ def update_instance_info(self):
if not nodeinfo_url:
return None

res = httpx.get(nodeinfo_url)
res = self.http.get(nodeinfo_url)
if res.status_code != 200:
return None

Expand Down Expand Up @@ -328,6 +339,7 @@ def setup(self):
client_secret=client_secret,
api_base_url=base_url,
version_check_mode="created" if actually_mastodon else "none",
user_agent=self.user_agent,
)

req_url = mastodon.auth_request_url()
Expand Down

0 comments on commit 3b87ef1

Please sign in to comment.