Coverage for notifications/moderation_alerts.py: 92.31%

44 statements  

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

1"""Telegram alert to the operator when a chat message is reported (SB-1309). 

2 

3App Store guideline 1.2 asks for a timely response to reports. A report that 

4only lands in a table is answered whenever someone next opens the admin 

5screen; this puts it in front of the operator straight away. The admin 

6attention badge counts the same reports, so nothing depends on the alert 

7arriving. 

8 

9Same destination and the same per-window cap as the ingest alerts 

10(notifications/ingest_alerts.py): a burst of reports — one abusive user, a 

11dozen parents — sends at most the cap, then one summary, then silence for the 

12rest of the hour. Every report is still recorded. 

13""" 

14 

15from __future__ import annotations 

16 

17import os 

18from datetime import UTC, datetime, timedelta 

19from typing import Any 

20 

21import structlog 

22 

23from notifications.ingest_alerts import CHAT_ID_ENV 

24from notifications.senders import send_to 

25 

26logger = structlog.get_logger() 

27 

28DEFAULT_MAX_ALERTS_PER_WINDOW = 10 

29WINDOW = timedelta(hours=1) 

30_MESSAGE_PREVIEW = 200 

31 

32 

33def _max_alerts_per_window() -> int: 

34 try: 

35 return int(os.getenv("MT_REPORT_ALERT_MAX_PER_HOUR", DEFAULT_MAX_ALERTS_PER_WINDOW)) 

36 except ValueError: 

37 return DEFAULT_MAX_ALERTS_PER_WINDOW 

38 

39 

40def _truncate(text: str) -> str: 

41 return text if len(text) <= _MESSAGE_PREVIEW else text[: _MESSAGE_PREVIEW - 1] + "…" 

42 

43 

44def _format(report: dict[str, Any], reporter_username: str | None) -> str: 

45 lines = [ 

46 "🚩 MT chat message reported", 

47 f"Reason: {report.get('reason')}", 

48 f"Author: {report.get('reported_username') or 'unknown'}", 

49 f"Reported by: {reporter_username or 'unknown'}", 

50 f"Match: {report.get('match_id')}", 

51 f"Message: {_truncate(report.get('message_text') or '')}", 

52 ] 

53 if report.get("details"): 53 ↛ 54line 53 didn't jump to line 54 because the condition on line 53 was never true

54 lines.append(f"Details: {_truncate(report['details'])}") 

55 lines.append("Review: GET /api/admin/content-reports?status=pending") 

56 return "\n".join(lines) 

57 

58 

59def alert_content_report(moderation_dao: Any, report: dict[str, Any], reporter_username: str | None) -> bool: 

60 """Send one Telegram alert for a new report. Returns whether one was sent. 

61 

62 Never raises: the report is already recorded, and a reporter must not see 

63 an error because the operator's alert channel is down or unconfigured. 

64 """ 

65 try: 

66 chat_id = os.getenv(CHAT_ID_ENV) 

67 if not chat_id: 

68 logger.info( 

69 "Content report recorded but not alerted — %s is unset", CHAT_ID_ENV, report_id=report.get("id") 

70 ) 

71 return False 

72 

73 window_start = (datetime.now(tz=UTC) - WINDOW).isoformat() 

74 # Includes this report, which is already inserted. 

75 earlier = moderation_dao.count_reports_since(window_start) - 1 

76 cap = _max_alerts_per_window() 

77 

78 if earlier > cap: 

79 return False 

80 if earlier == cap: 

81 send_to( 

82 "telegram", 

83 chat_id, 

84 f"🚩 MT chat: more than {cap} reports this hour. Further reports are recorded " 

85 "but not alerted — see GET /api/admin/content-reports?status=pending.", 

86 ) 

87 return True 

88 

89 send_to("telegram", chat_id, _format(report, reporter_username)) 

90 logger.info("Alerted on content report", report_id=report.get("id")) 

91 return True 

92 

93 except Exception: 

94 logger.exception("Could not alert on content report", report_id=report.get("id")) 

95 return False