Coverage for src/copytrading_engine/trading/adapters/channel_history.py: 98%
45 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Read a Discord channel's recent posts so the model can learn a guru's style."""
3import asyncio
4import logging
5from collections.abc import Callable
7import discord
9from copytrading_engine.shared.cleanup import close_logged
10from copytrading_engine.shared.owner_facing import OwnerFacingError
11from copytrading_engine.sources.source import (
12 InvalidSourceMessage,
13 envelope,
14 require_history_channel,
15)
17log = logging.getLogger(__name__)
20class ChannelHistoryError(OwnerFacingError):
21 """Discord could not provide the channel's recent posts."""
24class DiscordChannelHistory:
25 """Log in with the owner's token, read recent text posts, and log out again."""
27 def __init__(
28 self,
29 *,
30 client_factory: Callable[..., discord.Client] = discord.Client,
31 timeout_seconds: float = 45,
32 ) -> None:
33 if timeout_seconds <= 0:
34 raise ValueError("History timeout must be positive")
35 self._client_factory = client_factory
36 self._timeout_seconds = timeout_seconds
38 async def recent_posts(
39 self, token: str, channel_id: str, author_id: str | None, limit: int
40 ) -> tuple[str, ...]:
41 """Newest-last text of up to `limit` posts, optionally from one author."""
42 client = self._client_factory()
43 try:
44 async with asyncio.timeout(self._timeout_seconds):
45 await client.login(token)
46 channel = require_history_channel(await client.fetch_channel(int(channel_id)))
47 posts: list[str] = []
48 async for message in channel.history(limit=limit * 3):
49 if author_id is not None and str(message.author.id) != author_id:
50 continue
51 # The same text the live pipeline reads: message body plus embeds.
52 try:
53 text = envelope(message).text.strip()
54 except InvalidSourceMessage:
55 continue
56 if text:
57 posts.append(text)
58 if len(posts) == limit:
59 break
60 return tuple(reversed(posts))
61 except asyncio.CancelledError:
62 raise
63 except TimeoutError:
64 raise ChannelHistoryError(
65 "Discord took too long to return the channel's history."
66 ) from None
67 except discord.Forbidden:
68 raise ChannelHistoryError("Discord refused to show this channel's history.") from None
69 except discord.LoginFailure:
70 raise ChannelHistoryError("Discord rejected the saved token.") from None
71 except discord.HTTPException, ValueError:
72 raise ChannelHistoryError("Discord could not read this channel.") from None
73 finally:
74 await close_logged(client.close, resource="channel_history", log=log)