Skip to content

Commit 9b4edf4

Browse files
committed
run black
1 parent e9ac1b4 commit 9b4edf4

File tree

3 files changed

+71
-33
lines changed

3 files changed

+71
-33
lines changed

twitchio/ext/eventsub/http.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ def __init__(self, client: Union[EventSubClient, EventSubWSClient], token: Optio
1818
self._http = client.client._http
1919
self._token = token
2020

21-
async def create_webhook_subscription(self, event_type: Tuple[str, int, Type[EventData]], condition: Dict[str, str]):
21+
async def create_webhook_subscription(
22+
self, event_type: Tuple[str, int, Type[EventData]], condition: Dict[str, str]
23+
):
2224
payload = {
2325
"type": event_type[0],
2426
"version": str(event_type[1]),
@@ -28,7 +30,9 @@ async def create_webhook_subscription(self, event_type: Tuple[str, int, Type[Eve
2830
route = Route("POST", "eventsub/subscriptions", body=payload, token=self._token)
2931
return await self._http.request(route, paginate=False, force_app_token=True)
3032

31-
async def create_websocket_subscription(self, event_type: Tuple[str, int, Type[EventData]], condition: Dict[str, str], session_id: str, token: str):
33+
async def create_websocket_subscription(
34+
self, event_type: Tuple[str, int, Type[EventData]], condition: Dict[str, str], session_id: str, token: str
35+
):
3236
payload = {
3337
"type": event_type[0],
3438
"version": str(event_type[1]),

twitchio/ext/eventsub/models.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __init__(self, data: dict):
5454
if self.transport_method is TransportType.webhook:
5555
self.transport.callback: str = data["transport"]["callback"] # type: ignore
5656
else:
57-
self.transport.callback: str = "" # type: ignore # compatibility
57+
self.transport.callback: str = "" # type: ignore # compatibility
5858
self.transport.session_id: str = data["transport"]["session_id"] # type: ignore
5959

6060

@@ -114,12 +114,15 @@ class WebsocketHeaders:
114114
timestamp: :class:`datetime.datetime`
115115
The timestamp the message was sent at
116116
"""
117+
117118
def __init__(self, frame: dict):
118119
meta = frame["metadata"]
119120
self.message_id: str = meta["message_id"]
120121
self.timestamp = _parse_datetime(meta["message_timestamp"])
121-
self.message_type: Literal["notification", "revocation", "reconnect", "session_keepalive"] = meta["message_type"]
122-
self.message_retry: int = 0 # don't make breaking changes with the Header class
122+
self.message_type: Literal["notification", "revocation", "reconnect", "session_keepalive"] = meta[
123+
"message_type"
124+
]
125+
self.message_retry: int = 0 # don't make breaking changes with the Header class
123126
self.signature: str = ""
124127
self.subscription_type: Optional[str]
125128
self.subscription_version: Optional[str]
@@ -153,7 +156,9 @@ def __init__(self, client: EventSubClient, _data: str, request: web.Request):
153156
def __init__(self, client: EventSubWSClient, _data: dict, request: None):
154157
...
155158

156-
def __init__(self, client: Union[EventSubClient, EventSubWSClient], _data: Union[str, dict], request: Optional[web.Request]):
159+
def __init__(
160+
self, client: Union[EventSubClient, EventSubWSClient], _data: Union[str, dict], request: Optional[web.Request]
161+
):
157162
self._client = client
158163
self._raw_data = _data
159164

@@ -178,15 +183,14 @@ def __init__(self, client: Union[EventSubClient, EventSubWSClient], _data: Union
178183
self.subscription = None
179184
self.setup(data["payload"])
180185

181-
182186
def setup(self, data: dict):
183187
pass
184188

185189
def verify(self):
186190
"""
187191
Only used in webhook transport types. Verifies the message is valid
188192
"""
189-
hmac_message = (self.headers.message_id + self.headers._raw_timestamp + self._raw_data).encode("utf-8") # type: ignore
193+
hmac_message = (self.headers.message_id + self.headers._raw_timestamp + self._raw_data).encode("utf-8") # type: ignore
190194
secret = self._client.secret.encode("utf-8")
191195
digest = hmac.new(secret, msg=hmac_message, digestmod=hashlib.sha256).hexdigest()
192196

@@ -220,7 +224,7 @@ def setup(self, data: dict):
220224
self.challenge: str = data["challenge"]
221225

222226
def verify(self):
223-
hmac_message = (self.headers.message_id + self.headers._raw_timestamp + self._raw_data).encode("utf-8") # type: ignore
227+
hmac_message = (self.headers.message_id + self.headers._raw_timestamp + self._raw_data).encode("utf-8") # type: ignore
224228
secret = self._client.secret.encode("utf-8")
225229
digest = hmac.new(secret, msg=hmac_message, digestmod=hashlib.sha256).hexdigest()
226230

@@ -261,6 +265,7 @@ class KeepAliveEvent(BaseEvent):
261265
These are only dispatched when using :class:`~twitchio.ext.eventsub.EventSubWSClient
262266
263267
"""
268+
264269
pass
265270

266271

@@ -1651,6 +1656,7 @@ class _SubscriptionTypes(metaclass=_SubTypesMeta):
16511656

16521657
SubscriptionTypes = _SubscriptionTypes()
16531658

1659+
16541660
class TransportType(Enum):
16551661
webhook = "webhook"
16561662
websocket = "websocket"

twitchio/ext/eventsub/websocket.py

Lines changed: 52 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,25 @@
1818
"notification": models.NotificationEvent,
1919
"revocation": models.RevokationEvent,
2020
"reconnect": models.ReconnectEvent,
21-
"session_keepalive": models.KeepAliveEvent
21+
"session_keepalive": models.KeepAliveEvent,
2222
}
2323
_messages = Union[models.NotificationEvent, models.RevokationEvent, models.ReconnectEvent, models.KeepAliveEvent]
2424

2525

2626
class _Subscription:
2727
__slots__ = "event", "condition", "token", "subscription_id", "cost"
28+
2829
def __init__(self, event_type: Tuple[str, int, Type[models.EventData]], condition: Dict[str, str], token: str):
2930
self.event = event_type
3031
self.condition = condition
3132
self.token = token
3233
self.subscription_id: Optional[str] = None
3334
self.cost: Optional[int] = None
3435

36+
3537
_T = TypeVar("_T")
3638

39+
3740
class _WakeupList(list, Generic[_T]):
3841
def __init__(self, *args):
3942
super().__init__(*args)
@@ -45,15 +48,15 @@ def _wakeup_append(self, obj: _T) -> None:
4548
loop = asyncio.get_running_loop()
4649
for cb in self._append_waiters:
4750
loop.create_task(cb(obj))
48-
except: # don't wake the waiters if theres no loop
51+
except: # don't wake the waiters if theres no loop
4952
pass
5053

5154
def _wakeup_pop(self, obj: _T) -> None:
5255
try:
5356
loop = asyncio.get_running_loop()
5457
for cb in self._pop_waiters:
5558
loop.create_task(cb(obj))
56-
except: # don't wake the waiters
59+
except: # don't wake the waiters
5760
pass
5861

5962
def append(self, obj: _T) -> None:
@@ -93,7 +96,7 @@ def __init__(self, client: Client, http: http.EventSubHTTP):
9396
self._timeout: Optional[int] = None
9497
self._session_id: Optional[str] = None
9598

96-
self.remaining_slots: int = 100 # default to 100
99+
self.remaining_slots: int = 100 # default to 100
97100

98101
@property
99102
def session_id(self) -> Optional[str]:
@@ -107,7 +110,9 @@ async def _subscribe(self, obj: _Subscription) -> dict:
107110
resp = await self._http.create_websocket_subscription(obj.event, obj.condition, self._session_id, obj.token)
108111
data = resp["data"][0]
109112
cost = data["cost"]
110-
self.remaining_slots = resp["total_cost"] - resp["max_total_cost"] # FIXME: twitch is pretty vague about these, check back on their values later
113+
self.remaining_slots = (
114+
resp["total_cost"] - resp["max_total_cost"]
115+
) # FIXME: twitch is pretty vague about these, check back on their values later
111116
obj.cost = cost
112117

113118
return data
@@ -122,7 +127,7 @@ async def _wakeup_and_connect(self, obj: _Subscription):
122127

123128
async def connect(self, reconnect_url: Optional[str] = None):
124129
if not self._subscription_pool:
125-
return # TODO: should this raise?
130+
return # TODO: should this raise?
126131

127132
async with aiohttp.ClientSession() as session:
128133
sock = self._sock = await session.ws_connect(reconnect_url or self.URL)
@@ -137,18 +142,20 @@ async def connect(self, reconnect_url: Optional[str] = None):
137142

138143
self._pump_task = self.client.loop.create_task(self.pump())
139144

140-
if reconnect_url: # don't resubscribe to events
145+
if reconnect_url: # don't resubscribe to events
141146
return
142147

143148
for sub in self._subscription_pool:
144-
await self._subscribe(sub) # TODO: how do I return this to the end user (do I bother?)
149+
await self._subscribe(sub) # TODO: how do I return this to the end user (do I bother?)
145150

146151
async def pump(self) -> None:
147152
while self.is_connected:
148153
try:
149-
msg = await cast(aiohttp.ClientWebSocketResponse, self._sock).receive_str(timeout=self._timeout+1) # extra jitter on the timeout in case of network lag
154+
msg = await cast(aiohttp.ClientWebSocketResponse, self._sock).receive_str(
155+
timeout=self._timeout + 1
156+
) # extra jitter on the timeout in case of network lag
150157
if not msg:
151-
continue # TODO: should this raise?
158+
continue # TODO: should this raise?
152159

153160
logger.debug("Received websocket payload: %s", msg)
154161
frame: _messages = self.parse_frame(_loads(msg))
@@ -171,12 +178,16 @@ async def pump(self) -> None:
171178
sock = self._sock
172179
self._sock = None
173180
await self.connect(frame.reconnect_url)
174-
await cast(aiohttp.ClientWebSocketResponse, sock).close(code=aiohttp.WSCloseCode.GOING_AWAY, message=b"reconnecting")
181+
await cast(aiohttp.ClientWebSocketResponse, sock).close(
182+
code=aiohttp.WSCloseCode.GOING_AWAY, message=b"reconnecting"
183+
)
175184
return
176185

177186
except asyncio.TimeoutError:
178187
logger.warning(f"Websocket timed out (timeout: {self._timeout}), reconnecting")
179-
await cast(aiohttp.ClientWebSocketResponse, self._sock).close(code=aiohttp.WSCloseCode.ABNORMAL_CLOSURE, message=b"timeout surpassed")
188+
await cast(aiohttp.ClientWebSocketResponse, self._sock).close(
189+
code=aiohttp.WSCloseCode.ABNORMAL_CLOSURE, message=b"timeout surpassed"
190+
)
180191
await self.connect()
181192
return
182193

@@ -219,7 +230,10 @@ def subscribe_user_updated(self, user: Union[PartialUser, str, int], token: str)
219230
self._assign_subscription(sub)
220231

221232
def subscribe_channel_raid(
222-
self, token: str, from_broadcaster: Union[PartialUser, str, int] = None, to_broadcaster: Union[PartialUser, str, int] = None
233+
self,
234+
token: str,
235+
from_broadcaster: Union[PartialUser, str, int] = None,
236+
to_broadcaster: Union[PartialUser, str, int] = None,
223237
):
224238
if (not from_broadcaster and not to_broadcaster) or (from_broadcaster and to_broadcaster):
225239
raise ValueError("Expected 1 of from_broadcaster or to_broadcaster")
@@ -239,7 +253,11 @@ def subscribe_channel_raid(
239253
self._assign_subscription(sub)
240254

241255
def _subscribe_channel_points_reward(
242-
self, event: Tuple[str, int, Type[models._DataType]], broadcaster: Union[PartialUser, str, int], token: str, reward_id: str = None
256+
self,
257+
event: Tuple[str, int, Type[models._DataType]],
258+
broadcaster: Union[PartialUser, str, int],
259+
token: str,
260+
reward_id: str = None,
243261
):
244262
if isinstance(broadcaster, PartialUser):
245263
broadcaster = broadcaster.id
@@ -261,13 +279,13 @@ def _subscribe_with_broadcaster(
261279
broadcaster = str(broadcaster)
262280
sub = _Subscription(event, {"broadcaster_user_id": broadcaster}, token)
263281
self._assign_subscription(sub)
264-
282+
265283
def _subscribe_with_broadcaster_moderator(
266284
self,
267285
event: Tuple[str, int, Type[models._DataType]],
268286
broadcaster: Union[PartialUser, str, int],
269287
moderator: Union[PartialUser, str, int],
270-
token: str
288+
token: str,
271289
):
272290
if isinstance(broadcaster, PartialUser):
273291
broadcaster = broadcaster.id
@@ -279,7 +297,6 @@ def _subscribe_with_broadcaster_moderator(
279297
sub = _Subscription(event, {"broadcaster_user_id": broadcaster, "moderator_user_id": moderator}, token)
280298
self._assign_subscription(sub)
281299

282-
283300
def subscribe_channel_bans(self, broadcaster: Union[PartialUser, str, int], token: str):
284301
return self._subscribe_with_broadcaster(models.SubscriptionTypes.ban, broadcaster, token)
285302

@@ -310,7 +327,9 @@ def subscribe_channel_follows(self, broadcaster: Union[PartialUser, str, int], t
310327
def subscribe_channel_follows_v2(
311328
self, broadcaster: Union[PartialUser, str, int], moderator: Union[PartialUser, str, int], token: str
312329
):
313-
return self._subscribe_with_broadcaster_moderator(models.SubscriptionTypes.followV2, broadcaster, moderator, token)
330+
return self._subscribe_with_broadcaster_moderator(
331+
models.SubscriptionTypes.followV2, broadcaster, moderator, token
332+
)
314333

315334
def subscribe_channel_moderators_add(self, broadcaster: Union[PartialUser, str, int], token: str):
316335
return self._subscribe_with_broadcaster(models.SubscriptionTypes.channel_moderator_add, broadcaster, token)
@@ -342,27 +361,37 @@ def subscribe_channel_stream_start(self, broadcaster: Union[PartialUser, str, in
342361
def subscribe_channel_stream_end(self, broadcaster: Union[PartialUser, str, int], token: str):
343362
return self._subscribe_with_broadcaster(models.SubscriptionTypes.stream_end, broadcaster, token)
344363

345-
def subscribe_channel_points_reward_added(self, broadcaster: Union[PartialUser, str, int], reward_id: str, token: str):
364+
def subscribe_channel_points_reward_added(
365+
self, broadcaster: Union[PartialUser, str, int], reward_id: str, token: str
366+
):
346367
return self._subscribe_channel_points_reward(
347368
models.SubscriptionTypes.channel_reward_add, broadcaster, token, reward_id
348369
)
349370

350-
def subscribe_channel_points_reward_updated(self, broadcaster: Union[PartialUser, str, int], reward_id: str, token: str):
371+
def subscribe_channel_points_reward_updated(
372+
self, broadcaster: Union[PartialUser, str, int], reward_id: str, token: str
373+
):
351374
return self._subscribe_channel_points_reward(
352375
models.SubscriptionTypes.channel_reward_update, broadcaster, token, reward_id
353376
)
354377

355-
def subscribe_channel_points_reward_removed(self, broadcaster: Union[PartialUser, str, int], reward_id: str, token: str):
378+
def subscribe_channel_points_reward_removed(
379+
self, broadcaster: Union[PartialUser, str, int], reward_id: str, token: str
380+
):
356381
return self._subscribe_channel_points_reward(
357382
models.SubscriptionTypes.channel_reward_remove, broadcaster, token, reward_id
358383
)
359384

360-
def subscribe_channel_points_redeemed(self, broadcaster: Union[PartialUser, str, int], token: str, reward_id: str = None):
385+
def subscribe_channel_points_redeemed(
386+
self, broadcaster: Union[PartialUser, str, int], token: str, reward_id: str = None
387+
):
361388
return self._subscribe_channel_points_reward(
362389
models.SubscriptionTypes.channel_reward_redeem, broadcaster, token, reward_id
363390
)
364391

365-
def subscribe_channel_points_redeem_updated(self, broadcaster: Union[PartialUser, str, int], token: str, reward_id: str = None):
392+
def subscribe_channel_points_redeem_updated(
393+
self, broadcaster: Union[PartialUser, str, int], token: str, reward_id: str = None
394+
):
366395
return self._subscribe_channel_points_reward(
367396
models.SubscriptionTypes.channel_reward_redeem_updated, broadcaster, token, reward_id
368397
)
@@ -388,7 +417,6 @@ def subscribe_channel_prediction_lock(self, broadcaster: Union[PartialUser, str,
388417
def subscribe_channel_prediction_end(self, broadcaster: Union[PartialUser, str, int], token: str):
389418
return self._subscribe_with_broadcaster(models.SubscriptionTypes.prediction_end, broadcaster, token)
390419

391-
392420
def subscribe_channel_shield_mode_begin(
393421
self, broadcaster: Union[PartialUser, str, int], moderator: Union[PartialUser, str, int], token: str
394422
):

0 commit comments

Comments
 (0)