Skip to content

Commit

Permalink
Replace discontinued deta db with preliminary JSON implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonyte committed Nov 15, 2024
1 parent dba0396 commit aa0f40e
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 23 deletions.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ description = "A Discord bot to play virtual Russian Roulette with your friends.
readme = "readme.md"
requires-python = ">=3.11"
dependencies = [
"deta~=1.1.0",
"discord-py~=2.4.0",
"pydantic-settings~=2.6.1",
]
Expand Down
27 changes: 20 additions & 7 deletions src/bot/modules/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
from __future__ import annotations

import asyncio
import json
import random
from pathlib import Path
from typing import TYPE_CHECKING

from deta import Base
from discord import (
ButtonStyle,
CategoryChannel,
Expand Down Expand Up @@ -121,23 +122,35 @@ def remove_player(self, player: User) -> None:


class GameDB:
def __init__(self, bot: Bot) -> None:
def __init__(self, bot: RussianRoulette, /, *, file_path: Path = Path("data/games.json")) -> None:
self.bot = bot
self._db = Base("games_preview" if config.preview else "games")
self._file_path = file_path

def get(self, id: int) -> GameInstance | None:
data = self._db.get(str(id))
with self._file_path.open("r") as file:
games = dict(json.load(file))
data = games.get(str(id), None)
if data is not None:
return GameInstance.from_dict(data, self.bot) # type: ignore
return GameInstance.from_dict(data, self.bot)
return data

def put(self, game: GameInstance) -> str:
with self._file_path.open("r") as file:
games = dict(json.load(file))
key = str(game.channel.id)
self._db.insert(game.to_dict(), key=key, expire_in=15 * 60)
games[key] = game.to_dict()
with self._file_path.open("w") as file:
json.dump(games, file)
return key

def delete(self, id: int) -> None:
self._db.delete(str(id))
with self._file_path.open("r") as file:
games = dict(json.load(file))
key = str(id)
if key in games:
del games[key]
with self._file_path.open("w") as file:
json.dump(games, file)


class View(ui.View):
Expand Down
113 changes: 98 additions & 15 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit aa0f40e

Please sign in to comment.