From e5f0d4e21053e53716bc119800d4ad289334e332 Mon Sep 17 00:00:00 2001 From: Bastian Neumann Date: Wed, 4 May 2022 21:45:19 +0200 Subject: [PATCH] Request tags for IRC messages After authentication send a request to enable tags for incoming messages. Message parsing is updated to deal with tagged messages. --- twitch/chat/chat.py | 11 +++++++++-- twitch/chat/irc.py | 3 +++ twitch/chat/message.py | 6 ++++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/twitch/chat/chat.py b/twitch/chat/chat.py index 5087000..0f08cd2 100644 --- a/twitch/chat/chat.py +++ b/twitch/chat/chat.py @@ -30,16 +30,23 @@ def _message_handler(self, data: bytes) -> None: # First messages are server connection messages, # which should be handled by joining the chat room. if not self.joined: + self.irc.activate_tags() self.irc.join_channel(self.channel) self.joined = True text = data.decode("UTF-8").strip('\n\r') if text.find('PRIVMSG') >= 0: - sender = text.split('!', 1)[0][1:] + if text[0] == '@': + block = text.split(' :') + tags = dict(t.split('=',1) for t in block[0][1:].split(';')) + sender = block[1].split('!', 1)[0] + else: + sender = text.split('!', 1)[0][1:] + tags = None message = text.split('PRIVMSG', 1)[1].split(':', 1)[1] self.on_next( - chat.Message(channel=self.channel, sender=sender, text=message, helix_api=self.helix, chat=self)) + chat.Message(channel=self.channel, sender=sender, text=message, helix_api=self.helix, chat=self, tags=tags)) def send(self, message: str) -> None: while not self.joined: diff --git a/twitch/chat/irc.py b/twitch/chat/irc.py index ea76d6e..e9e5b32 100644 --- a/twitch/chat/irc.py +++ b/twitch/chat/irc.py @@ -57,6 +57,9 @@ def authenticate(self) -> None: self.send_raw(f'PASS {self.password}') self.send_raw(f'NICK {self.nickname}') + def activate_tags(self) -> None: + self.send_raw(f'CAP REQ :twitch.tv/tags') + def join_channel(self, channel: str) -> None: channel = channel.lstrip('#') self.channels.append(channel) diff --git a/twitch/chat/message.py b/twitch/chat/message.py index f45607b..d0f9299 100644 --- a/twitch/chat/message.py +++ b/twitch/chat/message.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Dict, Optional from twitch.helix import User, Helix from .chat import Chat @@ -11,12 +11,14 @@ def __init__(self, sender: str, text: str, helix_api: Optional[Helix] = None, - chat: Optional[Chat] = None): + chat: Optional[Chat] = None, + tags: Optional[Dict] = None): self.channel: str = channel self.sender: str = sender self.text: str = text self.helix: Optional[Helix] = helix_api self.chat: Optional[Chat] = chat + self.tags: Optional[Dict] = tags @property def user(self) -> Optional[User]: