Coverage for bot/irc_protocol.py: 95%

40 statements  

« prev     ^ index     » next       coverage.py v7.10.7, created at 2026-02-25 12:30 -0300

1import re 

2 

3IRC_PRIVMSG_PATTERN = re.compile( 

4 r"^(?:@(?P<tags>[^ ]+) )?:(?P<author>[^!]+)![^ ]+ PRIVMSG #(?P<channel>[^ ]+) :(?P<message>.*)$" 

5) 

6IRC_NOTICE_PATTERN = re.compile( 

7 r"^(?:@(?P<tags>[^ ]+) )?:[^ ]+ NOTICE (?P<target>[^ ]+) :(?P<message>.*)$", 

8 re.IGNORECASE, 

9) 

10IRC_JOIN_PATTERN = re.compile( 

11 r"^(?:@(?P<tags>[^ ]+) )?:(?P<author>[^!]+)![^ ]+ JOIN #(?P<channel>[^ ]+)$", 

12 re.IGNORECASE, 

13) 

14IRC_PART_PATTERN = re.compile( 

15 r"^(?:@(?P<tags>[^ ]+) )?:(?P<author>[^!]+)![^ ]+ PART #(?P<channel>[^ ]+)(?: :(?P<reason>.*))?$", 

16 re.IGNORECASE, 

17) 

18IRC_WELCOME_PATTERN = re.compile(r"^:[^ ]+\s001\s", re.IGNORECASE) 

19IRC_NOTICE_DELIVERY_BLOCK_IDS = { 

20 "msg_bad_characters", 

21 "msg_banned", 

22 "msg_channel_blocked", 

23 "msg_channel_suspended", 

24 "msg_duplicate", 

25 "msg_emoteonly", 

26 "msg_followersonly", 

27 "msg_followersonly_followed", 

28 "msg_r9k", 

29 "msg_requires_verified_phone_number", 

30 "msg_slowmode", 

31 "msg_subsonly", 

32 "msg_suspended", 

33 "msg_timedout", 

34} 

35IRC_NOTICE_DELIVERY_BLOCK_HINTS = ( 

36 "banned", 

37 "followers-only", 

38 "followers only", 

39 "phone number must be verified", 

40 "requires a verified phone number", 

41 "room is no longer available", 

42 "subscribers-only", 

43 "subscribers only", 

44 "timed out", 

45 "you are permanently banned", 

46) 

47 

48 

49class IrcAuthor: 

50 def __init__(self, login: str, tags: dict[str, str]) -> None: 

51 self.login = login 

52 self.name = tags.get("display-name") or login 

53 self.id = tags.get("user-id", "") 

54 is_mod = tags.get("mod") == "1" or "moderator/" in tags.get("badges", "") 

55 self.is_mod = is_mod 

56 self.is_moderator = is_mod 

57 

58 

59class IrcMessageAdapter: 

60 def __init__(self, text: str, author: IrcAuthor) -> None: 

61 self.text = text 

62 self.author = author 

63 self.echo = False 

64 

65 

66def parse_irc_tags(raw_tags: str) -> dict[str, str]: 

67 if not raw_tags: 

68 return {} 

69 parsed: dict[str, str] = {} 

70 for item in raw_tags.split(";"): 

71 if "=" in item: 

72 key, value = item.split("=", maxsplit=1) 

73 else: 

74 key, value = item, "" 

75 parsed[key] = value.replace(r"\s", " ").replace(r"\:", ";").replace(r"\\", "\\") 

76 return parsed 

77 

78 

79def flatten_chat_text(text: str) -> str: 

80 lines = [line.strip() for line in (text or "").splitlines() if line.strip()] 

81 return " | ".join(lines) 

82 

83 

84def is_irc_notice_delivery_block(msg_id: str, message: str) -> bool: 

85 normalized_id = (msg_id or "").strip().lower() 

86 if normalized_id in IRC_NOTICE_DELIVERY_BLOCK_IDS: 

87 return True 

88 

89 lowered_message = (message or "").strip().lower() 

90 return any(marker in lowered_message for marker in IRC_NOTICE_DELIVERY_BLOCK_HINTS)