-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathchallenger.py
More file actions
52 lines (38 loc) · 2.04 KB
/
challenger.py
File metadata and controls
52 lines (38 loc) · 2.04 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
import asyncio
from api import API
from botli_dataclasses import ApiChallengeResponse, ChallengeRequest, ChallengeResponse
class Challenger:
def __init__(self, api: API) -> None:
self.api = api
self.tasks: set[asyncio.Task[None]] = set()
async def create(self, challenge_request: ChallengeRequest) -> ChallengeResponse:
challenge_id = None
challenge_queue: asyncio.Queue[ApiChallengeResponse] = asyncio.Queue()
task = asyncio.create_task(self.api.create_challenge(challenge_request, challenge_queue))
self.tasks.add(task)
task.add_done_callback(self.tasks.discard)
while response := await challenge_queue.get():
if response.challenge_id:
challenge_id = response.challenge_id
if response.was_accepted:
return ChallengeResponse(challenge_id=challenge_id, success=True)
if response.was_declined:
return ChallengeResponse()
if response.has_reached_rate_limit:
print(f"Challenge against {challenge_request.opponent_username} failed due to Lichess rate limit.")
return ChallengeResponse(has_reached_rate_limit=True, wait_seconds=response.wait_seconds)
if response.invalid_initial:
print("Challenge failed due to invalid initial time.")
return ChallengeResponse(is_misconfigured=True)
if response.invalid_increment:
print("Challenge failed due to invalid increment time.")
return ChallengeResponse(is_misconfigured=True)
if response.has_timed_out:
print(f"Challenge against {challenge_request.opponent_username} has timed out.")
if challenge_id is not None:
await self.api.cancel_challenge(challenge_id)
return ChallengeResponse()
if response.error:
print(response.error)
return ChallengeResponse(wait_seconds=response.wait_seconds)
return ChallengeResponse()