-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrb_timer.py
More file actions
2187 lines (1834 loc) · 73 KB
/
Copy pathbrb_timer.py
File metadata and controls
2187 lines (1834 loc) · 73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
BRB Timer for OBS Studio
https://github.com/beporter/brb-timer
"""
from __future__ import annotations
import base64
import contextlib
from dataclasses import dataclass
import datetime
import functools
import hashlib
import http
import inspect
import json
import logging
import os
import re
import socket
import ssl
import struct
import sys
from textwrap import dedent
import threading
import time
from typing import Callable, Dict
from urllib import error, parse, request
# =========================================================================
SCRIPT_NAME = "BRB Timer"
SCRIPT_VERSION = 1.1
LOG_LEVEL = logging.INFO # Standard python log levels. Ref: https://docs.python.org/3.12/library/logging.html#logging-levels
logging.basicConfig()
logging.getLogger().setLevel(LOG_LEVEL)
brblog = logging.getLogger(__name__)
brblog.setLevel(LOG_LEVEL)
# =========================================================================
try:
import obspython as S # type: ignore
except ImportError:
# This bit of code replaces the real obspython module with a
# testing mock. The script won't "work" without obs, but it'll
# let you run `python -i brb_timer.py` to access an interactive
# terminal without failing on
# `NameError: name 'obs' is not defined.` to let you test the
# rest of it.
from unittest.mock import Mock
S = Mock()
S.script_log = lambda _lvl, msg: print(msg)
logging.warning('obspython module unavailable. Replaced with a mock.')
# =========================================================================
class DEFAULTS:
AUTO_HIDE_SECS = 120
TEXT_TIMER = f"{SCRIPT_NAME} - Timer"
TRANSITION_SHOW = f"{SCRIPT_NAME} - Show Transition"
TRANSITION_HIDE = f"{SCRIPT_NAME} - Hide Transition"
###########################################################################
# Chat Commands and Messages
# =========================================================================
class COMMANDS:
BRB = "!brb"
BACK = "!back"
AT = "!at"
# =========================================================================
class Message(str):
def __call__(self, **kwargs):
return self.format(**kwargs)
# =========================================================================
class MessageMeta(type):
def __getattribute__(cls, name):
value = super().__getattribute__(name)
if isinstance(value, str) and not isinstance(value, Message):
return Message(value)
return value
# =========================================================================
class MESSAGES(metaclass=MessageMeta):
"""
This class cleans up the code that uses these format strings.
Instead of:
str.format(MESSAGES.BRB_STARTED, streamer='some user')
You can use:
MESSAGES.BRB_STARTED(streamer="some user")
"""
# Access control.
ONLY_MOD_START = f"Only mods can start a {COMMANDS.BRB}."
ONLY_MOD_END = f"Only mods can end a {COMMANDS.BRB} with {COMMANDS.BACK}."
# Reporting script state.
ALREADY_RUNNING = (
f"A {COMMANDS.BRB} is already running! "
f"Must use {COMMANDS.BACK} first."
)
NO_BRB = (
f"There's no {COMMANDS.BRB} running. "
f"A mod must use {COMMANDS.BRB} first."
)
BRB_STARTED = (
"{streamer} is taking a break! "
"Guess how long till they're back (without going over!) "
f"Type `{COMMANDS.AT} MM:SS` in chat!"
)
BRB_FINISHED = (
"{streamer} is back after {time}! "
"Winner is: {winner}. They were {diff} off."
)
BRB_FINISHED_NO_GUESSES = (
"{streamer} is back after {time}! "
"But there were no valid "
f"{COMMANDS.AT} guesses so there's no winner. "
"(Price is Right rules: closest without going over!)"
)
# Guessing.
BAD_GUESS = (
"Couldn't understand {user}'s guess. "
"Format is MINS:SECS. "
"For example: '1:35:42' means you think the streamer "
"will return in 1 hour, 35 mins and 42 seconds."
)
ALREADY_GUESSED = (
"{user} already guessed {guess}. "
"You can't change your guess!"
)
GUESS_ACCEPTED = "{user} guesses {guess}."
###########################################################################
# Convience datetime and timedelta methods
# =========================================================================
class DT:
#----------------------------------------------------------------------
@classmethod
def strfdelta(self, delta: int) -> str:
if delta >= 3600:
fmt = '%H:%M:%S'
elif delta >= 60:
fmt = '%M:%S'
else:
fmt = '%S secs'
return datetime.datetime.fromtimestamp(
delta,
tz=datetime.timezone.utc,
).strftime(fmt).lstrip('0')
#----------------------------------------------------------------------
@classmethod
def strpdelta(self, time_str: str) -> int | False:
"""
Parse the provided `[[HH:]MM:]SS` string into a integer number
of seconds.
Ref: timedelta https://stackoverflow.com/a/51916936/70876
Ref: regex https://stackoverflow.com/a/8318367/70876
"""
pattern = re.compile(
r'''
^(?:
(?:
(?P<hours>[01]?\d|2[0-3]):
)?
(?P<minutes>[0-5]?\d):
)?
(?P<seconds>[0-5]?\d)$
''',
re.X,
)
parts = pattern.match(time_str)
if parts is None:
return False
time_params = {name: float(param) for name, param
in parts.groupdict().items() if param}
return int(datetime.timedelta(**time_params).total_seconds())
###########################################################################
# Twitch Chat Client
# =========================================================================
@dataclass
class ChatMessage(object):
"""
Message passing container from the IRC client to the command parser.
"""
username: str
display_name: str
message: str
is_mod: bool
is_broadcaster: bool
# =========================================================================
type ChatMsgCallback = Callable[[ChatMessage], None]
# =========================================================================
class _WebSocket:
"""
Minimal RFC6455 WebSocket client implemented with only the
Python standard library.
"""
MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
#----------------------------------------------------------------------
def __init__(self, url: str, timeout: float = 10):
self.url = url
self.timeout = timeout
self.socket: socket.socket | ssl.SSLSocket | None = None
self._recv_buffer = bytearray()
self._fragment_buffer = bytearray()
self._fragment_opcode: int | None = None
#----------------------------------------------------------------------
def connect(self) -> None:
parsed = parse.urlsplit(self.url)
if parsed.scheme != "wss":
raise ValueError(
f"Only wss:// URLs are supported: {self.url!r}"
)
host = parsed.hostname
if not host:
raise ValueError(f"Invalid WebSocket URL: {self.url!r}")
port = parsed.port or 443
path = parsed.path or "/"
if parsed.query:
path += "?" + parsed.query
self.socket = ssl.create_default_context().wrap_socket(
socket.create_connection(
(host, port),
timeout=self.timeout,
),
server_hostname=host,
)
# RFC 6455 opening handshake.
key = base64.b64encode(os.urandom(16)).decode("ascii")
request = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {host}:{port}\r\n"
f"Upgrade: websocket\r\n"
f"Connection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
f"Sec-WebSocket-Version: 13\r\n"
f"\r\n"
).encode("ascii")
self.socket.sendall(request)
status_line, headers = self._read_http_response()
try:
version, status, reason = status_line.split(" ", 2)
except ValueError as e:
raise ConnectionError(
f"Invalid WebSocket HTTP response: {status_line!r}"
) from e
if version != "HTTP/1.1":
raise ConnectionError(
f"Unexpected WebSocket HTTP version: {version!r}"
)
if status != "101":
raise ConnectionError(
f"WebSocket handshake failed: {status} {reason}"
)
if headers.get("upgrade", "").lower() != "websocket":
raise ConnectionError(
"WebSocket handshake missing Upgrade: websocket"
)
connection_tokens = {
token.strip().lower()
for token in headers.get("connection", "").split(",")
}
if "upgrade" not in connection_tokens:
raise ConnectionError(
"WebSocket handshake missing Connection: Upgrade"
)
accept = headers.get("sec-websocket-accept")
if accept is None:
raise ConnectionError(
"WebSocket handshake missing Sec-WebSocket-Accept"
)
expected_accept = base64.b64encode(
hashlib.sha1((key + self.MAGIC).encode("ascii")).digest()
).decode("ascii")
if accept.strip() != expected_accept:
raise ConnectionError(
"Invalid WebSocket Sec-WebSocket-Accept"
)
if "sec-websocket-extensions" in headers:
raise ConnectionError(
"WebSocket extensions are not supported"
)
self.socket.settimeout(1.0)
#----------------------------------------------------------------------
def recv_message(self) -> str | bytes | None:
"""
Receive the next complete WebSocket message.
Returns:
str for text messages
bytes for binary messages
None for a clean WebSocket close
"""
while True:
fin, opcode, payload = self._recv_frame()
# Continuation frame.
if opcode == 0x0:
if self._fragment_opcode is None:
raise ConnectionError(
"Unexpected WebSocket continuation frame"
)
self._fragment_buffer.extend(payload)
if not fin:
continue
message_opcode = self._fragment_opcode
data = bytes(self._fragment_buffer)
self._fragment_buffer.clear()
self._fragment_opcode = None
if message_opcode == 0x1:
return data.decode("utf-8")
if message_opcode == 0x2:
return data
raise ConnectionError(
f"Invalid fragmented opcode: {message_opcode}"
)
# Text or binary data frame.
if opcode in (0x1, 0x2):
if self._fragment_opcode is not None:
raise ConnectionError(
"New WebSocket data frame received "
"during fragmented message"
)
if fin:
if opcode == 0x1:
return payload.decode("utf-8")
return payload
self._fragment_opcode = opcode
self._fragment_buffer.clear()
self._fragment_buffer.extend(payload)
continue
# Close.
if opcode == 0x8:
if len(payload) == 1:
raise ConnectionError(
"WebSocket close frame has invalid payload length"
)
self._send_close(payload)
if len(payload) >= 2:
close_code = struct.unpack("!H", payload[:2])[0]
raise ConnectionError(
f"WebSocket closed by server (code {close_code})"
)
raise ConnectionError("WebSocket closed by server")
# Ping.
if opcode == 0x9:
self._send_frame(0xA, payload)
continue
# Pong.
if opcode == 0xA:
continue
raise ConnectionError(
f"Unsupported WebSocket opcode: {opcode}"
)
#----------------------------------------------------------------------
def close(self) -> None:
sock = self.socket
if sock is None:
return
try:
self._send_close(struct.pack("!H", 1000))
except (OSError, ValueError):
pass
finally:
self.socket = None
try:
sock.close()
except OSError:
pass
#----------------------------------------------------------------------
def _read_http_response(self) -> tuple[str, dict[str, str]]:
data = bytearray()
while b"\r\n\r\n" not in data:
try:
chunk = self._recv_socket(4096)
except socket.timeout:
continue
if not chunk:
raise ConnectionError(
"EOF during WebSocket handshake"
)
data.extend(chunk)
if len(data) > 64 * 1024:
raise ConnectionError(
"WebSocket handshake response exceeds 64 KiB"
)
header_bytes, remainder = data.split(b"\r\n\r\n", 1)
# Preserve anything that happened to arrive after the HTTP headers.
self._recv_buffer.extend(remainder)
lines = header_bytes.decode("iso-8859-1").split("\r\n")
if not lines or not lines[0]:
raise ConnectionError(
"Empty WebSocket handshake response"
)
headers: dict[str, str] = {}
for line in lines[1:]:
if not line:
continue
if ":" not in line:
raise ConnectionError(
f"Malformed WebSocket HTTP header: {line!r}"
)
name, value = line.split(":", 1)
headers[name.strip().lower()] = value.strip()
return lines[0], headers
#----------------------------------------------------------------------
def _recv_frame(self) -> tuple[bool, int, bytes]:
first_two = self._recv_exact(2)
first = first_two[0]
second = first_two[1]
fin = bool(first & 0x80)
if first & 0x70:
raise ConnectionError(
"WebSocket frame uses unsupported RSV bits"
)
opcode = first & 0x0F
masked = bool(second & 0x80)
length = second & 0x7F
if masked:
raise ConnectionError(
"Server sent a masked WebSocket frame"
)
if length == 126:
length = struct.unpack("!H", self._recv_exact(2))[0]
elif length == 127:
length = struct.unpack("!Q", self._recv_exact(8))[0]
if length & (1 << 63):
raise ConnectionError(
"Invalid WebSocket 64-bit frame length"
)
# Control frames must be final and <= 125 bytes.
if opcode >= 0x8:
if not fin:
raise ConnectionError(
"Fragmented WebSocket control frame"
)
if length > 125:
raise ConnectionError(
"WebSocket control frame exceeds "
"125-byte limit"
)
# Continuation frames require an active fragmented message.
if opcode == 0x0 and self._fragment_opcode is None:
raise ConnectionError(
"Unexpected WebSocket continuation frame"
)
# Reject undefined control opcodes.
if opcode >= 0x8 and opcode not in (
0x8, # Close
0x9, # Ping
0xA, # Pong
):
raise ConnectionError(
f"Unknown WebSocket control opcode: {opcode}"
)
payload = self._recv_exact(length)
return fin, opcode, payload
#----------------------------------------------------------------------
def _recv_exact(self, size: int) -> bytes:
while len(self._recv_buffer) < size:
chunk = self._recv_socket(
max(4096, size - len(self._recv_buffer))
)
if not chunk:
raise ConnectionError("WebSocket EOF")
self._recv_buffer.extend(chunk)
result = bytes(self._recv_buffer[:size])
del self._recv_buffer[:size]
return result
#----------------------------------------------------------------------
def _recv_socket(self, size: int) -> bytes:
if self.socket is None:
raise ConnectionError("WebSocket is not connected")
return self.socket.recv(size)
#----------------------------------------------------------------------
def _send_close(self, payload: bytes = b"") -> None:
if len(payload) == 1:
raise ValueError(
"WebSocket close payload cannot have length 1"
)
if len(payload) > 125:
raise ValueError(
"WebSocket close payload exceeds "
"125-byte control-frame limit"
)
try:
self._send_frame(0x8, payload)
except OSError:
pass # The peer may already have closed the TCP connection.
#----------------------------------------------------------------------
def _send_frame(self, opcode: int, payload: bytes = b"") -> None:
if self.socket is None:
raise ConnectionError("WebSocket is not connected")
if opcode >= 0x8 and len(payload) > 125:
raise ValueError(
"WebSocket control frame payload "
"cannot exceed 125 bytes"
)
# RFC 6455 requires client-to-server frames to be masked.
mask = os.urandom(4)
length = len(payload)
if length < 126:
header = struct.pack("!BB", 0x80|opcode, 0x80|length)
elif length <= 0xFFFF:
header = struct.pack("!BBH", 0x80|opcode, 0x80|126, length)
else:
header = struct.pack("!BBQ", 0x80|opcode, 0x80|127, length)
masked_payload = bytes(
value ^ mask[index % 4]
for index, value in enumerate(payload)
)
self.socket.sendall(header + mask + masked_payload)
# =========================================================================
class TwitchEventPubClient:
"""
Twitch's EventSub WebSocket is a text-data/server-to-client connection.
The client only needs to:
- receive text/binary/continuation frames
- respond to Ping with Pong
- send the WebSocket Close frame
"""
# BRB Timer for Chat by beporter@users.sourceforge.net
# https://dev.twitch.tv/console/apps/ja5swzyzsr1euwm0e53h1sxqhk553l
APP_CLIENT_ID = "ja5swzyzsr1euwm0e53h1sxqhk553l"
KICKOFF_URL: str = 'https://beporter.github.io/brb-timer/start.html'
ID_URL: str = 'https://id.twitch.tv'
API_URL: str = 'https://api.twitch.tv'
EVENTSUB_URL: str = 'wss://eventsub.wss.twitch.tv/ws'
# https://dev.twitch.tv/docs/api/reference/#send-chat-message
OAUTH_SCOPES: list[str] = [
'user:read:chat',
'user:write:chat',
'user:bot',
]
RECONNECT_DELAY: int = 5
CONNECT_TIMEOUT: int = 10
HTTP_TIMEOUT: int = 10
#----------------------------------------------------------------------
def __init__(
self,
oauth: str,
callback: ChatMsgCallback,
):
self.oauth: str = oauth.removeprefix("oauth:")
self.callback: Callable = callback
self.socket: socket.socket = None
self.send_lock: threading.Lock = threading.Lock()
self.running: bool = False
self.thread: threading.Thread = None
self.stop_event: threading.Event = threading.Event()
self.client_id: str = self.APP_CLIENT_ID
self.expires_at: int = 0
self.username: str = ''
self.bot_user_id: int = None # ID of bot connecting to channel.
self.channel_user_id: int = None # ID of channel's owner.
self.keepalive_timeout: int = 10
self.last_sent: str = ''
#----------------------------------------------------------------------
def start(self) -> None:
if self.running:
return
self.running = True
self.stop_event.clear()
self.thread = threading.Thread(
target=self._receive_loop_thread,
daemon=True,
name=f"{SCRIPT_NAME}-TwitchEventSub",
)
self.thread.start()
#----------------------------------------------------------------------
def close(self) -> None:
"""
Permanently close the client.
The receiver thread owns the WebSocket and is responsible for
closing it.
"""
self.stop()
if self.thread is not None and self.thread is not threading.current_thread():
self.thread.join(timeout=2)
if self.thread.is_alive():
OBS.error(f"Failed joining Twitch EventSub thread.")
raise
self.thread = None
OBS.info("Twitch EventSub client shut down.")
#----------------------------------------------------------------------
def stop(self) -> None:
self.running = False
self.stop_event.set()
#----------------------------------------------------------------------
def send_chat(self, message: str) -> None:
"""
Send a chat message through Twitch Helix.
This is the EventSub/API equivalent of IRC PRIVMSG.
Ref: https://dev.twitch.tv/docs/api/reference/#send-chat-message
"""
with self.send_lock:
if not self.client_id or not self.bot_user_id:
raise ConnectionError(
"Twitch client is not connected"
)
if not self.channel_user_id:
raise ConnectionError(
"Twitch channel identity is unavailable"
)
resp = self._api_request(
"helix/chat/messages",
body={
"broadcaster_id": self.channel_user_id, # Broadcaster's channel
"sender_id": self.bot_user_id, # Who you're posting as
"message": message,
},
)
if not resp:
raise ConnectionError(
"Twitch Send Chat Message failed"
)
data = resp.get("data", [])[0]
if not data:
raise ConnectionError(
f"Twitch returned no chat result."
)
if not data.get("is_sent"):
raise ConnectionError(
"Twitch rejected chat message: "
f"{data.get('drop_reason')!r}"
)
self.last_sent = message
#----------------------------------------------------------------------
def _receive_loop_thread(self) -> None:
while self.running:
try:
self._connect()
self._read_loop()
except ConnectionError as e:
OBS.error(f"Connection error: {e!r}")
pass
finally:
self._close_socket()
if self.running: # Pause if we're looping.
self._wait_for_reconnect()
#----------------------------------------------------------------------
def _connect(self) -> None:
"""
Create a fresh EventSub WebSocket session.
"""
if not self._initialize_identity():
self.running = False
return
self.socket = _WebSocket(self.EVENTSUB_URL, timeout=self.CONNECT_TIMEOUT)
self.socket.connect()
raw = self.socket.recv_message()
if raw is None:
raise ConnectionError("EventSub closed during welcome")
if not isinstance(raw, str):
raise ConnectionError("EventSub welcome was not a text frame")
try:
welcome = json.loads(raw)
except json.JSONDecodeError as e:
raise ConnectionError(f"Invalid EventSub welcome: {e}")
metadata = welcome.get("metadata", {})
if metadata.get("message_type") != "session_welcome":
raise ConnectionError(
"Expected EventSub session_welcome, got "
f"{metadata.get('message_type')!r}"
)
session = (welcome.get("payload", {}).get("session", {}))
session_id = session.get("id")
if not session_id:
raise ConnectionError(
"EventSub welcome did not contain a session ID"
)
self.keepalive_timeout = int(
session.get("keepalive_timeout_seconds", 10)
)
self._create_chat_subscription(session_id)
OBS.info(
"Twitch EventSub connected "
f"(session={session_id!r})."
)
#----------------------------------------------------------------------
def _initialize_identity(self) -> None:
"""
Check the passed oauth token to determine if it's still valid,
and who it belongs to.
Ref: https://dev.twitch.tv/docs/authentication/validate-tokens#how-to-validate-a-token
"""
resp = self._api_request('oauth2/validate')
if not resp:
OBS.error("oauth2/validate failed.")
return False
if not resp['login']:
OBS.error("OAuth token is not attached to a user.")
return False
if not set(self.OAUTH_SCOPES).issubset(resp['scopes']):
missing_scopes = ", ".join(set(self.OAUTH_SCOPES) - set(resp['scopes']))
OBS.error(
"OAuth token is lacking necessary scopes: "
f"{missing_scopes!s}"
)
return False
self.user = resp.get('login', '')
self.client_id = resp.get('client_id', self.APP_CLIENT_ID)
self.expires_at = int(time.time()) + int(resp.get('expires_in', 0)) # int seconds
self.username = resp.get('login', '')
self.channel_user_id = resp.get('user_id', '') # Channel is always the streamer's id...
self.bot_user_id = self.channel_user_id # ...posting as themselves.
if (
not self.client_id
or not self.bot_user_id
or not self.channel_user_id
):
OBS.error("Twitch OAuth validation did not return client_id/user_id")
return False
return True
#----------------------------------------------------------------------
def _create_chat_subscription(
self,
session_id: str,
) -> None:
"""
Subscribe the EventSub WebSocket session to chat messages.
Twitch requires the bot's user ID in the user_id condition.
"""
body = {
"type": "channel.chat.message",
"version": "1",
"condition": {
"broadcaster_user_id": self.channel_user_id, # Broadcaster's channel
"user_id": self.bot_user_id, # Who you're listening as
},
"transport": {
"method": "websocket",
"session_id": session_id,
},
}
resp = self._api_request('helix/eventsub/subscriptions', body=body)
if not resp:
raise ConnectionError(
"Failed to create Twitch EventSub subscription."
)
#----------------------------------------------------------------------
def _read_loop(self) -> None:
if self.socket is None:
raise ConnectionError("EventSub WebSocket is not connected")
while self.running:
try:
raw = self.socket.recv_message()
except socket.timeout:
# The 1-second socket timeout exists solely to make stop()
# responsive. It is not a connection failure.
if not self.running:
return
continue
if not self.running:
return # Ends thread excution.
if not isinstance(raw, str):
continue
try:
message = json.loads(raw)
except json.JSONDecodeError as e:
OBS.debug(f"Ignoring invalid EventSub JSON: {e!r}")
continue
message_type = message.get("metadata", {}).get("message_type")
if message_type == "notification":
self._handle_notification(message)
elif message_type == "session_keepalive":
continue
elif message_type == "session_reconnect":
self._handle_reconnect(message)
return
elif message_type == "revocation":
self._handle_revocation(message)
return
#----------------------------------------------------------------------
def _handle_notification(self, message: dict) -> None:
payload = message.get('payload', {})
subscription = payload.get('subscription', {})
if subscription.get('type') != 'channel.chat.message':
return
chat_message = self._parse_eventsub_message(payload.get('event', {}))
if chat_message is not None:
self.callback(chat_message)
#----------------------------------------------------------------------
def _parse_eventsub_message(self, event: dict) -> ChatMessage | None:
username = event.get('chatter_user_login', '')
text = event.get('message', {}).get('text')
badges = event.get('badges', [])
if not username or text is None:
return None
return ChatMessage(
username,
event.get('chatter_user_name', username),
text,
any(
badge.get('set_id') == 'moderator'
and badge.get('id') == '1'
for badge in badges
),
any(
badge.get('set_id') == 'broadcaster'
and badge.get('id') == '1'
for badge in badges
),
)
#----------------------------------------------------------------------
def _handle_reconnect(self, message: dict) -> None:
"""
Twitch specifically requires us to keep the old connection alive
until the new connection has delivered its welcome message.
"""
session = message.get('payload', {}).get('session', {})
reconnect_url = session.get('reconnect_url')
if not reconnect_url:
raise ConnectionError(
"EventSub reconnect message has no reconnect URL"
)
OBS.info("Twitch requested EventSub reconnect.")
old_ws = self.socket
new_ws = _WebSocket(reconnect_url, timeout=self.CONNECT_TIMEOUT)
try:
new_ws.connect()
raw = new_ws.recv_message()
if not isinstance(raw, str):
raise ConnectionError(
"EventSub reconnect did not return "
"a text welcome message"
)
welcome = json.loads(raw)
message_type = welcome.get('metadata', {}).get('message_type')
if (message_type != 'session_welcome'):
raise ConnectionError(
"Invalid EventSub reconnect welcome"
)
new_session = welcome.get('payload', {}).get('session', {})
self.keepalive_timeout = int(
new_session.get(
"keepalive_timeout_seconds",
self.keepalive_timeout,
)
)
# Only switch after the new socket has successfully completed
# the WebSocket handshake AND received its EventSub welcome.
self.socket = new_ws
# Now that the new connection has inherited the subscriptions,
# the old socket can be closed.
if old_ws is not None: