Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update get deck and endpoints for new api #10

Merged
merged 2 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions bot/exts/card.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __init__(

async def get_stats(
self: CardExt, server: Server, deck: list[Card]
) -> tuple[Image.Image, tuple[int, int, int], dict[str, int], int]:
) -> tuple[Image.Image, tuple[int, int, int], dict[str, int]]:
"""Get information and an image of a deck.

Args:
Expand All @@ -110,7 +110,6 @@ async def get_stats(
"redstone": 0,
"farm": 0,
}
cost: int = 0
hermits, items, effects = ([] for _ in range(3))
for card in deck:
if card.category == "item":
Expand All @@ -121,7 +120,6 @@ async def get_stats(
type_counts[card.hermit_type] += 1
else:
effects.append(card)
cost += card.cost

hermits.sort(key=lambda x: x.text_id)
items.sort(key=lambda x: x.text_id)
Expand All @@ -139,7 +137,7 @@ async def get_stats(
for i, card_image in enumerate(card_images):
card_image = card_image.resize((200, 200)).convert("RGBA")
im.paste(card_image, ((i % width) * 200, (i // width) * 200), card_image)
return im, (len(hermits), len(effects), len(items)), type_counts, cost
return im, (len(hermits), len(effects), len(items)), type_counts

@global_autocomplete("card_name")
async def card_autocomplete(self: CardExt, ctx: AutocompleteContext) -> None:
Expand Down Expand Up @@ -189,16 +187,16 @@ async def deck(self: CardExt, ctx: SlashContext, code: str, *, hide_hash: bool =
).add_field("Deck loading", "Please wait")
message = await ctx.send(embed=e)

im, card_type_counts, hermit_type_counts, cost = await self.get_stats(
server, [server.data_generator.universe[card["props"]["id"]] for card in deck["cards"]]
im, card_type_counts, hermit_type_counts = await self.get_stats(
server, [server.data_generator.universe[card] for card in deck["cards"]]
)
if len(deck["tags"]) == 0:
e.color = rgb_to_int(TYPE_COLORS[Counter(hermit_type_counts).most_common()[0][0]])

e.fields.clear()
e = (
e.set_image("attachment://deck.png")
.add_field("Token cost", str(cost), inline=True)
.add_field("Token cost", str(deck["cost"]), inline=True)
.add_field(
"HEI ratio",
f"{card_type_counts[0]}:{card_type_counts[1]}:{card_type_counts[2]}",
Expand Down
4 changes: 4 additions & 0 deletions bot/util/datagen.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ async def get_image(self: DataGenerator, path: str) -> Image.Image:
return self.cache[path]
async with self.http_session.get(path) as response:
self.cache[path] = Image.open(BytesIO(await response.content.read()))
if not response.ok:
return Image.new("RGBA", (0, 0))
return self.cache[path]
except Image.UnidentifiedImageError:
return Image.new("RGBA", (0, 0))
Expand All @@ -166,6 +168,8 @@ async def load_data(self: DataGenerator) -> list[Card]:
cards = []
async with self.http_session.get("cards") as response:
content = await response.content.read()
if not response.ok:
return []

iterator = loads(content.decode())
if has_progression:
Expand Down
12 changes: 9 additions & 3 deletions bot/util/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,17 +151,19 @@ async def get_deck(self: Server, code: str) -> dict | None:
try:
async with self.http_session.get(f"deck/{code}") as response:
result = loads((await response.content.read()).decode())
if not response.ok:
return None
except (TimeoutError, JSONDecodeError):
return None
if result.status != 200:
return None
return result

async def create_game(self: Server) -> QueueGame | None:
"""Create a server game."""
try:
async with self.http_session.get("games/create") as response:
data: dict[str, str | int] = loads((await response.content.read()).decode())
if not response.ok:
return None
return QueueGame(data)
except (
ConnectionError,
Expand All @@ -176,7 +178,7 @@ async def cancel_game(self: Server, game: QueueGame) -> bool:
async with self.http_session.delete(
"games/cancel", json={"code": game.secret}
) as response:
data: dict[str, str | None] = loads((await response.content.read()).decode())
loads((await response.content.read()).decode())
return response.status == 200
except (
ConnectionError,
Expand All @@ -193,6 +195,8 @@ async def get_game_count(self: Server) -> int:

async with self.http_session.get("games/count") as response:
data: dict[str, int] = loads((await response.content.read()).decode())
if not response.ok:
return 0
self.last_game_count = data["games"]
self.last_game_count_time = round(time())
return self.last_game_count
Expand All @@ -211,6 +215,8 @@ async def get_queue_length(self: Server) -> int:

async with self.http_session.get("games/queue/length") as response:
data: dict[str, int] = loads((await response.content.read()).decode())
if not response.ok:
return 0
self.last_queue_length = data["queueLength"]
self.last_queue_length_time = round(time())
return self.last_queue_length
Expand Down