Coverage for src/retrospeedlab/backend/twitch/support.py: 80%

112 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-12-04 00:01 +0000

1import asyncio 

2import re 

3from datetime import datetime 

4from decimal import Decimal 

5 

6import httpx 

7from loguru import logger 

8from sqlalchemy.orm import Session 

9 

10from ..database import engine 

11from ..kofi.payment import NAME_LENGTH, TWITCH_BITS, TWITCH_GIFT, TWITCH_SUB, Donation 

12from ..kofi.router import recorded 

13from ..kofi.thanks import thanks 

14from ..oauth.session import OAuthSession 

15from ..streamelements.chat import tell 

16from .failures import DOWN, FAILURES 

17from .helix import helix_client, send 

18from .predictions import granted_scopes 

19from .rewards import SUBSCRIPTIONS_PATH 

20 

21CHEER = "channel.cheer" 

22SUBSCRIBE = "channel.subscribe" 

23RESUBSCRIBE = "channel.subscription.message" 

24GIFT = "channel.subscription.gift" 

25SUBSCRIPTIONS_SCOPE = "channel:read:subscriptions" 

26SCOPES = { 

27 CHEER: "bits:read", 

28 SUBSCRIBE: SUBSCRIPTIONS_SCOPE, 

29 RESUBSCRIBE: SUBSCRIPTIONS_SCOPE, 

30 GIFT: SUBSCRIPTIONS_SCOPE, 

31} 

32BITS = "BITS" 

33SUBS = "SUBS" 

34TIERS = {"1000": "Tier 1", "2000": "Tier 2", "3000": "Tier 3"} 

35CHAT_TITLE = "💜 Thank you!" 

36SCOPE_CHECK_SECONDS = 300 

37RETRY_SECONDS = 30 

38# shortcut: every word ending in digits counts as a cheermote (Cheer100, Kappa50), so words like level2 go too 

39CHEERMOTE = re.compile(r"\b[A-Za-z]+\d+\b") 

40 

41 

42def _donation(metadata: dict, event: dict, kind: str, amount: int, first: bool, message: str | None) -> Donation: 

43 anonymous = "is_anonymous" in event and event["is_anonymous"] 

44 return Donation( 

45 message_id=metadata["message_id"], 

46 transaction_id=metadata["message_id"], 

47 at=datetime.fromisoformat(metadata["message_timestamp"]), 

48 kind=kind, 

49 public=not anonymous, 

50 name=None if anonymous or event["user_name"] is None else event["user_name"][:NAME_LENGTH], 

51 message=message, 

52 amount=Decimal(amount), 

53 currency=BITS if kind == TWITCH_BITS else SUBS, 

54 subscription_payment=kind != TWITCH_BITS, 

55 first_payment=first, 

56 tier=TIERS[event["tier"]] if "tier" in event else None, 

57 ) 

58 

59 

60def support_donation(message: dict) -> Donation | None: 

61 metadata, event = message["metadata"], message["payload"]["event"] 

62 kind = metadata["subscription_type"] 

63 if kind == CHEER: 

64 return _donation(metadata, event, TWITCH_BITS, event["bits"], False, CHEERMOTE.sub("", event["message"])) 

65 if kind == SUBSCRIBE: 

66 return None if event["is_gift"] else _donation(metadata, event, TWITCH_SUB, 1, True, None) 

67 if kind == RESUBSCRIBE: 

68 return _donation(metadata, event, TWITCH_SUB, 1, False, event["message"]["text"]) 

69 if kind == GIFT: 

70 return _donation(metadata, event, TWITCH_GIFT, event["total"], False, None) 

71 raise LookupError(f"Twitch sent a {kind} notification nobody follows") 

72 

73 

74def stored(donation: Donation) -> bool: 

75 with Session(engine) as session: 

76 return recorded(session, donation) 

77 

78 

79class SupportFeed: 

80 def __init__(self, session: OAuthSession) -> None: 

81 self.session = session 

82 self.events: asyncio.Queue[dict] = asyncio.Queue() 

83 self.followed: set[str] = set() 

84 self.socket = "" 

85 self.broadcaster = "" 

86 

87 async def subscribe(self, client: httpx.AsyncClient, session_id: str, broadcaster: str) -> None: 

88 self.socket, self.broadcaster, self.followed = session_id, broadcaster, set() 

89 await self._follow_granted(client) 

90 

91 async def _follow_granted(self, client: httpx.AsyncClient) -> None: 

92 granted = set(await granted_scopes(self.session)) 

93 for kind, scope in SCOPES.items(): 

94 if kind in self.followed or scope not in granted: 

95 continue 

96 condition = {"broadcaster_user_id": self.broadcaster} 

97 transport = {"method": "websocket", "session_id": self.socket} 

98 body = {"type": kind, "version": "1", "condition": condition, "transport": transport} 

99 await send(client, "POST", SUBSCRIPTIONS_PATH, {}, body) 

100 self.followed.add(kind) 

101 logger.info(f"Twitch {kind} is followed") 

102 missing = sorted({scope for kind, scope in SCOPES.items() if kind not in self.followed}) 

103 if missing: 

104 logger.warning(f"Twitch Bits and subs wait for the owner to sign Twitch in again with {' '.join(missing)}") 

105 

106 async def watch_scopes(self) -> None: 

107 while True: 

108 await asyncio.sleep(SCOPE_CHECK_SECONDS) 

109 if not self.socket or self.followed == set(SCOPES): 

110 continue 

111 try: 

112 async with await helix_client(self.session) as client: 

113 await self._follow_granted(client) 

114 except FAILURES as error: 

115 logger.error(f"Twitch Bits and subs could not be followed yet: {error!r}") 

116 

117 def receive(self, message: dict) -> None: 

118 self.events.put_nowait(message) 

119 

120 async def run(self) -> None: 

121 while True: 

122 message = await self.events.get() 

123 while not await self._thanked(message): 

124 await asyncio.sleep(RETRY_SECONDS) 

125 

126 async def _thanked(self, message: dict) -> bool: 

127 try: 

128 return await self.thank(message) 

129 except (KeyError, LookupError, ValueError) as error: 

130 logger.error(f"Twitch sent a support notification the backend cannot read: {error!r}") 

131 return True 

132 

133 async def thank(self, message: dict) -> bool: 

134 donation = support_donation(message) 

135 if donation is None: 

136 return True 

137 said = thanks(donation) 

138 try: 

139 fresh = await asyncio.to_thread(stored, donation) 

140 except DOWN as error: 

141 logger.error(f"Twitch {donation.kind} of {donation.name} waits for the database: {error!r}") 

142 return False 

143 if not fresh: 

144 logger.info(f"Twitch sent {donation.message_id} again") 

145 return True 

146 logger.info(f"Twitch: {'nothing to thank' if said is None else said.text}") 

147 if said is not None: 

148 await tell(f"{CHAT_TITLE} {said.text}") 

149 return True