Coverage for src/copytrading_engine/trading/adapters/notifications.py: 98%

66 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-16 16:55 +0000

1"""Optional plain-text alert delivery, to Telegram or a Discord webhook, for committed local 

2notification outboxes.""" 

3 

4import asyncio 

5import http.client 

6import json 

7from collections.abc import Mapping 

8from typing import Protocol 

9from urllib.parse import urlsplit 

10 

11from copytrading_engine.shared.notification_models import NotificationPayload 

12from copytrading_engine.trading.domain.config import NotificationConfiguration 

13 

14_DISCORD_HOSTS = frozenset( 

15 {"discord.com", "discordapp.com", "ptb.discord.com", "canary.discord.com"} 

16) 

17# Discord rejects a message longer than this. 

18_DISCORD_MESSAGE_LIMIT = 2000 

19 

20 

21class AlertSender(Protocol): 

22 async def send(self, payload: NotificationPayload) -> None: ... 

23 

24 

25def alert_sender(configuration: NotificationConfiguration, secret: str) -> AlertSender: 

26 """The sender for the configured service; the secret is a bot token or a webhook URL.""" 

27 if configuration.service == "discord": 

28 return DiscordWebhookNotifier(secret) 

29 if configuration.chat_id is None: 29 ↛ 30line 29 didn't jump to line 30 because the condition on line 29 was never true

30 raise ValueError("Telegram alerts need a chat ID") 

31 return TelegramNotifier(secret, configuration.chat_id) 

32 

33 

34def discord_webhook(url: str) -> tuple[str, str]: 

35 """The host and path of a Discord webhook URL, or ValueError; never echoes the URL, which holds 

36 the webhook's secret.""" 

37 parts = urlsplit(url.strip()) 

38 if ( 

39 parts.scheme != "https" 

40 or parts.hostname not in _DISCORD_HOSTS 

41 or parts.port is not None 

42 or parts.username 

43 or parts.password 

44 or parts.query 

45 or parts.fragment 

46 or not parts.path.startswith("/api/webhooks/") 

47 or len(parts.path.split("/")) != 5 

48 ): 

49 raise ValueError("Discord alerts need a channel webhook URL") 

50 return parts.hostname, parts.path 

51 

52 

53class DiscordWebhookNotifier: 

54 def __init__(self, url: str) -> None: 

55 self._host, self._path = discord_webhook(url) 

56 

57 async def send(self, payload: NotificationPayload) -> None: 

58 await asyncio.to_thread(self._send, _render(payload.annotations)) 

59 

60 def _send(self, text: str) -> None: 

61 connection = http.client.HTTPSConnection(self._host, timeout=5) 

62 try: 

63 body = json.dumps( 

64 { 

65 "content": text[:_DISCORD_MESSAGE_LIMIT], 

66 # An alert never pings anyone, whatever its text says. 

67 "allowed_mentions": {"parse": []}, 

68 } 

69 ).encode() 

70 connection.request( 

71 "POST", self._path, body=body, headers={"Content-Type": "application/json"} 

72 ) 

73 response = connection.getresponse() 

74 response.read(4096) 

75 if response.status not in {200, 204}: 

76 raise RuntimeError("Discord delivery was not accepted") 

77 except Exception: # noqa: BLE001 - replace URL-bearing errors before re-raising 

78 # HTTP exception strings can contain the webhook path, which is its secret. 

79 raise RuntimeError("Discord delivery is unavailable") from None 

80 finally: 

81 connection.close() 

82 

83 

84class TelegramNotifier: 

85 def __init__(self, token: str, chat_id: str) -> None: 

86 if not token or not chat_id: 

87 raise ValueError("Telegram token and chat ID are required") 

88 self._token = token 

89 self._chat_id = chat_id 

90 

91 async def send(self, payload: NotificationPayload) -> None: 

92 await asyncio.to_thread(self._send, _render(payload.annotations)) 

93 

94 def _send(self, text: str) -> None: 

95 connection = http.client.HTTPSConnection("api.telegram.org", timeout=5) 

96 try: 

97 body = json.dumps({"chat_id": self._chat_id, "text": text}).encode() 

98 connection.request( 

99 "POST", 

100 f"/bot{self._token}/sendMessage", 

101 body=body, 

102 headers={"Content-Type": "application/json"}, 

103 ) 

104 response = connection.getresponse() 

105 response.read(4096) 

106 if response.status != 200: 

107 raise RuntimeError("Telegram delivery was not accepted") 

108 except Exception: # noqa: BLE001 - replace token-bearing errors before re-raising 

109 # HTTP exception strings and URLs can contain the bot token. 

110 raise RuntimeError("Telegram delivery is unavailable") from None 

111 finally: 

112 connection.close() 

113 

114 

115def _render(annotations: Mapping[str, str]) -> str: 

116 parts = [annotations.get("summary", "Trading update")] 

117 for field in ("evidence", "impact", "action"): 

118 value = annotations.get(field) 

119 if value: 

120 parts.append(value) 

121 return "\n\n".join(parts)[:3900]