-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathcore.py
63 lines (51 loc) · 2.23 KB
/
core.py
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
import ssl
import aiohttp
from racetime_bot import Bot
from tenacity import (AsyncRetrying, RetryError, retry_if_exception_type,
stop_after_attempt)
import config
from alttprbot import models
RACETIME_HOST = config.RACETIME_HOST
RACETIME_SECURE = config.RACETIME_SECURE
RACETIME_PORT = config.RACETIME_PORT
class SahasrahBotRaceTimeBot(Bot):
racetime_host = RACETIME_HOST
racetime_port = RACETIME_PORT
racetime_secure = RACETIME_SECURE
def __init__(self, handler_class, *args, **kwargs):
super().__init__(*args, **kwargs)
self.handler_class = handler_class
if self.racetime_secure:
self.ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
def get_handler_kwargs(self, ws_conn, state):
return {
'conn': ws_conn,
'logger': self.logger,
'state': state,
'command_prefix': config.RACETIME_COMMAND_PREFIX,
}
def get_handler_class(self):
return self.handler_class
async def start(self):
self.http = aiohttp.ClientSession(raise_for_status=True)
self.access_token, self.reauthorize_every = await self.authorize()
self.loop.create_task(self.reauthorize())
self.loop.create_task(self.refresh_races())
unlisted_rooms = await models.RTGGUnlistedRooms.filter(category=self.category_slug)
for unlisted_room in unlisted_rooms:
try:
async for attempt in AsyncRetrying(
stop=stop_after_attempt(5),
retry=retry_if_exception_type(aiohttp.ClientResponseError)):
with attempt:
async with self.http.get(
self.http_uri(f'/{unlisted_room.room_name}/data'),
ssl=self.ssl_context,
) as resp:
race_data = await resp.json()
if race_data['status']['value'] in ['finished', 'cancelled'] or not race_data['unlisted']:
await unlisted_room.delete()
else:
await self.join_race_room(unlisted_room.room_name)
except RetryError as e:
raise e.last_attempt._exception from e