Coverage for notifications/adapters/discord.py: 97.56%

37 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1"""Discord, through a per-channel webhook.""" 

2 

3from __future__ import annotations 

4 

5from typing import ClassVar 

6 

7import httpx 

8from discord_notify import DiscordWebhookClient 

9 

10from notifications.adapters.base import Capability, ChannelAdapter, DeliveryResult 

11 

12TIMEOUT_SECONDS = 10.0 

13 

14 

15class DiscordAdapter(ChannelAdapter): 

16 id: ClassVar[str] = "discord" 

17 label: ClassVar[str] = "Discord" 

18 icon: ClassVar[str] = "💬" 

19 invite_pattern: ClassVar[str] = r"^https://(discord\.gg|discord\.com/invite)/[A-Za-z0-9_-]{2,64}$" 

20 invite_error: ClassVar[str] = "Must be a Discord invite link (https://discord.gg/...)" 

21 placeholder: ClassVar[str] = "https://discord.com/api/webhooks/…/…" 

22 hint: ClassVar[str] = ( 

23 "Create a webhook on your Discord channel (Channel Settings → Integrations → Webhooks) and paste the full URL." 

24 ) 

25 setup_steps: ClassVar[tuple[str, ...]] = ( 

26 "You need the Manage Webhooks permission on the Discord server.", 

27 "Open the channel's settings (gear icon) → Integrations → Webhooks → New Webhook.", 

28 "Name it Missing Table, make sure the right channel is selected, and save.", 

29 "Click Copy Webhook URL and paste it here. Treat it like a password: anyone with it can post.", 

30 "Then click Send test to confirm a message arrives.", 

31 "A text channel gets every update as its own message. For one post per match, point the " 

32 "webhook at a Forum channel instead and tick One post per match below.", 

33 ) 

34 player_setup_steps: ClassVar[tuple[str, ...]] = ( 

35 "Players get two channels: club announcements (read-only, players react) and a squad " 

36 "channel for team chat. Make each visible only to its role, so fans never see them.", 

37 "Club announcements: Channel settings → Permissions → the players' role: deny Send Messages, " 

38 "Send Messages in Threads, Create Public Threads and Create Private Threads.", 

39 "Keep View Channel, Read Message History and Add Reactions allowed. Reacting needs Read Message History.", 

40 "Squad chat: leave Send Messages on for the squad's role. It is the team's chat.", 

41 "Test from a player account: react but not post in announcements, chat in the squad channel.", 

42 ) 

43 age_note: ClassVar[str | None] = "Discord requires members to be at least 13, and older in some countries." 

44 destination_pattern: ClassVar[str] = r"^https://discord(app)?\.com/api/webhooks/\d+/[\w-]+$" 

45 destination_error: ClassVar[str] = "Discord destination must be a webhook URL" 

46 # Discord's minimum age is 13; U14 is the youngest squad that clears it. 

47 min_player_age: ClassVar[int | None] = 14 

48 

49 # Match threads (SB-1606): a webhook in a forum channel. 

50 capabilities: ClassVar[frozenset[Capability]] = frozenset({Capability.THREADS}) 

51 

52 def _deliver_in_thread( 

53 self, destination: str, content: str, thread_ref: str | None, thread_name: str | None 

54 ) -> DeliveryResult: 

55 """POST to the webhook with wait=true so Discord returns the message. 

56 

57 `thread_name` makes a new forum post (forum and media channels only); 

58 `thread_id` posts into an existing one. A message posted in a thread 

59 carries the thread as its channel_id, which is how the new post's id 

60 comes back for follow-ups. Send test on a forum channel checks this 

61 live: it creates a post, then replies into it with that id. 

62 """ 

63 params: dict[str, str] = {"wait": "true"} 

64 body: dict[str, str] = {"content": content} 

65 if thread_ref: 

66 params["thread_id"] = thread_ref 

67 elif thread_name: 67 ↛ 69line 67 didn't jump to line 69 because the condition on line 67 was always true

68 body["thread_name"] = thread_name[:100] 

69 response = httpx.post(destination, params=params, json=body, timeout=TIMEOUT_SECONDS) 

70 response.raise_for_status() 

71 data = response.json() if response.content else {} 

72 message_id = data.get("id") 

73 thread = data.get("channel_id") or thread_ref 

74 return DeliveryResult( 

75 message_ref=None if message_id is None else str(message_id), 

76 thread_ref=None if thread is None else str(thread), 

77 ) 

78 

79 def _deliver(self, destination: str, content: str) -> DeliveryResult: 

80 # Discord-flavored markdown is permissive, so the text goes as-is. 

81 response = DiscordWebhookClient(webhook_url=destination).send(content) 

82 # A webhook answers 204 with no body unless asked to wait. 

83 message_id = (response or {}).get("id") 

84 return DeliveryResult(message_ref=None if message_id is None else str(message_id))