Skip to content

Commit

Permalink
Merge pull request #2 from noneplugin/feat/orm
Browse files Browse the repository at this point in the history
  • Loading branch information
MeetWq committed Oct 20, 2023
2 parents 11f2bd2 + 1aa37aa commit 613ea0e
Show file tree
Hide file tree
Showing 8 changed files with 769 additions and 676 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
*__pycache__/
dist/
.vscode/
.env
data.db
36 changes: 11 additions & 25 deletions nonebot_plugin_chess/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,21 @@
EventToMe,
ShellCommandArgv,
)
from nonebot.plugin import PluginMetadata
from nonebot.plugin import PluginMetadata, inherit_supported_adapters
from nonebot.rule import ArgumentParser, Rule
from nonebot.typing import T_State

require("nonebot_plugin_saa")
require("nonebot_plugin_session")
require("nonebot_plugin_userinfo")
require("nonebot_plugin_datastore")
require("nonebot_plugin_orm")
require("nonebot_plugin_htmlrender")

from nonebot_plugin_saa import Image, MessageFactory
from nonebot_plugin_saa import __plugin_meta__ as saa_plugin_meta
from nonebot_plugin_session import SessionIdType, SessionLevel
from nonebot_plugin_session import __plugin_meta__ as session_plugin_meta
from nonebot_plugin_session import extract_session
from nonebot_plugin_userinfo import __plugin_meta__ as userinfo_plugin_meta
from nonebot_plugin_session import SessionIdType, SessionLevel, extract_session
from nonebot_plugin_userinfo import get_user_info

assert saa_plugin_meta.supported_adapters
assert session_plugin_meta.supported_adapters
assert userinfo_plugin_meta.supported_adapters
supported_adapters = (
saa_plugin_meta.supported_adapters
& session_plugin_meta.supported_adapters
& userinfo_plugin_meta.supported_adapters
)

from . import migrations
from .config import Config
from .game import AiPlayer, Game, Player

Expand All @@ -61,12 +49,15 @@
type="application",
homepage="https://github.com/noneplugin/nonebot-plugin-chess",
config=Config,
supported_adapters=supported_adapters,
supported_adapters=inherit_supported_adapters(
"nonebot_plugin_saa", "nonebot_plugin_session", "nonebot_plugin_userinfo"
),
extra={
"unique_name": "chess",
"example": "@小Q 国际象棋人机lv5\ne2e4\n结束下棋",
"author": "meetwq <[email protected]>",
"version": "0.4.2",
"version": "0.4.3",
"orm_version_location": migrations,
},
)

Expand Down Expand Up @@ -217,17 +208,12 @@ def set_timeout(matcher: Matcher, cid: str, timeout: float = 600):
timers[cid] = timer


async def handle_chess(
bot: Bot,
matcher: Matcher,
event: Event,
argv: List[str],
):
async def handle_chess(bot: Bot, matcher: Matcher, event: Event, argv: List[str]):
async def new_player(event: Event) -> Player:
user_id = event.get_user_id()
user_name = ""
if user_info := await get_user_info(bot, event, user_id=user_id):
user_name = user_info.user_name
user_name = user_info.user_displayname or user_info.user_name
return Player(user_id, user_name)

async def send(msgs: Union[str, Iterable[Union[str, bytes]]] = "") -> NoReturn:
Expand Down
27 changes: 17 additions & 10 deletions nonebot_plugin_chess/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import chess.svg
from chess import Board, Move
from nonebot import get_driver
from nonebot_plugin_datastore import create_session
from nonebot_plugin_htmlrender import html_to_pic
from nonebot_plugin_orm import get_session
from sqlalchemy import select

from .config import Config
Expand Down Expand Up @@ -113,10 +113,11 @@ async def draw(self) -> bytes:

async def save_record(self, session_id: str):
statement = select(GameRecord).where(GameRecord.game_id == self.id)
async with create_session() as session:
record: Optional[GameRecord] = await session.scalar(statement)
async with get_session() as session:
record = await session.scalar(statement)
if not record:
record = GameRecord(game_id=self.id, session_id=session_id)

if self.player_white:
record.player_white_id = str(self.player_white.id)
record.player_white_name = self.player_white.name
Expand All @@ -135,6 +136,7 @@ async def save_record(self, session_id: str):
record.start_fen = self.board.starting_fen
record.moves = " ".join([str(move) for move in self.board.move_stack])
record.is_game_over = self.board.is_game_over()

session.add(record)
await session.commit()

Expand All @@ -156,14 +158,19 @@ async def load_player(
else:
return Player(id, name)

statement = select(GameRecord).where(
GameRecord.session_id == session_id, GameRecord.is_game_over == False
statement = (
select(GameRecord)
.where(
GameRecord.session_id == session_id,
GameRecord.is_game_over == False,
)
.order_by(GameRecord.update_time.desc())
)
async with create_session() as session:
records = (await session.scalars(statement)).all()
if not records:
return None
record = sorted(records, key=lambda x: x.update_time)[-1]
async with get_session() as session:
record = await session.scalar(statement)
if not record:
return None

game = cls()
game.id = record.game_id
game.player_white = await load_player(
Expand Down
53 changes: 53 additions & 0 deletions nonebot_plugin_chess/migrations/32c01e50814d_init_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""init_db
修订 ID: 32c01e50814d
父修订:
创建时间: 2023-10-19 15:33:59.636036
"""
from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "32c01e50814d"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = "nonebot_plugin_chess"
depends_on: str | Sequence[str] | None = None


def upgrade(name: str = "") -> None:
if name:
return
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"nonebot_plugin_chess_gamerecord",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("game_id", sa.String(length=128), nullable=False),
sa.Column("session_id", sa.String(length=128), nullable=False),
sa.Column("start_time", sa.DateTime(), nullable=False),
sa.Column("update_time", sa.DateTime(), nullable=False),
sa.Column("player_white_id", sa.String(length=64), nullable=False),
sa.Column("player_white_name", sa.Text(), nullable=False),
sa.Column("player_white_is_ai", sa.Boolean(), nullable=False),
sa.Column("player_white_level", sa.Integer(), nullable=False),
sa.Column("player_black_id", sa.String(length=64), nullable=False),
sa.Column("player_black_name", sa.Text(), nullable=False),
sa.Column("player_black_is_ai", sa.Boolean(), nullable=False),
sa.Column("player_black_level", sa.Integer(), nullable=False),
sa.Column("start_fen", sa.Text(), nullable=False),
sa.Column("moves", sa.Text(), nullable=False),
sa.Column("is_game_over", sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_nonebot_plugin_chess_gamerecord")),
)
# ### end Alembic commands ###


def downgrade(name: str = "") -> None:
if name:
return
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("nonebot_plugin_chess_gamerecord")
# ### end Alembic commands ###
46 changes: 0 additions & 46 deletions nonebot_plugin_chess/migrations/62899ffdd34f_init_db.py

This file was deleted.

6 changes: 1 addition & 5 deletions nonebot_plugin_chess/model.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
from datetime import datetime

from nonebot_plugin_datastore import get_plugin_data
from nonebot_plugin_orm import Model
from sqlalchemy import String, Text
from sqlalchemy.orm import Mapped, mapped_column

Model = get_plugin_data().Model


class GameRecord(Model):
__table_args__ = {"extend_existing": True}

id: Mapped[int] = mapped_column(primary_key=True)
game_id: Mapped[str] = mapped_column(String(128))
session_id: Mapped[str] = mapped_column(String(128))
Expand Down
Loading

0 comments on commit 613ea0e

Please sign in to comment.