mirror of
https://github.com/A-Minos/nonebot-plugin-tetris-stats.git
synced 2026-03-05 05:36:54 +08:00
Compare commits
157 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 435850819c | |||
| 6f439ad357 | |||
| b74cc1f4a0 | |||
| 1a1c2675d1 | |||
| 1f02c107f5 | |||
| 89c319a500 | |||
| 56f9a69c4d | |||
| 50431fe7cb | |||
| 71ad53a1f9 | |||
| 820393f216 | |||
| 27994cea6b | |||
|
|
eb753cb059 | ||
|
|
256d13d1df | ||
|
|
d8d56b44db | ||
|
|
57a57f0259 | ||
|
|
4f7f4a3e33 | ||
|
|
367a9a8297 | ||
|
|
009dd90609 | ||
| 8e6e0dc274 | |||
|
|
df7efc6707 | ||
|
|
d783ecd3eb | ||
|
|
13f3e34f79 | ||
| 566509dd46 | |||
| 737671d7a8 | |||
| e4f19d1d81 | |||
|
|
29c12e9249 | ||
|
|
1e22dae6f9 | ||
|
|
7b308d30bc | ||
|
|
ec13ebc43d | ||
|
|
640ecaea85 | ||
|
|
ef772a97ba | ||
|
|
e6cc6a8451 | ||
| 0989090456 | |||
| f8fc9ebdf8 | |||
|
|
ac2b115bd6 | ||
|
|
46eb9b4517 | ||
|
|
eaa81f8157 | ||
| e2eb288b90 | |||
| ed95c8c9fa | |||
|
|
7138e91b2e | ||
|
|
50642866b2 | ||
|
|
92c91f2388 | ||
|
|
42d1bc9a5f | ||
| c8013a080c | |||
| 8bdde936f8 | |||
| aacf518004 | |||
| 34c857387e | |||
| abc2ac07ef | |||
|
|
43d7972cc1 | ||
| 84a7a70183 | |||
| f61bbd00b7 | |||
| 84b74278a6 | |||
|
|
1438ad5efb | ||
| 01e85960fa | |||
|
|
c705610c1d | ||
| 5f0799d505 | |||
|
|
3454e0afbe | ||
| 95d9b74cd7 | |||
| 4b5f0263e4 | |||
| 7500640330 | |||
| 967a028235 | |||
|
|
abe5e30ede | ||
|
|
d9d3f63118 | ||
|
|
4f864c54bc | ||
|
|
2474f77291 | ||
|
|
6291a2ba70 | ||
| 77b10a858e | |||
| e908b3b67f | |||
|
|
bc98c0a3e6 | ||
|
|
f29caf4dc6 | ||
|
|
a1e88dd1c9 | ||
|
|
0dcfa53bcc | ||
| bf4ccdfd61 | |||
| ae65b5140f | |||
| 95aa5b0419 | |||
| b7b92cd785 | |||
| f97ae15969 | |||
| aae43df953 | |||
| c58f124f0c | |||
| 2f900d0538 | |||
| 3e75a4b4e2 | |||
| e285ccfa15 | |||
|
|
d2acbaa0ad | ||
|
|
c81be48585 | ||
|
|
93ec0d8808 | ||
| d5e07880fd | |||
| 8b370f152d | |||
| e8527c7ba4 | |||
| 1dd3d310c9 | |||
| b08685086a | |||
|
|
c2b6fe920f | ||
| a1ad86d0c7 | |||
| e6260ce170 | |||
| b0e53bc8c8 | |||
| 2267bc8f14 | |||
| 607a0927bc | |||
| 7b3ca9eb2a | |||
| 37c12e439c | |||
| 504579710e | |||
| ce94aee0f4 | |||
| b9c58ae125 | |||
| 92159e93b8 | |||
| f9b11895e2 | |||
| f7c3d493ea | |||
| 4954ab3d60 | |||
| bcca869e72 | |||
| a4247abdad | |||
| 2c1d43601a | |||
| c929c463ec | |||
| 314e1dede3 | |||
| d5b0ef34c5 | |||
| 3d9ef841b1 | |||
| b98871f170 | |||
| 38ab872dd8 | |||
| f44c0baa2e | |||
| 9b8d17577e | |||
| f301bee2b0 | |||
| fbe018e56a | |||
| ab046fe786 | |||
| ce95d8f977 | |||
| fa05b80e61 | |||
| 0ab0d11a98 | |||
| 7f469540b2 | |||
| 21bee29146 | |||
|
|
c2dd9c5d86 | ||
|
|
5927cb2bb5 | ||
|
|
4a4a215b61 | ||
| bfe931d3bf | |||
| b7b152d84d | |||
| b6f6eb1170 | |||
| 934800aae0 | |||
|
|
d19c37e99a | ||
|
|
43167fe9bd | ||
|
|
db8de88667 | ||
| 318b42dbd2 | |||
| af4a9f33b0 | |||
|
|
5e5bc4da2c | ||
|
|
594ea9a76f | ||
|
|
69e9ca7933 | ||
|
|
b1bc111b7a | ||
| 43970f4853 | |||
| 48b200697c | |||
| 1a791f5ef8 | |||
| 9b13a9e87c | |||
| ecad6b8070 | |||
| 1e6932b3de | |||
| 3ef7605e11 | |||
|
|
e8539c15cc | ||
|
|
9ace65f9df | ||
|
|
d727a0bc53 | ||
| 52947556a4 | |||
| 7fe9a6fd3d | |||
| 6dbfd31eab | |||
| 1788d40ed2 | |||
| 18d8e0cdcc | |||
| b37f927be6 | |||
| 314bf4c2f0 |
27
.github/workflows/TypeCheck.yml
vendored
Normal file
27
.github/workflows/TypeCheck.yml
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
name: TypeCheck
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
jobs:
|
||||
Mypy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install poetry
|
||||
run: pipx install poetry
|
||||
shell: bash
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
cache: 'poetry'
|
||||
|
||||
- run: poetry install
|
||||
shell: bash
|
||||
|
||||
- name: Run Mypy
|
||||
shell: bash
|
||||
run: |
|
||||
poetry run mypy ./nonebot_plugin_tetris_stats
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -19,3 +19,6 @@ package-lock.json
|
||||
bot.py
|
||||
TODO
|
||||
*.fish
|
||||
extracted_skin_mino_*
|
||||
sample_*
|
||||
TODO*
|
||||
|
||||
22
.pre-commit-config.yaml
Normal file
22
.pre-commit-config.yaml
Normal file
@@ -0,0 +1,22 @@
|
||||
default_install_hook_types: [pre-commit, prepare-commit-msg]
|
||||
ci:
|
||||
autofix_commit_msg: ':rotating_light: auto fix by pre-commit hooks'
|
||||
autofix_prs: true
|
||||
autoupdate_branch: master
|
||||
autoupdate_schedule: monthly
|
||||
autoupdate_commit_msg: ':arrow_up: auto update by pre-commit hooks'
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.4.10
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
stages: [commit]
|
||||
- id: ruff-format
|
||||
stages: [commit]
|
||||
|
||||
- repo: https://github.com/nonebot/nonemoji
|
||||
rev: v0.1.4
|
||||
hooks:
|
||||
- id: nonemoji
|
||||
stages: [prepare-commit-msg]
|
||||
10
README.md
10
README.md
@@ -87,3 +87,13 @@ pip install nonebot-plugin-tetris-stats
|
||||
## 📝 开源
|
||||
|
||||
本项目使用 [AGPL-3.0](https://github.com/shoucandanghehe/nonebot-plugin-tetris-stats/blob/main/LICENSE) 许可证开源
|
||||
|
||||
## 🤓☝ 给个 star 吧
|
||||
|
||||
<a href="https://star-history.com/#A-Minos/nonebot-plugin-tetris-stats&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=A-Minos/nonebot-plugin-tetris-stats&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=A-Minos/nonebot-plugin-tetris-stats&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=A-Minos/nonebot-plugin-tetris-stats&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
@@ -1,25 +1,39 @@
|
||||
from nonebot import require
|
||||
from nonebot.plugin import PluginMetadata
|
||||
from nonebot.plugin import PluginMetadata, inherit_supported_adapters
|
||||
|
||||
require('nonebot_plugin_alconna')
|
||||
require('nonebot_plugin_apscheduler')
|
||||
require('nonebot_plugin_localstore')
|
||||
require('nonebot_plugin_orm')
|
||||
require('nonebot_plugin_session')
|
||||
require('nonebot_plugin_session_orm')
|
||||
require_plugins = {
|
||||
'nonebot_plugin_alconna',
|
||||
'nonebot_plugin_apscheduler',
|
||||
'nonebot_plugin_localstore',
|
||||
'nonebot_plugin_orm',
|
||||
'nonebot_plugin_session_orm',
|
||||
'nonebot_plugin_session',
|
||||
'nonebot_plugin_user',
|
||||
'nonebot_plugin_userinfo',
|
||||
}
|
||||
|
||||
from .config.config import migrations # noqa: E402
|
||||
for i in require_plugins:
|
||||
require(i)
|
||||
|
||||
from nonebot_plugin_alconna import namespace # noqa: E402
|
||||
|
||||
with namespace('tetris_stats') as ns:
|
||||
ns.enable_message_cache = False
|
||||
|
||||
from .config import migrations # noqa: E402
|
||||
from .config.config import Config # noqa: E402
|
||||
|
||||
__plugin_meta__ = PluginMetadata(
|
||||
name='Tetris Stats',
|
||||
description='一个用于查询 Tetris 相关游戏玩家数据的插件',
|
||||
usage='发送 {游戏名} --help 查询使用方法',
|
||||
usage='发送 tstats --help 查询使用方法',
|
||||
type='application',
|
||||
homepage='https://github.com/A-minos/nonebot-plugin-tetris-stats',
|
||||
config=Config,
|
||||
supported_adapters=inherit_supported_adapters(*require_plugins),
|
||||
extra={
|
||||
'orm_version_location': migrations,
|
||||
},
|
||||
)
|
||||
|
||||
from . import game_data_processor # noqa: F401, E402
|
||||
from .utils import host # noqa: F401, E402
|
||||
from . import games # noqa: F401, E402
|
||||
|
||||
@@ -3,8 +3,6 @@ from pathlib import Path
|
||||
from nonebot_plugin_localstore import get_cache_dir # type: ignore[import-untyped]
|
||||
from pydantic import BaseModel
|
||||
|
||||
from . import migrations # noqa: F401
|
||||
|
||||
CACHE_PATH: Path = get_cache_dir('nonebot_plugin_tetris_stats')
|
||||
|
||||
|
||||
@@ -12,3 +10,4 @@ class Config(BaseModel):
|
||||
"""配置类"""
|
||||
|
||||
tetris_req_timeout: float = 30.0
|
||||
tetris_screenshot_quality: float = 2
|
||||
|
||||
@@ -46,7 +46,9 @@ def upgrade(name: str = '') -> None: # noqa: C901
|
||||
TimeRemainingColumn,
|
||||
)
|
||||
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import BaseProcessedData # type: ignore[attr-defined]
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import ( # type: ignore[import-untyped]
|
||||
BaseProcessedData,
|
||||
)
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=op.get_bind())
|
||||
|
||||
@@ -37,14 +37,10 @@ def migrate_old_data(connection: Connection) -> None:
|
||||
Bind = Base.classes.nonebot_plugin_tetris_stats_bind # noqa: N806
|
||||
|
||||
def non_empty(obj: str) -> bool:
|
||||
if obj != '' and not obj.isspace():
|
||||
return True
|
||||
return False
|
||||
return bool(obj != '' and not obj.isspace())
|
||||
|
||||
def is_int(obj: int | str) -> bool:
|
||||
if isinstance(obj, int) or obj.isdigit():
|
||||
return True
|
||||
return False
|
||||
return bool(isinstance(obj, int) or obj.isdigit())
|
||||
|
||||
bind_list = [
|
||||
Bind(chat_platform='OneBot V11', chat_account=int(row.QQ), game_platform='IO', game_account=row.USER)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Add TETRIO user configuration
|
||||
|
||||
迁移 ID: a1195e989cc6
|
||||
父迁移: b15844837693
|
||||
创建时间: 2024-06-09 04:20:07.819194
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'a1195e989cc6'
|
||||
down_revision: str | Sequence[str] | None = 'b15844837693'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
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_tetris_stats_tetriouserconfig',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('query_template', sa.String(length=2), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nonebot_plugin_tetris_stats_tetriouserconfig')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('nonebot_plugin_tetris_stats_tetriouserconfig')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Migrate to nonobot-plugin-user
|
||||
|
||||
迁移 ID: b15844837693
|
||||
父迁移: 3c25a5a8c050
|
||||
创建时间: 2024-06-08 02:27:35.227596
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'b15844837693'
|
||||
down_revision: str | Sequence[str] | None = '3c25a5a8c050'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_bind', schema=None) as batch_op:
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_bind_chat_account')
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_bind_chat_platform')
|
||||
|
||||
op.drop_table('nonebot_plugin_tetris_stats_bind')
|
||||
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_bind',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('game_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('game_account', sa.String(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nonebot_plugin_tetris_stats_bind')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_bind', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nonebot_plugin_tetris_stats_bind_user_id'), ['user_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_bind', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_bind_user_id'))
|
||||
|
||||
op.drop_table('nonebot_plugin_tetris_stats_bind')
|
||||
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_bind',
|
||||
sa.Column('id', sa.INTEGER(), nullable=False),
|
||||
sa.Column('chat_platform', sa.VARCHAR(length=32), nullable=False),
|
||||
sa.Column('chat_account', sa.VARCHAR(), nullable=False),
|
||||
sa.Column('game_platform', sa.VARCHAR(length=32), nullable=False),
|
||||
sa.Column('game_account', sa.VARCHAR(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name='pk_nonebot_plugin_tetris_stats_bind'),
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_bind', schema=None) as batch_op:
|
||||
batch_op.create_index('ix_nonebot_plugin_tetris_stats_bind_chat_platform', ['chat_platform'], unique=False)
|
||||
batch_op.create_index('ix_nonebot_plugin_tetris_stats_bind_chat_account', ['chat_account'], unique=False)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -46,7 +46,7 @@ def upgrade(name: str = '') -> None:
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import BaseUser
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import BaseUser # type: ignore[import-untyped]
|
||||
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('user_unique_identifier', sa.String(length=32), nullable=True))
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""TETR.IO new season
|
||||
|
||||
迁移 ID: f5b4a6d1325b
|
||||
父迁移: a1195e989cc6
|
||||
创建时间: 2024-08-01 20:44:48.644912
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'f5b4a6d1325b'
|
||||
down_revision: str | Sequence[str] | None = 'a1195e989cc6'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_iorank_file_hash')
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_iorank_rank')
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_iorank_update_time')
|
||||
|
||||
op.drop_table('nonebot_plugin_tetris_stats_iorank')
|
||||
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_tetriohistoricaldata', schema=None) as batch_op:
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_tetriohistoricaldata_api_type')
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_tetriohistoricaldata_update_time')
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_tetriohistoricaldata_user_unique_identifier')
|
||||
|
||||
op.drop_table('nonebot_plugin_tetris_stats_tetriohistoricaldata')
|
||||
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_tetriohistoricaldata',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_unique_identifier', sa.String(length=24), nullable=False),
|
||||
sa.Column('api_type', sa.String(length=16), nullable=False),
|
||||
sa.Column('data', sa.JSON(), nullable=False),
|
||||
sa.Column('update_time', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nonebot_plugin_tetris_stats_tetriohistoricaldata')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_tetriohistoricaldata', schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nonebot_plugin_tetris_stats_tetriohistoricaldata_api_type'), ['api_type'], unique=False
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nonebot_plugin_tetris_stats_tetriohistoricaldata_update_time'), ['update_time'], unique=False
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nonebot_plugin_tetris_stats_tetriohistoricaldata_user_unique_identifier'),
|
||||
['user_unique_identifier'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_iorank',
|
||||
sa.Column('id', sa.INTEGER(), nullable=False),
|
||||
sa.Column('rank', sa.VARCHAR(length=2), nullable=False),
|
||||
sa.Column('tr_line', sa.FLOAT(), nullable=False),
|
||||
sa.Column('player_count', sa.INTEGER(), nullable=False),
|
||||
sa.Column('low_pps', sa.JSON(), nullable=False),
|
||||
sa.Column('low_apm', sa.JSON(), nullable=False),
|
||||
sa.Column('low_vs', sa.JSON(), nullable=False),
|
||||
sa.Column('avg_pps', sa.FLOAT(), nullable=False),
|
||||
sa.Column('avg_apm', sa.FLOAT(), nullable=False),
|
||||
sa.Column('avg_vs', sa.FLOAT(), nullable=False),
|
||||
sa.Column('high_pps', sa.JSON(), nullable=False),
|
||||
sa.Column('high_apm', sa.JSON(), nullable=False),
|
||||
sa.Column('high_vs', sa.JSON(), nullable=False),
|
||||
sa.Column('update_time', sa.DATETIME(), nullable=False),
|
||||
sa.Column('file_hash', sa.VARCHAR(length=128), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id', name='pk_nonebot_plugin_tetris_stats_iorank'),
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.create_index('ix_nonebot_plugin_tetris_stats_iorank_update_time', ['update_time'], unique=False)
|
||||
batch_op.create_index('ix_nonebot_plugin_tetris_stats_iorank_rank', ['rank'], unique=False)
|
||||
batch_op.create_index('ix_nonebot_plugin_tetris_stats_iorank_file_hash', ['file_hash'], unique=False)
|
||||
@@ -8,17 +8,18 @@ from typing import TYPE_CHECKING, Literal, TypeVar, overload
|
||||
from nonebot.exception import FinishedException
|
||||
from nonebot.log import logger
|
||||
from nonebot_plugin_orm import AsyncSession, get_session
|
||||
from nonebot_plugin_user import User # type: ignore[import-untyped]
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..utils.typing import CommandType, GameType
|
||||
from ..utils.typing import AllCommandType, BaseCommandType, GameType, TETRIOCommandType
|
||||
from .models import Bind, TriggerHistoricalData
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..game_data_processor.io_data_processor.api.models import TETRIOHistoricalData
|
||||
from ..game_data_processor.top_data_processor.api.models import TOPHistoricalData
|
||||
from ..game_data_processor.tos_data_processor.api.models import TOSHistoricalData
|
||||
from ..games.tetrio.api.models import TETRIOHistoricalData
|
||||
from ..games.top.api.models import TOPHistoricalData
|
||||
from ..games.tos.api.models import TOSHistoricalData
|
||||
|
||||
|
||||
class BindStatus(Enum):
|
||||
@@ -28,37 +29,28 @@ class BindStatus(Enum):
|
||||
|
||||
async def query_bind_info(
|
||||
session: AsyncSession,
|
||||
chat_platform: str,
|
||||
chat_account: str,
|
||||
user: User,
|
||||
game_platform: GameType,
|
||||
) -> Bind | None:
|
||||
return (
|
||||
await session.scalars(
|
||||
select(Bind)
|
||||
.where(Bind.chat_platform == chat_platform)
|
||||
.where(Bind.chat_account == chat_account)
|
||||
.where(Bind.game_platform == game_platform)
|
||||
)
|
||||
await session.scalars(select(Bind).where(Bind.user_id == user.id).where(Bind.game_platform == game_platform))
|
||||
).one_or_none()
|
||||
|
||||
|
||||
async def create_or_update_bind(
|
||||
session: AsyncSession,
|
||||
chat_platform: str,
|
||||
chat_account: str,
|
||||
user: User,
|
||||
game_platform: GameType,
|
||||
game_account: str,
|
||||
) -> BindStatus:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
chat_platform=chat_platform,
|
||||
chat_account=chat_account,
|
||||
user=user,
|
||||
game_platform=game_platform,
|
||||
)
|
||||
if bind is None:
|
||||
bind = Bind(
|
||||
chat_platform=chat_platform,
|
||||
chat_account=chat_account,
|
||||
user_id=user.id,
|
||||
game_platform=game_platform,
|
||||
game_account=game_account,
|
||||
)
|
||||
@@ -100,7 +92,7 @@ async def anti_duplicate_add(cls: type[T], model: T) -> None:
|
||||
async def trigger(
|
||||
session_persist_id: int,
|
||||
game_platform: Literal['IO'],
|
||||
command_type: CommandType | Literal['rank'],
|
||||
command_type: TETRIOCommandType,
|
||||
command_args: list[str],
|
||||
) -> AsyncGenerator:
|
||||
yield
|
||||
@@ -111,7 +103,7 @@ async def trigger(
|
||||
async def trigger(
|
||||
session_persist_id: int,
|
||||
game_platform: GameType,
|
||||
command_type: CommandType,
|
||||
command_type: BaseCommandType,
|
||||
command_args: list[str],
|
||||
) -> AsyncGenerator:
|
||||
yield
|
||||
@@ -121,7 +113,7 @@ async def trigger(
|
||||
async def trigger(
|
||||
session_persist_id: int,
|
||||
game_platform: GameType,
|
||||
command_type: CommandType | Literal['rank'],
|
||||
command_type: AllCommandType,
|
||||
command_args: list[str],
|
||||
) -> AsyncGenerator:
|
||||
trigger_time = datetime.now(UTC)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from collections.abc import Callable, Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
from typing import Any
|
||||
|
||||
from nonebot.compat import PYDANTIC_V2, type_validate_json
|
||||
from nonebot_plugin_orm import Model
|
||||
@@ -9,7 +9,7 @@ from sqlalchemy import JSON, DateTime, Dialect, String, TypeDecorator
|
||||
from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
from typing_extensions import override
|
||||
|
||||
from ..utils.typing import CommandType, GameType
|
||||
from ..utils.typing import AllCommandType, GameType
|
||||
|
||||
|
||||
class PydanticType(TypeDecorator):
|
||||
@@ -66,8 +66,7 @@ class PydanticType(TypeDecorator):
|
||||
|
||||
class Bind(MappedAsDataclass, Model):
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
chat_platform: Mapped[str] = mapped_column(String(32), index=True)
|
||||
chat_account: Mapped[str] = mapped_column(index=True)
|
||||
user_id: Mapped[int] = mapped_column(index=True)
|
||||
game_platform: Mapped[GameType] = mapped_column(String(32))
|
||||
game_account: Mapped[str]
|
||||
|
||||
@@ -77,6 +76,6 @@ class TriggerHistoricalData(MappedAsDataclass, Model):
|
||||
trigger_time: Mapped[datetime] = mapped_column(DateTime)
|
||||
session_persist_id: Mapped[int]
|
||||
game_platform: Mapped[GameType] = mapped_column(String(32), index=True)
|
||||
command_type: Mapped[CommandType | Literal['rank']] = mapped_column(String(16), index=True)
|
||||
command_type: Mapped[AllCommandType] = mapped_column(String(16), index=True)
|
||||
command_args: Mapped[list[str]] = mapped_column(JSON)
|
||||
finish_time: Mapped[datetime] = mapped_column(DateTime)
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.exception import FinishedException
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.message import run_postprocessor
|
||||
from nonebot_plugin_alconna import AlcMatches, AlconnaMatcher, At
|
||||
|
||||
from ..utils.exception import MessageFormatError, NeedCatchError
|
||||
|
||||
|
||||
def add_default_handlers(matcher: type[AlconnaMatcher]) -> None:
|
||||
@matcher.assign('query')
|
||||
async def _(bot: Bot, matcher: Matcher, target: At):
|
||||
if isinstance(target, At) and target.target == bot.self_id:
|
||||
await matcher.finish('不能查询bot的信息')
|
||||
|
||||
@matcher.handle()
|
||||
async def _(matcher: Matcher, account: MessageFormatError):
|
||||
await matcher.finish(str(account))
|
||||
|
||||
@matcher.handle()
|
||||
async def _(matcher: Matcher, matches: AlcMatches):
|
||||
if matches.head_matched and matches.options != {} or matches.main_args == {}:
|
||||
await matcher.finish(
|
||||
(f'{matches.error_info!r}\n' if matches.error_info is not None else '')
|
||||
+ f'输入"{matches.header_result} --help"查看帮助'
|
||||
)
|
||||
|
||||
@matcher.handle()
|
||||
def _(other: Any): # noqa: ANN401, ARG001
|
||||
raise FinishedException
|
||||
|
||||
|
||||
from . import ( # noqa: F401, E402
|
||||
io_data_processor,
|
||||
top_data_processor,
|
||||
tos_data_processor,
|
||||
)
|
||||
|
||||
|
||||
@run_postprocessor
|
||||
async def _(matcher: Matcher, exception: NeedCatchError):
|
||||
await matcher.send(str(exception))
|
||||
@@ -1,85 +0,0 @@
|
||||
from arclet.alconna import Alconna, AllParam, Arg, ArgFlag, Args, CommandMeta, Option
|
||||
from nonebot_plugin_alconna import At, on_alconna
|
||||
|
||||
from ...utils.exception import MessageFormatError
|
||||
from ...utils.typing import Me
|
||||
from .. import add_default_handlers
|
||||
from ..constant import BIND_COMMAND, QUERY_COMMAND
|
||||
from .api import Player
|
||||
from .api.typing import Rank
|
||||
from .constant import USER_ID, USER_NAME
|
||||
|
||||
|
||||
def get_player(user_id_or_name: str) -> Player | MessageFormatError:
|
||||
if USER_ID.match(user_id_or_name):
|
||||
return Player(user_id=user_id_or_name, trust=True)
|
||||
if USER_NAME.match(user_id_or_name):
|
||||
return Player(user_name=user_id_or_name, trust=True)
|
||||
return MessageFormatError('用户名/ID不合法')
|
||||
|
||||
|
||||
alc = on_alconna(
|
||||
Alconna(
|
||||
'io',
|
||||
Option(
|
||||
BIND_COMMAND[0],
|
||||
Args(
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='IO 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN],
|
||||
)
|
||||
),
|
||||
alias=BIND_COMMAND[1:],
|
||||
compact=True,
|
||||
dest='bind',
|
||||
help_text='绑定 IO 账号',
|
||||
),
|
||||
Option(
|
||||
QUERY_COMMAND[0],
|
||||
Args(
|
||||
Arg(
|
||||
'target',
|
||||
At | Me,
|
||||
notice='@想要查询的人 | 自己',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='IO 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
alias=QUERY_COMMAND[1:],
|
||||
compact=True,
|
||||
dest='query',
|
||||
help_text='查询 IO 游戏信息',
|
||||
),
|
||||
Option(
|
||||
'rank',
|
||||
Args(Arg('rank', Rank, notice='IO 段位')),
|
||||
alias={'Rank', 'RANK', '段位'},
|
||||
compact=True,
|
||||
dest='rank',
|
||||
help_text='查询 IO 段位信息',
|
||||
),
|
||||
Arg('other', AllParam, flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL]),
|
||||
meta=CommandMeta(
|
||||
description='查询 TETR.IO 的信息',
|
||||
example='io绑定scdhh\nio查我\niorankx',
|
||||
compact=True,
|
||||
fuzzy_match=True,
|
||||
),
|
||||
),
|
||||
skip_for_unmatch=False,
|
||||
auto_send_output=True,
|
||||
aliases={'IO'},
|
||||
)
|
||||
|
||||
alc.shortcut('fkosk', {'command': 'io查', 'args': ['我'], 'fuzzy': False, 'humanized': 'An Easter egg!'})
|
||||
|
||||
from . import bind, query, rank # noqa: F401, E402
|
||||
|
||||
add_default_handlers(alc)
|
||||
@@ -1,102 +0,0 @@
|
||||
from typing import overload
|
||||
|
||||
from nonebot.compat import type_validate_json
|
||||
|
||||
from ....db import anti_duplicate_add
|
||||
from ....utils.exception import RequestError
|
||||
from ....utils.request import splice_url
|
||||
from ..constant import BASE_URL, USER_ID, USER_NAME
|
||||
from .cache import Cache
|
||||
from .models import TETRIOHistoricalData
|
||||
from .schemas.base import FailedModel
|
||||
from .schemas.user import User
|
||||
from .schemas.user_info import UserInfo, UserInfoSuccess
|
||||
from .schemas.user_records import UserRecords, UserRecordsSuccess
|
||||
|
||||
|
||||
class Player:
|
||||
@overload
|
||||
def __init__(self, *, user_id: str, trust: bool = False): ...
|
||||
@overload
|
||||
def __init__(self, *, user_name: str, trust: bool = False): ...
|
||||
def __init__(self, *, user_id: str | None = None, user_name: str | None = None, trust: bool = False):
|
||||
self.user_id = user_id
|
||||
self.user_name = user_name
|
||||
if not trust:
|
||||
if self.user_id is not None:
|
||||
if not USER_ID.match(self.user_id):
|
||||
msg = 'Invalid user id'
|
||||
raise ValueError(msg)
|
||||
elif self.user_name is not None:
|
||||
if not USER_NAME.match(self.user_name):
|
||||
msg = 'Invalid user name'
|
||||
raise ValueError(msg)
|
||||
else:
|
||||
msg = 'Invalid user'
|
||||
raise ValueError(msg)
|
||||
self.__user: User | None = None
|
||||
self._user_info: UserInfoSuccess | None = None
|
||||
self._user_records: UserRecordsSuccess | None = None
|
||||
|
||||
@property
|
||||
def _request_user_parameter(self) -> str:
|
||||
if self.user_id is not None:
|
||||
return self.user_id
|
||||
if self.user_name is not None:
|
||||
return self.user_name.lower()
|
||||
msg = 'Invalid user'
|
||||
raise ValueError(msg)
|
||||
|
||||
@property
|
||||
async def user(self) -> User:
|
||||
if self.__user is None:
|
||||
user_info = await self.get_info()
|
||||
self.__user = User(
|
||||
ID=user_info.data.user.id,
|
||||
name=user_info.data.user.username,
|
||||
)
|
||||
self.user_id = user_info.data.user.id
|
||||
self.user_name = user_info.data.user.username
|
||||
return self.__user
|
||||
|
||||
async def get_info(self) -> UserInfoSuccess:
|
||||
"""Get User Info"""
|
||||
if self._user_info is None:
|
||||
raw_user_info = await Cache.get(splice_url([BASE_URL, 'users/', f'{self._request_user_parameter}']))
|
||||
user_info: UserInfo = type_validate_json(UserInfo, raw_user_info) # type: ignore[arg-type]
|
||||
if isinstance(user_info, FailedModel):
|
||||
msg = f'用户信息请求错误:\n{user_info.error}'
|
||||
raise RequestError(msg)
|
||||
self._user_info = user_info
|
||||
await anti_duplicate_add(
|
||||
TETRIOHistoricalData,
|
||||
TETRIOHistoricalData(
|
||||
user_unique_identifier=(await self.user).unique_identifier,
|
||||
api_type='User Info',
|
||||
data=user_info,
|
||||
update_time=user_info.cache.cached_at,
|
||||
),
|
||||
)
|
||||
return self._user_info
|
||||
|
||||
async def get_records(self) -> UserRecordsSuccess:
|
||||
"""Get User Records"""
|
||||
if self._user_records is None:
|
||||
raw_user_records = await Cache.get(
|
||||
splice_url([BASE_URL, 'users/', f'{self._request_user_parameter}/', 'records'])
|
||||
)
|
||||
user_records: UserRecords = type_validate_json(UserRecords, raw_user_records) # type: ignore[arg-type]
|
||||
if isinstance(user_records, FailedModel):
|
||||
msg = f'用户Solo数据请求错误:\n{user_records.error}'
|
||||
raise RequestError(msg)
|
||||
self._user_records = user_records
|
||||
await anti_duplicate_add(
|
||||
TETRIOHistoricalData,
|
||||
TETRIOHistoricalData(
|
||||
user_unique_identifier=(await self.user).unique_identifier,
|
||||
api_type='User Records',
|
||||
data=user_records,
|
||||
update_time=user_records.cache.cached_at,
|
||||
),
|
||||
)
|
||||
return self._user_records
|
||||
@@ -1,22 +0,0 @@
|
||||
from typing import Literal
|
||||
|
||||
Rank = Literal[
|
||||
'x',
|
||||
'u',
|
||||
'ss',
|
||||
's+',
|
||||
's',
|
||||
's-',
|
||||
'a+',
|
||||
'a',
|
||||
'a-',
|
||||
'b+',
|
||||
'b',
|
||||
'b-',
|
||||
'c+',
|
||||
'c',
|
||||
'c-',
|
||||
'd+',
|
||||
'd',
|
||||
'z', # 未定级
|
||||
]
|
||||
@@ -1,28 +0,0 @@
|
||||
from datetime import datetime
|
||||
|
||||
from nonebot_plugin_orm import Model
|
||||
from sqlalchemy import JSON, DateTime, String
|
||||
from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
from .api.typing import Rank
|
||||
|
||||
|
||||
class IORank(MappedAsDataclass, Model):
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
rank: Mapped[Rank] = mapped_column(String(2), index=True)
|
||||
tr_line: Mapped[float]
|
||||
player_count: Mapped[int]
|
||||
low_pps: Mapped[tuple[dict[str, str], float]] = mapped_column(JSON)
|
||||
low_apm: Mapped[tuple[dict[str, str], float]] = mapped_column(JSON)
|
||||
low_vs: Mapped[tuple[dict[str, str], float]] = mapped_column(JSON)
|
||||
avg_pps: Mapped[float]
|
||||
avg_apm: Mapped[float]
|
||||
avg_vs: Mapped[float]
|
||||
high_pps: Mapped[tuple[dict[str, str], float]] = mapped_column(JSON)
|
||||
high_apm: Mapped[tuple[dict[str, str], float]] = mapped_column(JSON)
|
||||
high_vs: Mapped[tuple[dict[str, str], float]] = mapped_column(JSON)
|
||||
update_time: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
index=True,
|
||||
)
|
||||
file_hash: Mapped[str | None] = mapped_column(String(128), index=True)
|
||||
@@ -1,297 +0,0 @@
|
||||
import contextlib
|
||||
from asyncio import gather
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import md5
|
||||
from math import ceil, floor
|
||||
from urllib.parse import urlunparse
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.platform import get_platform
|
||||
from ...utils.render import TETRIOInfo, render
|
||||
from ...utils.render.schemas.base import Avatar
|
||||
from ...utils.render.schemas.tetrio_info import Data, Radar, Ranking, TetraLeague, TetraLeagueHistory
|
||||
from ...utils.render.schemas.tetrio_info import User as TemplateUser
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.typing import Me
|
||||
from ..constant import CANT_VERIFY_MESSAGE
|
||||
from . import alc
|
||||
from .api import Player, User, UserInfoSuccess
|
||||
from .api.models import TETRIOHistoricalData
|
||||
from .api.schemas.user_info import NeverPlayedLeague, NeverRatedLeague, RatedLeague
|
||||
from .api.schemas.user_records import SoloModeRecord, SoloRecord
|
||||
from .constant import GAME_TYPE, TR_MAX, TR_MIN
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
|
||||
@alc.assign('query')
|
||||
async def _(bot: Bot, event: Event, matcher: Matcher, target: At | Me, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
chat_platform=get_platform(bot),
|
||||
chat_account=(target.target if isinstance(target, At) else event.get_user_id()),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = UniMessage(CANT_VERIFY_MESSAGE)
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
user, user_info, user_records = await gather(player.user, player.get_info(), player.get_records())
|
||||
sprint = user_records.data.records.sprint
|
||||
blitz = user_records.data.records.blitz
|
||||
with contextlib.suppress(TypeError):
|
||||
message += UniMessage.image(raw=await make_query_image(user, user_info, sprint.record, blitz.record))
|
||||
await message.finish()
|
||||
message += make_query_text(user_info, sprint, blitz)
|
||||
await message.finish()
|
||||
|
||||
|
||||
@alc.assign('query')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
user, user_info, user_records = await gather(account.user, account.get_info(), account.get_records())
|
||||
sprint = user_records.data.records.sprint
|
||||
blitz = user_records.data.records.blitz
|
||||
with contextlib.suppress(TypeError):
|
||||
await UniMessage.image(raw=await make_query_image(user, user_info, sprint.record, blitz.record)).finish()
|
||||
await make_query_text(user_info, sprint, blitz).finish()
|
||||
|
||||
|
||||
def get_value_bounds(values: list[int | float]) -> tuple[int, int]:
|
||||
value_max = 10 * ceil(max(values) / 10)
|
||||
value_min = 10 * floor(min(values) / 10)
|
||||
return value_max, value_min
|
||||
|
||||
|
||||
def get_split(value_max: int, value_min: int) -> tuple[int, int]:
|
||||
offset = 0
|
||||
overflow = 0
|
||||
|
||||
while True:
|
||||
if (new_max_value := value_max + offset + overflow) > TR_MAX:
|
||||
overflow -= 1
|
||||
continue
|
||||
if (new_min_value := value_min - offset + overflow) < TR_MIN:
|
||||
overflow += 1
|
||||
continue
|
||||
if ((new_max_value - new_min_value) / 40).is_integer():
|
||||
split_value = int((value_max + offset - (value_min - offset)) / 4)
|
||||
break
|
||||
offset += 1
|
||||
return split_value, offset + overflow
|
||||
|
||||
|
||||
def get_specified_point(
|
||||
previous_point: Data,
|
||||
behind_point: Data,
|
||||
point_time: datetime,
|
||||
) -> Data:
|
||||
"""根据给出的 previous_point 和 behind_point, 推算 point_time 点处的数据
|
||||
|
||||
Args:
|
||||
previous_point (Data): 前面的数据点
|
||||
behind_point (Data): 后面的数据点
|
||||
point_time (datetime): 要推算的点的位置
|
||||
|
||||
Returns:
|
||||
Data: 要推算的点的数据
|
||||
"""
|
||||
# 求两个点的斜率
|
||||
slope = (behind_point.tr - previous_point.tr) / (
|
||||
datetime.timestamp(behind_point.record_at) - datetime.timestamp(previous_point.record_at)
|
||||
)
|
||||
return Data(
|
||||
record_at=point_time,
|
||||
tr=previous_point.tr + slope * (datetime.timestamp(point_time) - datetime.timestamp(previous_point.record_at)),
|
||||
)
|
||||
|
||||
|
||||
async def query_historical_data(user: User, user_info: UserInfoSuccess) -> list[Data]:
|
||||
today = datetime.now(ZoneInfo('Asia/Shanghai')).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
forward = timedelta(days=9)
|
||||
start_time = (today - forward).astimezone(UTC)
|
||||
async with get_session() as session:
|
||||
historical_data = (
|
||||
await session.scalars(
|
||||
select(TETRIOHistoricalData)
|
||||
.where(TETRIOHistoricalData.update_time >= start_time)
|
||||
.where(TETRIOHistoricalData.user_unique_identifier == user.unique_identifier)
|
||||
.where(TETRIOHistoricalData.api_type == 'User Info')
|
||||
)
|
||||
).all()
|
||||
if historical_data:
|
||||
extra = (
|
||||
await session.scalars(
|
||||
select(TETRIOHistoricalData)
|
||||
.where(TETRIOHistoricalData.user_unique_identifier == user.unique_identifier)
|
||||
.where(TETRIOHistoricalData.api_type == 'User Info')
|
||||
.order_by(TETRIOHistoricalData.id.desc())
|
||||
.where(TETRIOHistoricalData.id < min([i.id for i in historical_data]))
|
||||
.limit(1)
|
||||
)
|
||||
).one_or_none()
|
||||
if extra is not None:
|
||||
historical_data = list(historical_data)
|
||||
historical_data.append(extra)
|
||||
if not historical_data:
|
||||
return [
|
||||
Data(record_at=today - forward, tr=user_info.data.user.league.rating),
|
||||
Data(record_at=today.replace(microsecond=1000), tr=user_info.data.user.league.rating),
|
||||
]
|
||||
histories = [
|
||||
Data(
|
||||
record_at=i.update_time.astimezone(ZoneInfo('Asia/Shanghai')),
|
||||
tr=i.data.data.user.league.rating,
|
||||
)
|
||||
for i in historical_data
|
||||
if isinstance(i.data, UserInfoSuccess) and isinstance(i.data.data.user.league, RatedLeague)
|
||||
]
|
||||
|
||||
# 按照时间排序
|
||||
histories = sorted(histories, key=lambda x: x.record_at)
|
||||
print(histories)
|
||||
for index, value in enumerate(histories):
|
||||
# 在历史记录里找有没有今天0点后的数据, 并且至少要有两个数据点
|
||||
if value.record_at > today and len(histories) >= 2: # noqa: PLR2004
|
||||
histories = histories[:index] + [
|
||||
get_specified_point(histories[index - 1], histories[index], today.replace(microsecond=1000))
|
||||
]
|
||||
break
|
||||
else:
|
||||
histories.append(
|
||||
get_specified_point(
|
||||
histories[-1],
|
||||
Data(record_at=user_info.cache.cached_at, tr=user_info.data.user.league.rating),
|
||||
today.replace(microsecond=1000),
|
||||
)
|
||||
)
|
||||
if histories[0].record_at < (today - forward):
|
||||
histories[0] = get_specified_point(
|
||||
histories[0],
|
||||
histories[1],
|
||||
today - forward,
|
||||
)
|
||||
else:
|
||||
histories.insert(0, Data(record_at=today - forward, tr=histories[0].tr))
|
||||
return histories
|
||||
|
||||
|
||||
async def make_query_image(
|
||||
user: User, user_info: UserInfoSuccess, sprint: SoloRecord | None, blitz: SoloRecord | None
|
||||
) -> bytes:
|
||||
league = user_info.data.user.league
|
||||
if not isinstance(league, RatedLeague) or league.vs is None:
|
||||
raise TypeError
|
||||
user_name = user_info.data.user.username.upper()
|
||||
histories = await query_historical_data(user, user_info)
|
||||
value_max, value_min = get_value_bounds([i.tr for i in histories])
|
||||
split_value, offset = get_split(value_max, value_min)
|
||||
if sprint is not None:
|
||||
duration = timedelta(milliseconds=sprint.endcontext.final_time).total_seconds()
|
||||
sprint_value = f'{duration:.1f}s' if duration < 60 else f'{duration // 60:.0f}m {duration % 60:.1f}s' # noqa: PLR2004
|
||||
else:
|
||||
sprint_value = 'N/A'
|
||||
blitz_value = f'{blitz.endcontext.score:,}' if blitz is not None else 'N/A'
|
||||
async with HostPage(
|
||||
await render(
|
||||
'tetrio/info',
|
||||
TETRIOInfo(
|
||||
user=TemplateUser(
|
||||
avatar=f'https://tetr.io/user-content/avatars/{user_info.data.user.id}.jpg?rv={user_info.data.user.avatar_revision}'
|
||||
if user_info.data.user.avatar_revision is not None
|
||||
else Avatar(
|
||||
type='identicon',
|
||||
hash=md5(user_info.data.user.id.encode()).hexdigest(), # noqa: S324
|
||||
),
|
||||
name=user_name,
|
||||
bio=user_info.data.user.bio,
|
||||
),
|
||||
ranking=Ranking(
|
||||
rating=round(league.glicko, 2),
|
||||
rd=round(league.rd, 2),
|
||||
),
|
||||
tetra_league=TetraLeague(
|
||||
rank=league.rank,
|
||||
tr=round(league.rating, 2),
|
||||
global_rank=league.standing,
|
||||
pps=league.pps,
|
||||
lpm=round(lpm := (league.pps * 24), 2),
|
||||
apm=league.apm,
|
||||
apl=round(league.apm / lpm, 2),
|
||||
vs=league.vs,
|
||||
adpm=round(adpm := (league.vs * 0.6), 2),
|
||||
adpl=round(adpm / lpm, 2),
|
||||
),
|
||||
tetra_league_history=TetraLeagueHistory(
|
||||
data=histories,
|
||||
split_interval=split_value,
|
||||
min_tr=value_min,
|
||||
max_tr=value_max,
|
||||
offset=offset,
|
||||
),
|
||||
radar=Radar(
|
||||
app=(app := (league.apm / (60 * league.pps))),
|
||||
dsps=(dsps := ((league.vs / 100) - (league.apm / 60))),
|
||||
dspp=(dspp := (dsps / league.pps)),
|
||||
ci=150 * dspp - 125 * app + 50 * (league.vs / league.apm) - 25,
|
||||
ge=2 * ((app * dsps) / league.pps),
|
||||
),
|
||||
sprint=sprint_value,
|
||||
blitz=blitz_value,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(urlunparse(('http', get_self_netloc(), f'/host/{page_hash}.html', '', '', '')))
|
||||
|
||||
|
||||
def make_query_text(user_info: UserInfoSuccess, sprint: SoloModeRecord, blitz: SoloModeRecord) -> UniMessage:
|
||||
league = user_info.data.user.league
|
||||
user_name = user_info.data.user.username.upper()
|
||||
message = ''
|
||||
if isinstance(league, NeverPlayedLeague):
|
||||
message += f'用户 {user_name} 没有排位统计数据'
|
||||
else:
|
||||
if isinstance(league, NeverRatedLeague):
|
||||
message += f'用户 {user_name} 暂未完成定级赛, 最近十场的数据:'
|
||||
else:
|
||||
if league.rank == 'z':
|
||||
message += f'用户 {user_name} 暂无段位, {round(league.rating,2)} TR'
|
||||
else:
|
||||
message += f'{league.rank.upper()} 段用户 {user_name} {round(league.rating,2)} TR (#{league.standing})'
|
||||
message += f', 段位分 {round(league.glicko,2)}±{round(league.rd,2)}, 最近十场的数据:'
|
||||
lpm = league.pps * 24
|
||||
message += f"\nL'PM: {round(lpm, 2)} ( {league.pps} pps )"
|
||||
message += f'\nAPM: {league.apm} ( x{round(league.apm/lpm,2)} )'
|
||||
if league.vs is not None:
|
||||
adpm = league.vs * 0.6
|
||||
message += f'\nADPM: {round(adpm,2)} ( x{round(adpm/lpm,2)} ) ( {league.vs}vs )'
|
||||
if sprint.record is not None:
|
||||
message += f'\n40L: {round(sprint.record.endcontext.final_time/1000,2)}s'
|
||||
message += f' ( #{sprint.rank} )' if sprint.rank is not None else ''
|
||||
if blitz.record is not None:
|
||||
message += f'\nBlitz: {blitz.record.endcontext.score}'
|
||||
message += f' ( #{blitz.rank} )' if blitz.rank is not None else ''
|
||||
return UniMessage(message)
|
||||
@@ -1,174 +0,0 @@
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import sha512
|
||||
from math import floor
|
||||
from statistics import mean
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from aiofiles import open
|
||||
from nonebot import get_driver
|
||||
from nonebot.compat import model_dump
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.utils import run_sync
|
||||
from nonebot_plugin_apscheduler import scheduler # type: ignore[import-untyped]
|
||||
from nonebot_plugin_localstore import get_data_file # type: ignore[import-untyped]
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from sqlalchemy import func, select
|
||||
from zstandard import ZstdCompressor
|
||||
|
||||
from ...db import trigger
|
||||
from ...utils.exception import RequestError
|
||||
from ...utils.metrics import get_metrics
|
||||
from ...utils.retry import retry
|
||||
from . import alc
|
||||
from .api.schemas.base import FailedModel
|
||||
from .api.schemas.tetra_league import ValidUser
|
||||
from .api.schemas.user import User
|
||||
from .api.tetra_league import full_export
|
||||
from .api.typing import Rank
|
||||
from .constant import GAME_TYPE, RANK_PERCENTILE
|
||||
from .model import IORank
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
|
||||
@alc.assign('rank')
|
||||
async def _(matcher: Matcher, rank: Rank, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='rank',
|
||||
command_args=[],
|
||||
):
|
||||
if rank == 'z':
|
||||
await matcher.finish('暂不支持查询未知段位')
|
||||
async with get_session() as session:
|
||||
latest_data = (
|
||||
await session.scalars(select(IORank).where(IORank.rank == rank).order_by(IORank.id.desc()).limit(1))
|
||||
).one()
|
||||
compare_data = (
|
||||
await session.scalars(
|
||||
select(IORank)
|
||||
.where(IORank.rank == rank)
|
||||
.order_by(
|
||||
func.abs(
|
||||
func.julianday(IORank.update_time)
|
||||
- func.julianday(latest_data.update_time - timedelta(hours=24))
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
).one()
|
||||
message = ''
|
||||
if (datetime.now(UTC) - latest_data.update_time.replace(tzinfo=UTC)) > timedelta(hours=7):
|
||||
message += 'Warning: 数据超过7小时未更新, 请联系Bot主人查看后台\n'
|
||||
message += f'{rank.upper()} 段 分数线 {latest_data.tr_line:.2f} TR, {latest_data.player_count} 名玩家\n'
|
||||
if compare_data.id != latest_data.id:
|
||||
message += f'对比 {(latest_data.update_time-compare_data.update_time).total_seconds()/3600:.2f} 小时前趋势: {f"↑{difference:.2f}" if (difference:=latest_data.tr_line-compare_data.tr_line) > 0 else f"↓{-difference:.2f}" if difference < 0 else "→"}'
|
||||
else:
|
||||
message += '暂无对比数据'
|
||||
avg = get_metrics(pps=latest_data.avg_pps, apm=latest_data.avg_apm, vs=latest_data.avg_vs)
|
||||
low_pps = get_metrics(pps=latest_data.low_pps[1])
|
||||
low_vs = get_metrics(vs=latest_data.low_vs[1])
|
||||
max_pps = get_metrics(pps=latest_data.high_pps[1])
|
||||
max_vs = get_metrics(vs=latest_data.high_vs[1])
|
||||
message += (
|
||||
'\n'
|
||||
'平均数据:\n'
|
||||
f"L'PM: {avg.lpm} ( {avg.pps} pps )\n"
|
||||
f'APM: {avg.apm} ( x{avg.apl} )\n'
|
||||
f'ADPM: {avg.adpm} ( x{avg.adpl} ) ( {avg.vs}vs )\n'
|
||||
'\n'
|
||||
'最低数据:\n'
|
||||
f"L'PM: {low_pps.lpm} ( {low_pps.pps} pps ) By: {latest_data.low_pps[0]['name'].upper()}\n"
|
||||
f'APM: {latest_data.low_apm[1]} By: {latest_data.low_apm[0]["name"].upper()}\n'
|
||||
f'ADPM: {low_vs.adpm} ( {low_vs.vs}vs ) By: {latest_data.low_vs[0]["name"].upper()}\n'
|
||||
'\n'
|
||||
'最高数据:\n'
|
||||
f"L'PM: {max_pps.lpm} ( {max_pps.pps} pps ) By: {latest_data.high_pps[0]['name'].upper()}\n"
|
||||
f'APM: {latest_data.high_apm[1]} By: {latest_data.high_apm[0]["name"].upper()}\n'
|
||||
f'ADPM: {max_vs.adpm} ( {max_vs.vs}vs ) By: {latest_data.high_vs[0]["name"].upper()}\n'
|
||||
'\n'
|
||||
f'数据更新时间: {latest_data.update_time.replace(tzinfo=UTC).astimezone(ZoneInfo("Asia/Shanghai")).strftime("%Y-%m-%d %H:%M:%S")}'
|
||||
)
|
||||
await matcher.finish(message)
|
||||
|
||||
|
||||
@scheduler.scheduled_job('cron', hour='0,6,12,18', minute=0)
|
||||
@retry(exception_type=RequestError, delay=timedelta(minutes=15))
|
||||
async def get_tetra_league_data() -> None:
|
||||
league, original = await full_export(with_original=True)
|
||||
if isinstance(league, FailedModel):
|
||||
msg = f'排行榜数据请求错误:\n{league.error}'
|
||||
raise RequestError(msg)
|
||||
|
||||
def pps(user: ValidUser) -> float:
|
||||
return user.league.pps
|
||||
|
||||
def apm(user: ValidUser) -> float:
|
||||
return user.league.apm
|
||||
|
||||
def vs(user: ValidUser) -> float:
|
||||
return user.league.vs
|
||||
|
||||
def _min(users: list[ValidUser], field: Callable[[ValidUser], float]) -> ValidUser:
|
||||
return min(users, key=field)
|
||||
|
||||
def _max(users: list[ValidUser], field: Callable[[ValidUser], float]) -> ValidUser:
|
||||
return max(users, key=field)
|
||||
|
||||
def build_extremes_data(
|
||||
users: list[ValidUser],
|
||||
field: Callable[[ValidUser], float],
|
||||
sort: Callable[[list[ValidUser], Callable[[ValidUser], float]], ValidUser],
|
||||
) -> tuple[dict[str, str], float]:
|
||||
user = sort(users, field)
|
||||
return model_dump(User(ID=user.id, name=user.username)), field(user)
|
||||
|
||||
data_hash: str | None = await run_sync((await run_sync(sha512)(original)).hexdigest)()
|
||||
async with open(get_data_file('nonebot_plugin_tetris_stats', f'{data_hash}.json.zst'), mode='wb') as file:
|
||||
await file.write(await run_sync(ZstdCompressor(level=12, threads=-1).compress)(original))
|
||||
|
||||
users = [i for i in league.data.users if isinstance(i, ValidUser)]
|
||||
rank_to_users: defaultdict[Rank, list[ValidUser]] = defaultdict(list)
|
||||
for i in users:
|
||||
rank_to_users[i.league.rank].append(i)
|
||||
rank_info: list[IORank] = []
|
||||
for rank, percentile in RANK_PERCENTILE.items():
|
||||
offset = floor((percentile / 100) * len(users)) - 1
|
||||
tr_line = users[offset].league.rating
|
||||
rank_users = rank_to_users[rank]
|
||||
rank_info.append(
|
||||
IORank(
|
||||
rank=rank,
|
||||
tr_line=tr_line,
|
||||
player_count=len(rank_users),
|
||||
low_pps=(build_extremes_data(rank_users, pps, _min)),
|
||||
low_apm=(build_extremes_data(rank_users, apm, _min)),
|
||||
low_vs=(build_extremes_data(rank_users, vs, _min)),
|
||||
avg_pps=mean({i.league.pps for i in rank_users}),
|
||||
avg_apm=mean({i.league.apm for i in rank_users}),
|
||||
avg_vs=mean({i.league.vs for i in rank_users}),
|
||||
high_pps=(build_extremes_data(rank_users, pps, _max)),
|
||||
high_apm=(build_extremes_data(rank_users, apm, _max)),
|
||||
high_vs=(build_extremes_data(rank_users, vs, _max)),
|
||||
update_time=league.cache.cached_at,
|
||||
file_hash=data_hash,
|
||||
)
|
||||
)
|
||||
async with get_session() as session:
|
||||
session.add_all(rank_info)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def _() -> None:
|
||||
async with get_session() as session:
|
||||
latest_time = await session.scalar(select(IORank.update_time).order_by(IORank.id.desc()).limit(1))
|
||||
if latest_time is None or datetime.now(tz=UTC) - latest_time.replace(tzinfo=UTC) > timedelta(hours=6):
|
||||
await get_tetra_league_data()
|
||||
@@ -1,170 +0,0 @@
|
||||
from asyncio import gather
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...utils.metrics import TetrisMetricsProWithLPMADPM, get_metrics
|
||||
from ...utils.platform import get_platform
|
||||
from ...utils.typing import Me
|
||||
from ..constant import CANT_VERIFY_MESSAGE
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
def add_special_handlers(
|
||||
teaid_prefix: Literal['onebot-', 'kook-', 'discord-', 'qqguild-'], match_event: type[Event]
|
||||
) -> None:
|
||||
@alc.assign('query')
|
||||
async def _(event: Event, target: At | Me, event_session: EventSession):
|
||||
if isinstance(event, match_event):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
await (
|
||||
await make_query_text(
|
||||
Player(
|
||||
teaid=f'{teaid_prefix}{target.target}'
|
||||
if isinstance(target, At)
|
||||
else f'{teaid_prefix}{event.get_user_id()}',
|
||||
trust=True,
|
||||
)
|
||||
)
|
||||
).finish()
|
||||
|
||||
|
||||
try:
|
||||
from nonebot.adapters.onebot.v11 import MessageEvent as OB11MessageEvent
|
||||
|
||||
add_special_handlers('onebot-', OB11MessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from nonebot.adapters.qq.event import GuildMessageEvent as QQGuildMessageEvent
|
||||
from nonebot.adapters.qq.event import QQMessageEvent
|
||||
|
||||
add_special_handlers('qqguild-', QQGuildMessageEvent)
|
||||
add_special_handlers('onebot-', QQMessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from nonebot.adapters.kaiheila.event import MessageEvent as KookMessageEvent
|
||||
|
||||
add_special_handlers('kook-', KookMessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from nonebot.adapters.discord import MessageEvent as DiscordMessageEvent
|
||||
|
||||
add_special_handlers('discord-', DiscordMessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
@alc.assign('query')
|
||||
async def _(bot: Bot, event: Event, matcher: Matcher, target: At | Me, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
chat_platform=get_platform(bot),
|
||||
chat_account=(target.target if isinstance(target, At) else event.get_user_id()),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = CANT_VERIFY_MESSAGE
|
||||
await (message + await make_query_text(Player(teaid=bind.game_account, trust=True))).finish()
|
||||
|
||||
|
||||
@alc.assign('query')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
await (await make_query_text(account)).finish()
|
||||
|
||||
|
||||
@dataclass
|
||||
class GameData:
|
||||
game_num: int
|
||||
metrics: TetrisMetricsProWithLPMADPM
|
||||
|
||||
|
||||
async def get_game_data(player: Player, query_num: int = 50) -> GameData | None:
|
||||
"""获取游戏数据"""
|
||||
user_profile = await player.get_profile()
|
||||
if user_profile.data == []:
|
||||
return None
|
||||
weighted_total_lpm = weighted_total_apm = weighted_total_adpm = total_time = 0.0
|
||||
num = 0
|
||||
for i in user_profile.data:
|
||||
# 排除单人局和时间为0的游戏
|
||||
# 茶: 不计算没挖掘的局, 即使apm和lpm也如此
|
||||
if i.num_players == 1 or i.time == 0 or i.dig is None:
|
||||
continue
|
||||
# 加权计算
|
||||
time = i.time / 1000
|
||||
lpm = 24 * (i.pieces / time)
|
||||
apm = (i.attack / time) * 60
|
||||
adpm = ((i.attack + i.dig) / time) * 60
|
||||
weighted_total_lpm += lpm * time
|
||||
weighted_total_apm += apm * time
|
||||
weighted_total_adpm += adpm * time
|
||||
total_time += time
|
||||
num += 1
|
||||
if num >= query_num:
|
||||
break
|
||||
if num == 0:
|
||||
return None
|
||||
# TODO: 如果有效局数小于 {查询数} , 并且没有无dig信息的局, 且 user_profile.data 内有{请求数}个局, 则继续往前获取信息
|
||||
metrics = get_metrics(
|
||||
lpm=weighted_total_lpm / total_time, apm=weighted_total_apm / total_time, adpm=weighted_total_adpm / total_time
|
||||
)
|
||||
lpm = weighted_total_lpm / total_time
|
||||
apm = weighted_total_apm / total_time
|
||||
adpm = weighted_total_adpm / total_time
|
||||
return GameData(game_num=num, metrics=metrics)
|
||||
|
||||
|
||||
async def make_query_text(player: Player) -> UniMessage:
|
||||
user_info, game_data = await gather(player.get_info(), get_game_data(player))
|
||||
user_data = user_info.data
|
||||
message = f'用户 {user_data.name} ({user_data.teaid}) '
|
||||
if user_data.ranked_games == '0':
|
||||
message += '暂无段位统计数据'
|
||||
else:
|
||||
message += f', 段位分 {round(float(user_data.rating_now),2)}±{round(float(user_data.rd_now),2)} ({round(float(user_data.vol_now),2)}) '
|
||||
if game_data is None:
|
||||
message += ', 暂无游戏数据'
|
||||
else:
|
||||
message += f', 最近 {game_data.game_num} 局数据'
|
||||
message += f"\nL'PM: {game_data.metrics.lpm} ( {game_data.metrics.pps} pps )"
|
||||
message += f'\nAPM: {game_data.metrics.apm} ( x{game_data.metrics.apl} )'
|
||||
message += f'\nADPM: {game_data.metrics.adpm} ( x{game_data.metrics.adpl} ) ( {game_data.metrics.vs}vs )'
|
||||
message += f'\n40L: {float(user_data.pb_sprint)/1000:.2f}s' if user_data.pb_sprint != '2147483647' else ''
|
||||
message += f'\nMarathon: {user_data.pb_marathon}' if user_data.pb_marathon != '0' else ''
|
||||
message += f'\nChallenge: {user_data.pb_challenge}' if user_data.pb_challenge != '0' else ''
|
||||
return UniMessage(message)
|
||||
55
nonebot_plugin_tetris_stats/games/__init__.py
Normal file
55
nonebot_plugin_tetris_stats/games/__init__.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.message import run_postprocessor
|
||||
from nonebot.typing import T_Handler
|
||||
from nonebot_plugin_alconna import AlcMatches, Alconna, At, CommandMeta, on_alconna
|
||||
|
||||
from .. import ns
|
||||
from ..utils.exception import MessageFormatError, NeedCatchError
|
||||
|
||||
command: Alconna = Alconna(
|
||||
['tetris-stats', 'tstats'],
|
||||
namespace=ns,
|
||||
meta=CommandMeta(
|
||||
description='俄罗斯方块相关游戏数据查询',
|
||||
fuzzy_match=True,
|
||||
),
|
||||
)
|
||||
|
||||
alc = on_alconna(
|
||||
command=command,
|
||||
skip_for_unmatch=False,
|
||||
auto_send_output=True,
|
||||
use_origin=True,
|
||||
)
|
||||
|
||||
|
||||
def add_block_handlers(handler: Callable[[T_Handler], T_Handler]) -> None:
|
||||
@handler
|
||||
async def _(bot: Bot, matcher: Matcher, target: At):
|
||||
if isinstance(target, At) and target.target == bot.self_id:
|
||||
await matcher.finish('不能查询bot的信息')
|
||||
|
||||
|
||||
from . import tetrio, top, tos # noqa: F401, E402
|
||||
|
||||
|
||||
@alc.handle()
|
||||
async def _(matcher: Matcher, account: MessageFormatError):
|
||||
await matcher.finish(str(account))
|
||||
|
||||
|
||||
@alc.handle()
|
||||
async def _(matcher: Matcher, matches: AlcMatches):
|
||||
if matches.head_matched and matches.options != {} or matches.main_args == {}:
|
||||
await matcher.finish(
|
||||
(f'{matches.error_info!r}\n' if matches.error_info is not None else '')
|
||||
+ f'输入"{matches.header_result} --help"查看帮助'
|
||||
)
|
||||
|
||||
|
||||
@run_postprocessor
|
||||
async def _(matcher: Matcher, exception: NeedCatchError):
|
||||
await matcher.send(str(exception))
|
||||
191
nonebot_plugin_tetris_stats/games/tetrio/__init__.py
Normal file
191
nonebot_plugin_tetris_stats/games/tetrio/__init__.py
Normal file
@@ -0,0 +1,191 @@
|
||||
from arclet.alconna import Arg, ArgFlag, Args, Option, Subcommand
|
||||
from nonebot_plugin_alconna import At
|
||||
|
||||
from ...utils.exception import MessageFormatError
|
||||
from ...utils.typing import Me
|
||||
|
||||
# from .. import add_block_handlers, alc, command
|
||||
from .. import alc, command
|
||||
from .api import Player
|
||||
|
||||
# from .api.typing import ValidRank
|
||||
from .constant import USER_ID, USER_NAME
|
||||
from .typing import Template
|
||||
|
||||
|
||||
def get_player(user_id_or_name: str) -> Player | MessageFormatError:
|
||||
if USER_ID.match(user_id_or_name):
|
||||
return Player(user_id=user_id_or_name, trust=True)
|
||||
if USER_NAME.match(user_id_or_name):
|
||||
return Player(user_name=user_id_or_name, trust=True)
|
||||
return MessageFormatError('用户名/ID不合法')
|
||||
|
||||
|
||||
command.add(
|
||||
Subcommand(
|
||||
'TETR.IO',
|
||||
Subcommand(
|
||||
'bind',
|
||||
Args(
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='TETR.IO 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN],
|
||||
)
|
||||
),
|
||||
help_text='绑定 TETR.IO 账号',
|
||||
),
|
||||
# Subcommand(
|
||||
# 'query',
|
||||
# Args(
|
||||
# Arg(
|
||||
# 'target',
|
||||
# At | Me,
|
||||
# notice='@想要查询的人 / 自己',
|
||||
# flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
# ),
|
||||
# Arg(
|
||||
# 'account',
|
||||
# get_player,
|
||||
# notice='TETR.IO 用户名 / ID',
|
||||
# flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
# ),
|
||||
# ),
|
||||
# Option(
|
||||
# '--template',
|
||||
# Arg('template', Template),
|
||||
# alias=['-T'],
|
||||
# help_text='要使用的查询模板',
|
||||
# ),
|
||||
# help_text='查询 TETR.IO 游戏信息',
|
||||
# ),
|
||||
Subcommand(
|
||||
'record',
|
||||
Option(
|
||||
'--40l',
|
||||
dest='sprint',
|
||||
),
|
||||
Option(
|
||||
'--blitz',
|
||||
dest='blitz',
|
||||
),
|
||||
Args(
|
||||
Arg(
|
||||
'target',
|
||||
At | Me,
|
||||
notice='@想要查询的人 / 自己',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='TETR.IO 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
),
|
||||
# Subcommand(
|
||||
# 'list',
|
||||
# Option('--max-tr', Arg('max_tr', float), help_text='TR的上限'),
|
||||
# Option('--min-tr', Arg('min_tr', float), help_text='TR的下限'),
|
||||
# Option('--limit', Arg('limit', int), help_text='查询数量'),
|
||||
# Option('--country', Arg('country', str), help_text='国家代码'),
|
||||
# help_text='查询 TETR.IO 段位排行榜',
|
||||
# ),
|
||||
# Subcommand(
|
||||
# 'rank',
|
||||
# Subcommand(
|
||||
# '--all',
|
||||
# Option(
|
||||
# '--template',
|
||||
# Arg('template', Template),
|
||||
# alias=['-T'],
|
||||
# help_text='要使用的查询模板',
|
||||
# ),
|
||||
# dest='all',
|
||||
# ),
|
||||
# Option(
|
||||
# '--detail',
|
||||
# Arg('rank', ValidRank),
|
||||
# alias=['-D'],
|
||||
# ),
|
||||
# help_text='查询 TETR.IO 段位信息',
|
||||
# ),
|
||||
Subcommand(
|
||||
'config',
|
||||
Option(
|
||||
'--default-template',
|
||||
Arg('template', Template),
|
||||
alias=['-DT', 'DefaultTemplate'],
|
||||
),
|
||||
),
|
||||
alias=['TETRIO', 'tetr.io', 'tetrio', 'io'],
|
||||
dest='TETRIO',
|
||||
help_text='TETR.IO 游戏相关指令',
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# def rank_wrapper(slot: int | str, content: str | None):
|
||||
# if slot == 'rank' and not content:
|
||||
# return '--all'
|
||||
# if content is not None:
|
||||
# return f'--detail {content.lower()}'
|
||||
# return content
|
||||
|
||||
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:绑定|绑|bind)',
|
||||
command='tstats TETR.IO bind',
|
||||
humanized='io绑定',
|
||||
)
|
||||
# alc.shortcut(
|
||||
# '(?i:io)(?i:查询|查|query|stats)',
|
||||
# command='tstats TETR.IO query',
|
||||
# humanized='io查',
|
||||
# )
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:记录|record)(?i:40l)',
|
||||
command='tstats TETR.IO record --40l',
|
||||
humanized='io记录40l',
|
||||
)
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:记录|record)(?i:blitz)',
|
||||
command='tstats TETR.IO record --blitz',
|
||||
humanized='io记录blitz',
|
||||
)
|
||||
# alc.shortcut(
|
||||
# r'(?i:io)(?i:段位|段|rank)\s*(?P<rank>[a-zA-Z+-]{0,2})',
|
||||
# command='tstats TETR.IO rank {rank}',
|
||||
# humanized='iorank',
|
||||
# fuzzy=False,
|
||||
# wrapper=rank_wrapper,
|
||||
# )
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:配置|配|config)',
|
||||
command='tstats TETR.IO config',
|
||||
humanized='io配置',
|
||||
)
|
||||
|
||||
# alc.shortcut(
|
||||
# 'fkosk',
|
||||
# command='tstats TETR.IO query',
|
||||
# arguments=['我'],
|
||||
# fuzzy=False,
|
||||
# humanized='An Easter egg!',
|
||||
# )
|
||||
|
||||
# add_block_handlers(alc.assign('TETRIO.query'))
|
||||
|
||||
# from . import bind, config, list, query, rank, record
|
||||
from . import bind, config, record # noqa: E402
|
||||
|
||||
__all__ = [
|
||||
'bind',
|
||||
'config',
|
||||
# 'list',
|
||||
# 'query',
|
||||
# 'rank',
|
||||
'record',
|
||||
]
|
||||
@@ -7,11 +7,12 @@ from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
from ....db.models import PydanticType
|
||||
from .schemas.base import SuccessModel
|
||||
from .typing import Summaries
|
||||
|
||||
|
||||
class TETRIOHistoricalData(MappedAsDataclass, Model):
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
user_unique_identifier: Mapped[str] = mapped_column(String(24), index=True)
|
||||
api_type: Mapped[Literal['User Info', 'User Records']] = mapped_column(String(16), index=True)
|
||||
api_type: Mapped[Literal['User Info', Summaries]] = mapped_column(String(16), index=True)
|
||||
data: Mapped[SuccessModel] = mapped_column(PydanticType(get_model=[SuccessModel.__subclasses__], models=set()))
|
||||
update_time: Mapped[datetime] = mapped_column(DateTime, index=True)
|
||||
187
nonebot_plugin_tetris_stats/games/tetrio/api/player.py
Normal file
187
nonebot_plugin_tetris_stats/games/tetrio/api/player.py
Normal file
@@ -0,0 +1,187 @@
|
||||
from types import MappingProxyType
|
||||
from typing import Literal, overload
|
||||
|
||||
from async_lru import alru_cache
|
||||
from nonebot.compat import type_validate_json
|
||||
|
||||
from ....db import anti_duplicate_add
|
||||
from ....utils.exception import RequestError
|
||||
from ....utils.request import splice_url
|
||||
from ..constant import BASE_URL, USER_ID, USER_NAME
|
||||
from .cache import Cache
|
||||
from .models import TETRIOHistoricalData
|
||||
from .schemas.base import FailedModel
|
||||
from .schemas.summaries import (
|
||||
AchievementsSuccessModel,
|
||||
SoloSuccessModel,
|
||||
SummariesModel,
|
||||
ZenithSuccessModel,
|
||||
ZenSuccessModel,
|
||||
)
|
||||
from .schemas.summaries.base import User as SummariesUser
|
||||
from .schemas.user import User
|
||||
from .schemas.user_info import UserInfo, UserInfoSuccess
|
||||
from .typing import Summaries
|
||||
|
||||
|
||||
class Player:
|
||||
__SUMMARIES_MAPPING: MappingProxyType[Summaries, type[SummariesModel]] = MappingProxyType(
|
||||
{
|
||||
'40l': SoloSuccessModel,
|
||||
'blitz': SoloSuccessModel,
|
||||
'zenith': ZenithSuccessModel,
|
||||
'zenithex': ZenithSuccessModel,
|
||||
'zen': ZenSuccessModel,
|
||||
'achievements': AchievementsSuccessModel,
|
||||
}
|
||||
)
|
||||
|
||||
@overload
|
||||
def __init__(self, *, user_id: str, trust: bool = False): ...
|
||||
@overload
|
||||
def __init__(self, *, user_name: str, trust: bool = False): ...
|
||||
def __init__(self, *, user_id: str | None = None, user_name: str | None = None, trust: bool = False):
|
||||
self.user_id = user_id
|
||||
self.user_name = user_name
|
||||
if not trust:
|
||||
if self.user_id is not None:
|
||||
if not USER_ID.match(self.user_id):
|
||||
msg = 'Invalid user id'
|
||||
raise ValueError(msg)
|
||||
elif self.user_name is not None:
|
||||
if not USER_NAME.match(self.user_name):
|
||||
msg = 'Invalid user name'
|
||||
raise ValueError(msg)
|
||||
else:
|
||||
msg = 'Invalid user'
|
||||
raise ValueError(msg)
|
||||
self.__user: User | None = None
|
||||
self._user_info: UserInfoSuccess | None = None
|
||||
self._summaries: dict[Summaries, SummariesModel] = {}
|
||||
|
||||
@property
|
||||
def _request_user_parameter(self) -> str:
|
||||
if self.user_id is not None:
|
||||
return self.user_id
|
||||
if self.user_name is not None:
|
||||
return self.user_name.lower()
|
||||
msg = 'Invalid user'
|
||||
raise ValueError(msg)
|
||||
|
||||
@property
|
||||
async def user(self) -> User:
|
||||
if self.__user is not None:
|
||||
return self.__user
|
||||
if (user := (await self._get_local_summaries_user())) is not None:
|
||||
self.__user = User(
|
||||
ID=user.id,
|
||||
name=user.username,
|
||||
)
|
||||
else:
|
||||
user_info = await self.get_info()
|
||||
self.__user = User(
|
||||
ID=user_info.data.id,
|
||||
name=user_info.data.username,
|
||||
)
|
||||
self.user_id = self.__user.ID
|
||||
self.user_name = self.__user.name
|
||||
return self.__user
|
||||
|
||||
async def get_info(self) -> UserInfoSuccess:
|
||||
"""Get User Info"""
|
||||
if self._user_info is None:
|
||||
raw_user_info = await Cache.get(splice_url([BASE_URL, 'users/', f'{self._request_user_parameter}']))
|
||||
user_info: UserInfo = type_validate_json(UserInfo, raw_user_info) # type: ignore[arg-type]
|
||||
if isinstance(user_info, FailedModel):
|
||||
msg = f'用户信息请求错误:\n{user_info.error}'
|
||||
raise RequestError(msg)
|
||||
self._user_info = user_info
|
||||
await anti_duplicate_add(
|
||||
TETRIOHistoricalData,
|
||||
TETRIOHistoricalData(
|
||||
user_unique_identifier=(await self.user).unique_identifier,
|
||||
api_type='User Info',
|
||||
data=user_info,
|
||||
update_time=user_info.cache.cached_at,
|
||||
),
|
||||
)
|
||||
return self._user_info
|
||||
|
||||
@overload
|
||||
async def get_summaries(self, summaries_type: Literal['40l', 'blitz']) -> SoloSuccessModel: ...
|
||||
@overload
|
||||
async def get_summaries(self, summaries_type: Literal['zenith', 'zenithex']) -> ZenithSuccessModel: ...
|
||||
@overload
|
||||
async def get_summaries(self, summaries_type: Literal['zen']) -> ZenSuccessModel: ...
|
||||
@overload
|
||||
async def get_summaries(self, summaries_type: Literal['achievements']) -> AchievementsSuccessModel: ...
|
||||
|
||||
async def get_summaries(self, summaries_type: Summaries) -> SummariesModel:
|
||||
if summaries_type not in self._summaries:
|
||||
raw_summaries = await Cache.get(
|
||||
splice_url([BASE_URL, 'users/', f'{self._request_user_parameter}/', 'summaries/', summaries_type])
|
||||
)
|
||||
summaries: SummariesModel | FailedModel = type_validate_json(
|
||||
self.__SUMMARIES_MAPPING[summaries_type] | FailedModel, # type: ignore[arg-type]
|
||||
raw_summaries,
|
||||
)
|
||||
if isinstance(summaries, FailedModel):
|
||||
msg = f'用户Summaries数据请求错误:\n{summaries.error}'
|
||||
raise RequestError(msg)
|
||||
self._summaries[summaries_type] = summaries
|
||||
await anti_duplicate_add(
|
||||
TETRIOHistoricalData,
|
||||
TETRIOHistoricalData(
|
||||
user_unique_identifier=(await self.user).unique_identifier,
|
||||
api_type=summaries_type,
|
||||
data=summaries,
|
||||
update_time=summaries.cache.cached_at,
|
||||
),
|
||||
)
|
||||
return self._summaries[summaries_type]
|
||||
|
||||
@property
|
||||
@alru_cache
|
||||
async def sprint(self) -> SoloSuccessModel:
|
||||
return await self.get_summaries('40l')
|
||||
|
||||
@property
|
||||
@alru_cache
|
||||
async def blitz(self) -> SoloSuccessModel:
|
||||
return await self.get_summaries('blitz')
|
||||
|
||||
@property
|
||||
@alru_cache
|
||||
async def zen(self) -> ZenSuccessModel:
|
||||
return await self.get_summaries('zen')
|
||||
|
||||
async def _get_local_summaries_user(self) -> SummariesUser | None:
|
||||
allow_summaries: set[Literal['40l', 'blitz', 'zenith', 'zenithex']] = {
|
||||
'40l',
|
||||
'blitz',
|
||||
'zenith',
|
||||
'zenithex',
|
||||
}
|
||||
if has_summaries := (allow_summaries & self._summaries.keys()):
|
||||
for i in has_summaries:
|
||||
if (record := (await self.get_summaries(i)).data.record) is not None:
|
||||
return record.user
|
||||
return None
|
||||
|
||||
@property
|
||||
@alru_cache
|
||||
async def avatar_revision(self) -> int | None:
|
||||
if self._user_info is not None:
|
||||
return self._user_info.data.avatar_revision
|
||||
if (user := (await self._get_local_summaries_user())) is not None:
|
||||
return user.avatar_revision
|
||||
return (await self.get_info()).data.avatar_revision
|
||||
|
||||
@property
|
||||
@alru_cache
|
||||
async def banner_revision(self) -> int | None:
|
||||
if self._user_info is not None:
|
||||
return self._user_info.data.banner_revision
|
||||
if (user := (await self._get_local_summaries_user())) is not None:
|
||||
return user.banner_revision
|
||||
return (await self.get_info()).data.banner_revision
|
||||
@@ -4,6 +4,12 @@ from typing import Literal
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class P(BaseModel): # what is P
|
||||
pri: float
|
||||
sec: float
|
||||
ter: float
|
||||
|
||||
|
||||
class Cache(BaseModel):
|
||||
status: str
|
||||
cached_at: datetime
|
||||
@@ -0,0 +1,27 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..base import SuccessModel
|
||||
from .base import Entry as BaseEntry
|
||||
|
||||
|
||||
class ArCounts(BaseModel):
|
||||
bronze: int | None = Field(None, alias='1')
|
||||
silver: int | None = Field(None, alias='2')
|
||||
gold: int | None = Field(None, alias='3')
|
||||
platinum: int | None = Field(None, alias='4')
|
||||
diamond: int | None = Field(None, alias='5')
|
||||
issued: int | None = Field(None, alias='100')
|
||||
top10: int | None = Field(None, alias='t10')
|
||||
|
||||
|
||||
class Entry(BaseEntry):
|
||||
ar: int
|
||||
ar_counts: ArCounts
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
entries: list[Entry]
|
||||
|
||||
|
||||
class ArSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
@@ -0,0 +1,30 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Rank
|
||||
from ..base import P
|
||||
|
||||
|
||||
class League(BaseModel):
|
||||
gamesplayed: int
|
||||
gameswon: int
|
||||
rating: int
|
||||
rank: Rank
|
||||
decaying: bool
|
||||
|
||||
|
||||
class Entry(BaseModel):
|
||||
id: str = Field(..., alias='_id')
|
||||
username: str
|
||||
role: str
|
||||
xp: float
|
||||
league: League
|
||||
supporter: bool | None = None
|
||||
verified: bool
|
||||
country: str | None = None
|
||||
ts: datetime
|
||||
gamesplayed: int
|
||||
gameswon: int
|
||||
gametime: float
|
||||
p: P
|
||||
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..base import SuccessModel
|
||||
from ..summaries.solo import Record
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
entries: list[Record]
|
||||
|
||||
|
||||
class SoloSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..base import SuccessModel
|
||||
from .base import Entry
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
entries: list[Entry]
|
||||
|
||||
|
||||
class XpSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..base import SuccessModel
|
||||
from ..summaries.zenith import Record
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
entries: list[Record]
|
||||
|
||||
|
||||
class ZenithSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
@@ -0,0 +1,20 @@
|
||||
from .achievements import Achievements, AchievementsSuccessModel
|
||||
from .solo import Blitz, SoloSuccessModel, Sprint
|
||||
from .zen import Zen, ZenSuccessModel
|
||||
from .zenith import Zenith, ZenithEx, ZenithSuccessModel
|
||||
|
||||
SummariesModel = AchievementsSuccessModel | SoloSuccessModel | ZenSuccessModel | ZenithSuccessModel
|
||||
|
||||
__all__ = [
|
||||
'Achievements',
|
||||
'AchievementsSuccessModel',
|
||||
'Blitz',
|
||||
'Sprint',
|
||||
'SoloSuccessModel',
|
||||
'Zen',
|
||||
'ZenSuccessModel',
|
||||
'Zenith',
|
||||
'ZenithEx',
|
||||
'ZenithSuccessModel',
|
||||
'SummariesModel',
|
||||
]
|
||||
@@ -0,0 +1,29 @@
|
||||
from typing import TypeAlias
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..base import FailedModel, SuccessModel
|
||||
|
||||
|
||||
class Achievement(BaseModel):
|
||||
# 这**都是些啥
|
||||
k: int
|
||||
o: int
|
||||
rt: int
|
||||
vt: int
|
||||
min: int
|
||||
deci: int
|
||||
name: str
|
||||
object: str
|
||||
category: str
|
||||
hidden: bool
|
||||
desc: str
|
||||
n: str
|
||||
stub: bool
|
||||
|
||||
|
||||
class AchievementsSuccessModel(SuccessModel):
|
||||
data: list[Achievement]
|
||||
|
||||
|
||||
Achievements: TypeAlias = AchievementsSuccessModel | FailedModel
|
||||
@@ -0,0 +1,23 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
avatar_revision: int | None
|
||||
banner_revision: int | None
|
||||
country: str | None
|
||||
verified: int
|
||||
supporter: int
|
||||
|
||||
|
||||
class AggregateStats(BaseModel):
|
||||
apm: float
|
||||
pps: float
|
||||
vsscore: float
|
||||
|
||||
|
||||
class Finesse(BaseModel):
|
||||
combo: int
|
||||
faults: int
|
||||
perfectpieces: int
|
||||
@@ -0,0 +1,103 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..base import FailedModel, P, SuccessModel
|
||||
from .base import AggregateStats, Finesse, User
|
||||
|
||||
|
||||
class Time(BaseModel):
|
||||
start: int
|
||||
zero: bool
|
||||
locked: bool
|
||||
prev: int
|
||||
frameoffset: int
|
||||
|
||||
|
||||
class Clears(BaseModel):
|
||||
singles: int
|
||||
doubles: int
|
||||
triples: int
|
||||
quads: int
|
||||
realtspins: int
|
||||
minitspins: int
|
||||
minitspinsingles: int
|
||||
tspinsingles: int
|
||||
minitspindoubles: int
|
||||
tspindoubles: int
|
||||
tspintriples: int
|
||||
tspinquads: int
|
||||
allclear: int
|
||||
|
||||
|
||||
class Garbage(BaseModel):
|
||||
sent: int
|
||||
received: int
|
||||
attack: int | None
|
||||
cleared: int
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
seed: int
|
||||
lines: int
|
||||
level_lines: int
|
||||
level_lines_needed: int
|
||||
inputs: int
|
||||
holds: int
|
||||
time: Time
|
||||
score: int
|
||||
zenlevel: int
|
||||
zenprogress: int
|
||||
level: int
|
||||
combo: int
|
||||
currentcombopower: int | None = None
|
||||
topcombo: int
|
||||
btb: int
|
||||
topbtb: int
|
||||
currentbtbchainpower: int | None = None
|
||||
tspins: int
|
||||
piecesplaced: int
|
||||
clears: Clears
|
||||
garbage: Garbage
|
||||
kills: int
|
||||
finesse: Finesse
|
||||
finaltime: float
|
||||
|
||||
|
||||
class Results(BaseModel):
|
||||
aggregatestats: AggregateStats
|
||||
stats: Stats
|
||||
gameoverreason: str
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
id: str = Field(..., alias='_id')
|
||||
replayid: str
|
||||
stub: bool
|
||||
gamemode: Literal['40l', 'blitz']
|
||||
pb: bool
|
||||
oncepb: bool
|
||||
ts: datetime
|
||||
revolution: None
|
||||
user: User
|
||||
otherusers: list
|
||||
leaderboards: list[str]
|
||||
results: Results
|
||||
extras: dict
|
||||
disputed: bool
|
||||
p: P
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
record: Record | None
|
||||
rank: int
|
||||
rank_local: int
|
||||
|
||||
|
||||
class SoloSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
|
||||
|
||||
Sprint: TypeAlias = SoloSuccessModel | FailedModel
|
||||
Blitz: TypeAlias = SoloSuccessModel | FailedModel
|
||||
@@ -0,0 +1,17 @@
|
||||
from typing import TypeAlias
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..base import FailedModel, SuccessModel
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
level: int
|
||||
score: int
|
||||
|
||||
|
||||
class ZenSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
|
||||
|
||||
Zen: TypeAlias = ZenSuccessModel | FailedModel
|
||||
@@ -0,0 +1,131 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..base import FailedModel, P, SuccessModel
|
||||
from .base import AggregateStats, Finesse, User
|
||||
|
||||
|
||||
class Clears(BaseModel):
|
||||
singles: int
|
||||
doubles: int
|
||||
triples: int
|
||||
quads: int
|
||||
pentas: int
|
||||
realtspins: int
|
||||
minitspins: int
|
||||
minitspinsingles: int
|
||||
tspinsingles: int
|
||||
minitspindoubles: int
|
||||
tspindoubles: int
|
||||
minitspintriples: int
|
||||
tspintriples: int
|
||||
minitspinquads: int
|
||||
tspinquads: int
|
||||
tspinpentas: int
|
||||
allclear: int
|
||||
|
||||
|
||||
class Garbage(BaseModel):
|
||||
sent: int
|
||||
sent_nomult: int
|
||||
maxspike: int
|
||||
maxspike_nomult: int
|
||||
received: int
|
||||
attack: int
|
||||
cleared: int
|
||||
|
||||
|
||||
class _Zenith(BaseModel):
|
||||
altitude: float
|
||||
rank: float
|
||||
peakrank: float
|
||||
avgrankpts: float
|
||||
floor: int
|
||||
targetingfactor: float
|
||||
targetinggrace: float
|
||||
totalbonus: float
|
||||
revives: int
|
||||
revives_total: int = Field(..., alias='revivesTotal')
|
||||
speedrun: bool
|
||||
speedrun_seen: bool
|
||||
splits: list[int]
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
lines: int
|
||||
level_lines: int
|
||||
level_lines_needed: int
|
||||
inputs: int
|
||||
holds: int
|
||||
score: int
|
||||
zenlevel: int
|
||||
zenprogress: int
|
||||
level: int
|
||||
combo: int
|
||||
topcombo: int
|
||||
combopower: int
|
||||
btb: int
|
||||
topbtb: int
|
||||
btbpower: int
|
||||
tspins: int
|
||||
piecesplaced: int
|
||||
clears: Clears
|
||||
garbage: Garbage
|
||||
kills: int
|
||||
finesse: Finesse
|
||||
zenith: _Zenith
|
||||
finaltime: float
|
||||
|
||||
|
||||
class Results(BaseModel):
|
||||
aggregatestats: AggregateStats
|
||||
stats: Stats
|
||||
gameoverreason: str
|
||||
|
||||
|
||||
class ExtrasZenith(BaseModel):
|
||||
mods: list[str]
|
||||
|
||||
|
||||
class Extras(BaseModel):
|
||||
zenith: ExtrasZenith
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
id: str = Field(..., alias='_id')
|
||||
replayid: str
|
||||
stub: bool
|
||||
gamemode: Literal['zenith', 'zenithex']
|
||||
pb: bool
|
||||
oncepb: bool
|
||||
ts: datetime
|
||||
revolution: None
|
||||
user: User
|
||||
otherusers: list
|
||||
leaderboards: list[str]
|
||||
results: Results
|
||||
extras: Extras
|
||||
disputed: bool
|
||||
p: P
|
||||
|
||||
|
||||
class Best(BaseModel):
|
||||
record: None # WTF
|
||||
rank: int
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
record: Record | None
|
||||
rank: int
|
||||
rank_local: int
|
||||
best: Best
|
||||
|
||||
|
||||
class ZenithSuccessModel(SuccessModel):
|
||||
data: Data
|
||||
|
||||
|
||||
Zenith: TypeAlias = ZenithSuccessModel | FailedModel
|
||||
ZenithEx: TypeAlias = ZenithSuccessModel | FailedModel
|
||||
@@ -10,7 +10,7 @@ class _User(BaseModel):
|
||||
username: str
|
||||
role: str
|
||||
xp: float
|
||||
supporter: bool
|
||||
supporter: bool | None = None
|
||||
verified: bool
|
||||
country: str | None = None
|
||||
|
||||
@@ -3,7 +3,6 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..typing import Rank
|
||||
from .base import FailedModel
|
||||
from .base import SuccessModel as BaseSuccessModel
|
||||
|
||||
@@ -15,67 +14,6 @@ class Badge(BaseModel):
|
||||
ts: datetime | Literal[False] | None = None
|
||||
|
||||
|
||||
class MetaLeague(BaseModel):
|
||||
decaying: bool
|
||||
|
||||
|
||||
class NeverPlayedLeague(MetaLeague):
|
||||
gamesplayed: Literal[0]
|
||||
gameswon: Literal[0]
|
||||
rating: Literal[-1]
|
||||
rank: Literal['z']
|
||||
standing: Literal[-1]
|
||||
standing_local: Literal[-1]
|
||||
next_rank: None
|
||||
prev_rank: None
|
||||
next_at: Literal[-1]
|
||||
prev_at: Literal[-1]
|
||||
percentile: Literal[-1]
|
||||
percentile_rank: Literal['z']
|
||||
apm: None = None
|
||||
pps: None = None
|
||||
vs: None = None
|
||||
|
||||
|
||||
class NeverRatedLeague(MetaLeague):
|
||||
gamesplayed: Literal[1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
gameswon: int
|
||||
rating: Literal[-1]
|
||||
rank: Literal['z']
|
||||
standing: Literal[-1]
|
||||
standing_local: Literal[-1]
|
||||
next_rank: None
|
||||
prev_rank: None
|
||||
next_at: Literal[-1]
|
||||
prev_at: Literal[-1]
|
||||
percentile: Literal[-1]
|
||||
percentile_rank: Literal['z']
|
||||
apm: float
|
||||
pps: float
|
||||
vs: float | None = None
|
||||
|
||||
|
||||
class RatedLeague(MetaLeague):
|
||||
gamesplayed: int
|
||||
gameswon: int
|
||||
rating: float
|
||||
rank: Rank
|
||||
bestrank: Rank
|
||||
standing: int
|
||||
standing_local: int
|
||||
next_rank: Rank | None = None
|
||||
prev_rank: Rank | None = None
|
||||
next_at: int
|
||||
prev_at: int
|
||||
percentile: float
|
||||
percentile_rank: str
|
||||
glicko: float
|
||||
rd: float
|
||||
apm: float
|
||||
pps: float
|
||||
vs: float | None = None
|
||||
|
||||
|
||||
class Discord(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
@@ -89,7 +27,7 @@ class Distinguishment(BaseModel):
|
||||
type: str
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
class Data(BaseModel):
|
||||
id: str = Field(..., alias='_id')
|
||||
username: str
|
||||
role: Literal['anon', 'user', 'bot', 'halfmod', 'mod', 'admin', 'sysop', 'banned']
|
||||
@@ -105,7 +43,6 @@ class User(BaseModel):
|
||||
supporter: bool | None = None # osk说是必有, 但实际上不是 fkosk
|
||||
supporter_tier: int
|
||||
verified: bool
|
||||
league: NeverPlayedLeague | NeverRatedLeague | RatedLeague
|
||||
avatar_revision: int | None = None
|
||||
"""This user's avatar ID. Get their avatar at
|
||||
|
||||
@@ -122,10 +59,6 @@ class User(BaseModel):
|
||||
distinguishment: Distinguishment | None = None
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
user: User
|
||||
|
||||
|
||||
class UserInfoSuccess(BaseSuccessModel):
|
||||
data: Data
|
||||
|
||||
@@ -36,7 +36,7 @@ class Garbage(BaseModel):
|
||||
sent: int
|
||||
received: int
|
||||
attack: int | None = None
|
||||
cleared: int
|
||||
cleared: int | None = None
|
||||
|
||||
|
||||
class Finesse(BaseModel):
|
||||
@@ -96,7 +96,7 @@ class MultiRecord(_Record):
|
||||
|
||||
|
||||
class SoloModeRecord(BaseModel):
|
||||
record: SoloRecord
|
||||
record: SoloRecord | None = None
|
||||
rank: int | None = None
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from typing import Literal, NamedTuple, overload
|
||||
from typing import Literal, NamedTuple, TypedDict, overload
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from nonebot.compat import type_validate_json
|
||||
|
||||
@@ -10,6 +11,24 @@ from .schemas.base import FailedModel
|
||||
from .schemas.tetra_league import TetraLeague, TetraLeagueSuccess
|
||||
|
||||
|
||||
class Parameter(TypedDict, total=False):
|
||||
after: float
|
||||
before: float
|
||||
limit: int
|
||||
country: str
|
||||
|
||||
|
||||
async def leaderboard(parameter: Parameter | None = None) -> TetraLeagueSuccess:
|
||||
league: TetraLeague = type_validate_json(
|
||||
TetraLeague, # type: ignore[arg-type]
|
||||
(await Cache.get(splice_url([BASE_URL, 'users/lists/league', f'?{urlencode(parameter or {})}']))),
|
||||
)
|
||||
if isinstance(league, FailedModel):
|
||||
msg = f'排行榜数据请求错误:\n{league.error}'
|
||||
raise RequestError(msg)
|
||||
return league
|
||||
|
||||
|
||||
class FullExport(NamedTuple):
|
||||
model: TetraLeagueSuccess
|
||||
original: bytes
|
||||
33
nonebot_plugin_tetris_stats/games/tetrio/api/typing.py
Normal file
33
nonebot_plugin_tetris_stats/games/tetrio/api/typing.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from typing import Literal
|
||||
|
||||
ValidRank = Literal[
|
||||
'x',
|
||||
'u',
|
||||
'ss',
|
||||
's+',
|
||||
's',
|
||||
's-',
|
||||
'a+',
|
||||
'a',
|
||||
'a-',
|
||||
'b+',
|
||||
'b',
|
||||
'b-',
|
||||
'c+',
|
||||
'c',
|
||||
'c-',
|
||||
'd+',
|
||||
'd',
|
||||
]
|
||||
|
||||
Rank = ValidRank | Literal['z'] # 未定级
|
||||
|
||||
Summaries = Literal[
|
||||
'40l',
|
||||
'blitz',
|
||||
'zenith',
|
||||
'zenithex',
|
||||
# 'league', # 等待正式赛季开始
|
||||
'zen',
|
||||
'achievements',
|
||||
]
|
||||
@@ -1,17 +1,17 @@
|
||||
from asyncio import gather
|
||||
from hashlib import md5
|
||||
from urllib.parse import urlunparse
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import User # type: ignore[import-untyped]
|
||||
from nonebot_plugin_userinfo import BotUserInfo, UserInfo # type: ignore[import-untyped]
|
||||
|
||||
from ...db import BindStatus, create_or_update_bind, trigger
|
||||
from ...utils.avatar import get_avatar
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.platform import get_platform
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import Avatar, People
|
||||
from ...utils.screenshot import screenshot
|
||||
@@ -20,36 +20,35 @@ from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('bind')
|
||||
async def _(bot: Bot, event: Event, account: Player, event_session: EventSession, bot_info: UserInfo = BotUserInfo()): # noqa: B008
|
||||
@alc.assign('TETRIO.bind')
|
||||
async def _(nb_user: User, account: Player, event_session: EventSession, bot_info: UserInfo = BotUserInfo()): # noqa: B008
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='bind',
|
||||
command_args=[],
|
||||
):
|
||||
user = await account.user
|
||||
user, user_info = await gather(account.user, account.get_info())
|
||||
async with get_session() as session:
|
||||
bind_status = await create_or_update_bind(
|
||||
session=session,
|
||||
chat_platform=get_platform(bot),
|
||||
chat_account=event.get_user_id(),
|
||||
user=nb_user,
|
||||
game_platform=GAME_TYPE,
|
||||
game_account=user.unique_identifier,
|
||||
)
|
||||
user_info = await account.get_info()
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
await render(
|
||||
'binding',
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
status='unknown',
|
||||
user=People(
|
||||
avatar=f'https://tetr.io/user-content/avatars/{user_info.data.user.id}.jpg?rv={user_info.data.user.avatar_revision}'
|
||||
if user_info.data.user.avatar_revision is not None
|
||||
else Avatar(type='identicon', hash=md5(user_info.data.user.id.encode()).hexdigest()), # noqa: S324
|
||||
name=user_info.data.user.username.upper(),
|
||||
avatar=f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}?{urlencode({"revision": avatar_revision})}'
|
||||
if (avatar_revision := (await account.avatar_revision)) is not None and avatar_revision != 0
|
||||
else Avatar(type='identicon', hash=md5(user.ID.encode()).hexdigest()), # noqa: S324
|
||||
name=user.name.upper(),
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(bot_info, 'Data URI', '../../static/logo/logo.svg'),
|
||||
@@ -59,6 +58,4 @@ async def _(bot: Bot, event: Event, account: Player, event_session: EventSession
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(
|
||||
raw=await screenshot(urlunparse(('http', get_self_netloc(), f'/host/{page_hash}.html', '', '', '')))
|
||||
).finish()
|
||||
await UniMessage.image(raw=await screenshot(f'http://{netloc}/host/{page_hash}.html')).finish()
|
||||
30
nonebot_plugin_tetris_stats/games/tetrio/config.py
Normal file
30
nonebot_plugin_tetris_stats/games/tetrio/config.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import async_scoped_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import User # type: ignore[import-untyped]
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...db import trigger
|
||||
from . import alc
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TETRIOUserConfig
|
||||
from .typing import Template
|
||||
|
||||
|
||||
@alc.assign('TETRIO.config')
|
||||
async def _(user: User, session: async_scoped_session, event_session: EventSession, template: Template):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='config',
|
||||
command_args=[f'--default-template {template}'],
|
||||
):
|
||||
config = (await session.scalars(select(TETRIOUserConfig).where(TETRIOUserConfig.id == user.id))).one_or_none()
|
||||
if config is None:
|
||||
config = TETRIOUserConfig(id=user.id, query_template=template)
|
||||
session.add(config)
|
||||
else:
|
||||
config.query_template = template
|
||||
await session.commit()
|
||||
await UniMessage('配置成功').finish()
|
||||
@@ -1,13 +1,13 @@
|
||||
from re import compile
|
||||
from typing import Literal
|
||||
|
||||
from .api.typing import Rank
|
||||
from .api.typing import ValidRank
|
||||
|
||||
GAME_TYPE: Literal['IO'] = 'IO'
|
||||
|
||||
BASE_URL = 'https://ch.tetr.io/api/'
|
||||
|
||||
RANK_PERCENTILE: dict[Rank, float] = {
|
||||
RANK_PERCENTILE: dict[ValidRank, float] = {
|
||||
'x': 1,
|
||||
'u': 5,
|
||||
'ss': 11,
|
||||
10
nonebot_plugin_tetris_stats/games/tetrio/models.py
Normal file
10
nonebot_plugin_tetris_stats/games/tetrio/models.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from nonebot_plugin_orm import Model
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
from .typing import Template
|
||||
|
||||
|
||||
class TETRIOUserConfig(MappedAsDataclass, Model):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
query_template: Mapped[Template] = mapped_column(String(2))
|
||||
@@ -0,0 +1,6 @@
|
||||
from . import blitz, sprint
|
||||
|
||||
__all__ = [
|
||||
'blitz',
|
||||
'sprint',
|
||||
]
|
||||
139
nonebot_plugin_tetris_stats/games/tetrio/record/blitz.py
Normal file
139
nonebot_plugin_tetris_stats/games/tetrio/record/blitz.py
Normal file
@@ -0,0 +1,139 @@
|
||||
from asyncio import gather
|
||||
from datetime import timedelta
|
||||
from hashlib import md5
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from nonebot.adapters import Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import get_user # type: ignore[import-untyped]
|
||||
|
||||
from ....db import query_bind_info, trigger
|
||||
from ....utils.exception import RecordNotFoundError
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.base import Avatar
|
||||
from ....utils.render.schemas.tetrio.tetrio_record_base import Finesse, Max, Mini, Tspins, User
|
||||
from ....utils.render.schemas.tetrio.tetrio_record_blitz import Record, Statistic
|
||||
from ....utils.screenshot import screenshot
|
||||
from ....utils.typing import Me
|
||||
from ...constant import CANT_VERIFY_MESSAGE
|
||||
from .. import alc
|
||||
from ..api.player import Player
|
||||
from ..constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('TETRIO.record.blitz')
|
||||
async def _(
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='record',
|
||||
command_args=['--blitz'],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=await get_user(
|
||||
event_session.platform, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = UniMessage(CANT_VERIFY_MESSAGE)
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
await (message + UniMessage.image(raw=await make_blitz_image(player))).finish()
|
||||
|
||||
|
||||
@alc.assign('TETRIO.record.blitz')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='record',
|
||||
command_args=['--blitz'],
|
||||
):
|
||||
await UniMessage.image(raw=await make_blitz_image(account)).finish()
|
||||
|
||||
|
||||
async def make_blitz_image(player: Player) -> bytes:
|
||||
user, blitz = await gather(player.user, player.blitz)
|
||||
if blitz.data.record is None:
|
||||
msg = f'未找到用户 {user.name.upper()} 的 Blitz 记录'
|
||||
raise RecordNotFoundError(msg)
|
||||
stats = blitz.data.record.results.stats
|
||||
clears = stats.clears
|
||||
duration = timedelta(milliseconds=stats.finaltime).total_seconds()
|
||||
metrics = get_metrics(pps=stats.piecesplaced / duration)
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
page=await render(
|
||||
'v2/tetrio/record/blitz',
|
||||
Record(
|
||||
type='personal_best',
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
avatar=f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}?{urlencode({"revision": avatar_revision})}'
|
||||
if (avatar_revision := (await player.avatar_revision)) is not None and avatar_revision != 0
|
||||
else Avatar(
|
||||
type='identicon',
|
||||
hash=md5(user.ID.encode()).hexdigest(), # noqa: S324
|
||||
),
|
||||
),
|
||||
replay_id=blitz.data.record.replayid,
|
||||
rank=blitz.data.rank,
|
||||
personal_rank=1,
|
||||
statistic=Statistic(
|
||||
keys=stats.inputs,
|
||||
kpp=round(stats.inputs / stats.piecesplaced, 2),
|
||||
kps=round(stats.inputs / duration, 2),
|
||||
max=Max(
|
||||
combo=max((0, stats.topcombo - 1)),
|
||||
btb=max((0, stats.topbtb - 1)),
|
||||
),
|
||||
pieces=stats.piecesplaced,
|
||||
pps=metrics.pps,
|
||||
lines=stats.lines,
|
||||
lpm=metrics.lpm,
|
||||
holds=stats.holds,
|
||||
score=stats.score,
|
||||
spp=round(stats.score / stats.piecesplaced, 2),
|
||||
single=clears.singles,
|
||||
double=clears.doubles,
|
||||
triple=clears.triples,
|
||||
quad=clears.quads,
|
||||
tspins=Tspins(
|
||||
total=clears.realtspins,
|
||||
single=clears.tspinsingles,
|
||||
double=clears.tspindoubles,
|
||||
triple=clears.tspintriples,
|
||||
mini=Mini(
|
||||
total=clears.minitspins,
|
||||
single=clears.minitspinsingles,
|
||||
double=clears.minitspindoubles,
|
||||
),
|
||||
),
|
||||
all_clear=clears.allclear,
|
||||
finesse=Finesse(
|
||||
faults=stats.finesse.faults,
|
||||
accuracy=round(stats.finesse.perfectpieces / stats.piecesplaced * 100, 2),
|
||||
),
|
||||
level=stats.level,
|
||||
),
|
||||
play_at=blitz.data.record.ts,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{netloc}/host/{page_hash}.html')
|
||||
139
nonebot_plugin_tetris_stats/games/tetrio/record/sprint.py
Normal file
139
nonebot_plugin_tetris_stats/games/tetrio/record/sprint.py
Normal file
@@ -0,0 +1,139 @@
|
||||
from asyncio import gather
|
||||
from datetime import timedelta
|
||||
from hashlib import md5
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from nonebot.adapters import Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import get_user # type: ignore[import-untyped]
|
||||
|
||||
from ....db import query_bind_info, trigger
|
||||
from ....utils.exception import RecordNotFoundError
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.base import Avatar
|
||||
from ....utils.render.schemas.tetrio.tetrio_record_base import Finesse, Max, Mini, Statistic, Tspins, User
|
||||
from ....utils.render.schemas.tetrio.tetrio_record_sprint import Record
|
||||
from ....utils.screenshot import screenshot
|
||||
from ....utils.typing import Me
|
||||
from ...constant import CANT_VERIFY_MESSAGE
|
||||
from .. import alc
|
||||
from ..api.player import Player
|
||||
from ..constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('TETRIO.record.sprint')
|
||||
async def _(
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='record',
|
||||
command_args=['--40l'],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=await get_user(
|
||||
event_session.platform, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = UniMessage(CANT_VERIFY_MESSAGE)
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
await (message + UniMessage.image(raw=await make_sprint_image(player))).finish()
|
||||
|
||||
|
||||
@alc.assign('TETRIO.record.sprint')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='record',
|
||||
command_args=['--40l'],
|
||||
):
|
||||
await UniMessage.image(raw=await make_sprint_image(account)).finish()
|
||||
|
||||
|
||||
async def make_sprint_image(player: Player) -> bytes:
|
||||
user, sprint = await gather(player.user, player.sprint)
|
||||
if sprint.data.record is None:
|
||||
msg = f'未找到用户 {user.name.upper()} 的 40L 记录'
|
||||
raise RecordNotFoundError(msg)
|
||||
stats = sprint.data.record.results.stats
|
||||
clears = stats.clears
|
||||
duration = timedelta(milliseconds=stats.finaltime).total_seconds()
|
||||
sprint_value = f'{duration:.3f}s' if duration < 60 else f'{duration // 60:.0f}m {duration % 60:.3f}s' # noqa: PLR2004
|
||||
metrics = get_metrics(pps=stats.piecesplaced / duration)
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
page=await render(
|
||||
'v2/tetrio/record/40l',
|
||||
Record(
|
||||
type='personal_best',
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
avatar=f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}?{urlencode({"revision": avatar_revision})}'
|
||||
if (avatar_revision := (await player.avatar_revision)) is not None and avatar_revision != 0
|
||||
else Avatar(
|
||||
type='identicon',
|
||||
hash=md5(user.ID.encode()).hexdigest(), # noqa: S324
|
||||
),
|
||||
),
|
||||
time=sprint_value,
|
||||
replay_id=sprint.data.record.replayid,
|
||||
rank=sprint.data.rank,
|
||||
personal_rank=1,
|
||||
statistic=Statistic(
|
||||
keys=stats.inputs,
|
||||
kpp=round(stats.inputs / stats.piecesplaced, 2),
|
||||
kps=round(stats.inputs / duration, 2),
|
||||
max=Max(
|
||||
combo=max((0, stats.topcombo - 1)),
|
||||
btb=max((0, stats.topbtb - 1)),
|
||||
),
|
||||
pieces=stats.piecesplaced,
|
||||
pps=metrics.pps,
|
||||
lines=stats.lines,
|
||||
lpm=metrics.lpm,
|
||||
holds=stats.holds,
|
||||
score=stats.score,
|
||||
single=clears.singles,
|
||||
double=clears.doubles,
|
||||
triple=clears.triples,
|
||||
quad=clears.quads,
|
||||
tspins=Tspins(
|
||||
total=clears.realtspins,
|
||||
single=clears.tspinsingles,
|
||||
double=clears.tspindoubles,
|
||||
triple=clears.tspintriples,
|
||||
mini=Mini(
|
||||
total=clears.minitspins,
|
||||
single=clears.minitspinsingles,
|
||||
double=clears.minitspindoubles,
|
||||
),
|
||||
),
|
||||
all_clear=clears.allclear,
|
||||
finesse=Finesse(
|
||||
faults=stats.finesse.faults,
|
||||
accuracy=round(stats.finesse.perfectpieces / stats.piecesplaced * 100, 2),
|
||||
),
|
||||
),
|
||||
play_at=sprint.data.record.ts,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{netloc}/host/{page_hash}.html')
|
||||
3
nonebot_plugin_tetris_stats/games/tetrio/typing.py
Normal file
3
nonebot_plugin_tetris_stats/games/tetrio/typing.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from typing import Literal
|
||||
|
||||
Template = Literal['v1', 'v2']
|
||||
@@ -1,10 +1,9 @@
|
||||
from arclet.alconna import Alconna, AllParam, Arg, ArgFlag, Args, CommandMeta, Option
|
||||
from nonebot_plugin_alconna import At, on_alconna
|
||||
from arclet.alconna import Arg, ArgFlag, Args, Subcommand
|
||||
from nonebot_plugin_alconna import At
|
||||
|
||||
from ...utils.exception import MessageFormatError
|
||||
from ...utils.typing import Me
|
||||
from .. import add_default_handlers
|
||||
from ..constant import BIND_COMMAND, QUERY_COMMAND
|
||||
from .. import add_block_handlers, alc, command
|
||||
from .api import Player
|
||||
from .constant import USER_NAME
|
||||
|
||||
@@ -15,31 +14,28 @@ def get_player(name: str) -> Player | MessageFormatError:
|
||||
return MessageFormatError('用户名/ID不合法')
|
||||
|
||||
|
||||
alc = on_alconna(
|
||||
Alconna(
|
||||
'top',
|
||||
Option(
|
||||
BIND_COMMAND[0],
|
||||
command.add(
|
||||
Subcommand(
|
||||
'TOP',
|
||||
Subcommand(
|
||||
'bind',
|
||||
Args(
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='TOP 用户名',
|
||||
notice='TOP 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN],
|
||||
)
|
||||
),
|
||||
alias=BIND_COMMAND[1:],
|
||||
compact=True,
|
||||
dest='bind',
|
||||
help_text='绑定 TOP 账号',
|
||||
),
|
||||
Option(
|
||||
QUERY_COMMAND[0],
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
Arg(
|
||||
'target',
|
||||
At | Me,
|
||||
notice='@想要查询的人 | 自己',
|
||||
notice='@想要查询的人 / 自己',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
Arg(
|
||||
@@ -49,24 +45,15 @@ alc = on_alconna(
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
alias=QUERY_COMMAND[1:],
|
||||
compact=True,
|
||||
dest='query',
|
||||
help_text='查询 TOP 游戏信息',
|
||||
),
|
||||
Arg('other', AllParam, flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL]),
|
||||
meta=CommandMeta(
|
||||
description='查询 TetrisOnline波兰服 的信息',
|
||||
example='top绑定scdhh\ntop查我',
|
||||
compact=True,
|
||||
fuzzy_match=True,
|
||||
),
|
||||
),
|
||||
skip_for_unmatch=False,
|
||||
auto_send_output=True,
|
||||
aliases={'TOP'},
|
||||
help_text='TOP 游戏相关指令',
|
||||
)
|
||||
)
|
||||
|
||||
from . import bind, query # noqa: E402, F401
|
||||
alc.shortcut('(?i:top)(?i:绑定|绑|bind)', {'command': 'tstats TOP bind', 'humanized': 'top绑定'})
|
||||
alc.shortcut('(?i:top)(?i:查询|查|query|stats)', {'command': 'tstats TOP query', 'humanized': 'top查'})
|
||||
|
||||
add_default_handlers(alc)
|
||||
add_block_handlers(alc.assign('TOP.query'))
|
||||
|
||||
from . import bind, query # noqa: E402, F401
|
||||
@@ -1,16 +1,13 @@
|
||||
from urllib.parse import urlunparse
|
||||
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import User # type: ignore[import-untyped]
|
||||
from nonebot_plugin_userinfo import BotUserInfo, EventUserInfo, UserInfo # type: ignore[import-untyped]
|
||||
|
||||
from ...db import BindStatus, create_or_update_bind, trigger
|
||||
from ...utils.avatar import get_avatar
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.platform import get_platform
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
@@ -19,13 +16,13 @@ from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('bind')
|
||||
@alc.assign('TOP.bind')
|
||||
async def _(
|
||||
bot: Bot,
|
||||
nb_user: User,
|
||||
account: Player,
|
||||
event_session: EventSession,
|
||||
bot_info: UserInfo = BotUserInfo(), # noqa: B008
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
bot_info: UserInfo = BotUserInfo(), # noqa: B008
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -37,15 +34,14 @@ async def _(
|
||||
async with get_session() as session:
|
||||
bind_status = await create_or_update_bind(
|
||||
session=session,
|
||||
chat_platform=get_platform(bot),
|
||||
chat_account=event_user_info.user_id,
|
||||
user=nb_user,
|
||||
game_platform=GAME_TYPE,
|
||||
game_account=user.unique_identifier,
|
||||
)
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
async with HostPage(
|
||||
await render(
|
||||
'binding',
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform=GAME_TYPE,
|
||||
status='unknown',
|
||||
@@ -62,5 +58,5 @@ async def _(
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(
|
||||
raw=await screenshot(urlunparse(('http', get_self_netloc(), f'/host/{page_hash}.html', '', '', '')))
|
||||
raw=await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
).finish()
|
||||
@@ -1,14 +1,14 @@
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.adapters import Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import get_user # type: ignore[import-untyped]
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...utils.metrics import get_metrics
|
||||
from ...utils.platform import get_platform
|
||||
from ...utils.typing import Me
|
||||
from ..constant import CANT_VERIFY_MESSAGE
|
||||
from . import alc
|
||||
@@ -17,8 +17,8 @@ from .api.schemas.user_profile import UserProfile
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('query')
|
||||
async def _(bot: Bot, event: Event, matcher: Matcher, target: At | Me, event_session: EventSession):
|
||||
@alc.assign('TOP.query')
|
||||
async def _(event: Event, matcher: Matcher, target: At | Me, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -28,8 +28,9 @@ async def _(bot: Bot, event: Event, matcher: Matcher, target: At | Me, event_ses
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
chat_platform=get_platform(bot),
|
||||
chat_account=(target.target if isinstance(target, At) else event.get_user_id()),
|
||||
user=await get_user(
|
||||
event_session.platform, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
@@ -38,7 +39,7 @@ async def _(bot: Bot, event: Event, matcher: Matcher, target: At | Me, event_ses
|
||||
await (message + make_query_text(await Player(user_name=bind.game_account, trust=True).get_profile())).finish()
|
||||
|
||||
|
||||
@alc.assign('query')
|
||||
@alc.assign('TOP.query')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -1,10 +1,9 @@
|
||||
from arclet.alconna import Alconna, AllParam, Arg, ArgFlag, Args, CommandMeta, Option
|
||||
from nonebot_plugin_alconna import At, on_alconna
|
||||
from arclet.alconna import Arg, ArgFlag, Args, Subcommand
|
||||
from nonebot_plugin_alconna import At
|
||||
|
||||
from ...utils.exception import MessageFormatError
|
||||
from ...utils.typing import Me
|
||||
from .. import add_default_handlers
|
||||
from ..constant import BIND_COMMAND, QUERY_COMMAND
|
||||
from .. import add_block_handlers, alc, command
|
||||
from .api import Player
|
||||
from .constant import USER_NAME
|
||||
|
||||
@@ -20,31 +19,28 @@ def get_player(teaid_or_name: str) -> Player | MessageFormatError:
|
||||
return MessageFormatError('用户名/ID不合法')
|
||||
|
||||
|
||||
alc = on_alconna(
|
||||
Alconna(
|
||||
'茶服',
|
||||
Option(
|
||||
BIND_COMMAND[0],
|
||||
command.add(
|
||||
Subcommand(
|
||||
'TOS',
|
||||
Subcommand(
|
||||
'bind',
|
||||
Args(
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='茶服 用户名 / TeaID',
|
||||
notice='茶服 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN],
|
||||
)
|
||||
),
|
||||
alias=BIND_COMMAND[1:],
|
||||
compact=True,
|
||||
dest='bind',
|
||||
help_text='绑定 茶服 账号',
|
||||
),
|
||||
Option(
|
||||
QUERY_COMMAND[0],
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
Arg(
|
||||
'target',
|
||||
At | Me,
|
||||
notice='@想要查询的人 | 自己',
|
||||
notice='@想要查询的人 / 自己',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
Arg(
|
||||
@@ -53,27 +49,16 @@ alc = on_alconna(
|
||||
notice='茶服 用户名 / TeaID',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
# 如果放在一个 Union Args 里, 验证顺序不能保证, 可能出错
|
||||
),
|
||||
alias=QUERY_COMMAND[1:],
|
||||
compact=True,
|
||||
dest='query',
|
||||
help_text='查询 茶服 游戏信息',
|
||||
),
|
||||
Arg('other', AllParam, flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL]),
|
||||
meta=CommandMeta(
|
||||
description='查询 TetrisOnline茶服 的信息',
|
||||
example='茶服查我',
|
||||
compact=True,
|
||||
fuzzy_match=True,
|
||||
),
|
||||
),
|
||||
skip_for_unmatch=False,
|
||||
auto_send_output=True,
|
||||
aliases={'tos', 'TOS'},
|
||||
help_text='茶服 游戏相关指令',
|
||||
)
|
||||
)
|
||||
|
||||
alc.shortcut('(?i:tos|茶服)(?i:绑定|绑|bind)', {'command': 'tstats TOS bind', 'humanized': '茶服绑定'})
|
||||
alc.shortcut('(?i:tos|茶服)(?i:查询|查|query|stats)', {'command': 'tstats TOS query', 'humanized': '茶服查'})
|
||||
|
||||
add_block_handlers(alc.assign('TOS.query'))
|
||||
|
||||
from . import bind, query # noqa: E402, F401
|
||||
|
||||
add_default_handlers(alc)
|
||||
@@ -1,16 +1,13 @@
|
||||
from urllib.parse import urlunparse
|
||||
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import User # type: ignore[import-untyped]
|
||||
from nonebot_plugin_userinfo import BotUserInfo, EventUserInfo, UserInfo # type: ignore[import-untyped]
|
||||
|
||||
from ...db import BindStatus, create_or_update_bind, trigger
|
||||
from ...utils.avatar import get_avatar
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.platform import get_platform
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
@@ -19,13 +16,13 @@ from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('bind')
|
||||
@alc.assign('TOS.bind')
|
||||
async def _(
|
||||
bot: Bot,
|
||||
nb_user: User,
|
||||
account: Player,
|
||||
event_session: EventSession,
|
||||
bot_info: UserInfo = BotUserInfo(), # noqa: B008
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
bot_info: UserInfo = BotUserInfo(), # noqa: B008
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -37,8 +34,7 @@ async def _(
|
||||
async with get_session() as session:
|
||||
bind_status = await create_or_update_bind(
|
||||
session=session,
|
||||
chat_platform=get_platform(bot),
|
||||
chat_account=event_user_info.user_id,
|
||||
user=nb_user,
|
||||
game_platform=GAME_TYPE,
|
||||
game_account=user.unique_identifier,
|
||||
)
|
||||
@@ -46,7 +42,7 @@ async def _(
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
async with HostPage(
|
||||
await render(
|
||||
'binding',
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform=GAME_TYPE,
|
||||
status='unknown',
|
||||
@@ -62,5 +58,5 @@ async def _(
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(
|
||||
raw=await screenshot(urlunparse(('http', get_self_netloc(), f'/host/{page_hash}.html', '', '', '')))
|
||||
raw=await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
).finish()
|
||||
252
nonebot_plugin_tetris_stats/games/tos/query.py
Normal file
252
nonebot_plugin_tetris_stats/games/tos/query.py
Normal file
@@ -0,0 +1,252 @@
|
||||
from asyncio import gather
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
from typing import Literal, NamedTuple
|
||||
|
||||
from nonebot.adapters import Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession # type: ignore[import-untyped]
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_user import get_user # type: ignore[import-untyped]
|
||||
from nonebot_plugin_userinfo import EventUserInfo, UserInfo # type: ignore[import-untyped]
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...utils.exception import RequestError
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.metrics import TetrisMetricsProWithLPMADPM, get_metrics
|
||||
from ...utils.render import render
|
||||
from ...utils.render.schemas.base import People, Ranking
|
||||
from ...utils.render.schemas.tos_info import Info, Multiplayer, Radar
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.typing import Me, Number
|
||||
from ..constant import CANT_VERIFY_MESSAGE
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .api.schemas.user_info import UserInfoSuccess
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
def add_special_handlers(
|
||||
teaid_prefix: Literal['onebot-', 'kook-', 'discord-', 'qqguild-'], match_event: type[Event]
|
||||
) -> None:
|
||||
@alc.assign('TOS.query')
|
||||
async def _(
|
||||
event: Event,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
):
|
||||
if isinstance(event, match_event):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
player = Player(
|
||||
teaid=f'{teaid_prefix}{target.target}'
|
||||
if isinstance(target, At)
|
||||
else f'{teaid_prefix}{event.get_user_id()}',
|
||||
trust=True,
|
||||
)
|
||||
try:
|
||||
user_info, game_data = await gather(player.get_info(), get_game_data(player))
|
||||
if game_data is not None:
|
||||
await UniMessage.image(
|
||||
raw=await make_query_image(user_info, game_data, event_user_info)
|
||||
).finish()
|
||||
await make_query_text(user_info, game_data).finish()
|
||||
except RequestError as e:
|
||||
if e.status_code == HTTPStatus.BAD_REQUEST and '未找到此用户' in e.message:
|
||||
return
|
||||
raise
|
||||
|
||||
|
||||
try:
|
||||
from nonebot.adapters.onebot.v11 import MessageEvent as OB11MessageEvent
|
||||
|
||||
add_special_handlers('onebot-', OB11MessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from nonebot.adapters.qq.event import GuildMessageEvent as QQGuildMessageEvent
|
||||
from nonebot.adapters.qq.event import QQMessageEvent
|
||||
|
||||
add_special_handlers('qqguild-', QQGuildMessageEvent)
|
||||
add_special_handlers('onebot-', QQMessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from nonebot.adapters.kaiheila.event import MessageEvent as KookMessageEvent
|
||||
|
||||
add_special_handlers('kook-', KookMessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
from nonebot.adapters.discord import MessageEvent as DiscordMessageEvent
|
||||
|
||||
add_special_handlers('discord-', DiscordMessageEvent)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
@alc.assign('TOS.query')
|
||||
async def _(
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=await get_user(
|
||||
event_session.platform, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = CANT_VERIFY_MESSAGE
|
||||
player = Player(teaid=bind.game_account, trust=True)
|
||||
user_info, game_data = await gather(player.get_info(), get_game_data(player))
|
||||
if game_data is not None:
|
||||
await (
|
||||
message + UniMessage.image(raw=await make_query_image(user_info, game_data, event_user_info))
|
||||
).finish()
|
||||
await (message + make_query_text(user_info, game_data)).finish()
|
||||
|
||||
|
||||
@alc.assign('TOS.query')
|
||||
async def _(account: Player, event_session: EventSession, event_user_info: UserInfo = EventUserInfo()): # noqa: B008
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
):
|
||||
user_info, game_data = await gather(account.get_info(), get_game_data(account))
|
||||
if game_data is not None:
|
||||
await UniMessage.image(raw=await make_query_image(user_info, game_data, event_user_info)).finish()
|
||||
await make_query_text(user_info, game_data).finish()
|
||||
|
||||
|
||||
class GameData(NamedTuple):
|
||||
game_num: int
|
||||
metrics: TetrisMetricsProWithLPMADPM
|
||||
OR: Number
|
||||
dspp: Number
|
||||
ge: Number
|
||||
|
||||
|
||||
async def get_game_data(player: Player, query_num: int = 50) -> GameData | None:
|
||||
"""获取游戏数据"""
|
||||
user_profile = await player.get_profile()
|
||||
if user_profile.data == []:
|
||||
return None
|
||||
weighted_total_lpm = weighted_total_apm = weighted_total_adpm = total_time = 0.0
|
||||
total_attack = total_dig = total_offset = total_pieses = total_receive = num = 0
|
||||
for i in user_profile.data:
|
||||
# 排除单人局和时间为0的游戏
|
||||
# 茶: 不计算没挖掘的局, 即使apm和lpm也如此
|
||||
if i.num_players == 1 or i.time == 0 or i.dig is None:
|
||||
continue
|
||||
# 加权计算
|
||||
time = i.time / 1000
|
||||
lpm = 24 * (i.pieces / time)
|
||||
apm = (i.attack / time) * 60
|
||||
adpm = ((i.attack + i.dig) / time) * 60
|
||||
weighted_total_lpm += lpm * time
|
||||
weighted_total_apm += apm * time
|
||||
weighted_total_adpm += adpm * time
|
||||
total_attack += i.attack
|
||||
total_dig += i.dig
|
||||
total_offset += i.offset
|
||||
total_pieses += i.pieces
|
||||
total_receive += i.receive
|
||||
total_time += time
|
||||
num += 1
|
||||
if num >= query_num:
|
||||
break
|
||||
if num == 0:
|
||||
return None
|
||||
# TODO: 如果有效局数小于 {查询数} , 并且没有无dig信息的局, 且 user_profile.data 内有{请求数}个局, 则继续往前获取信息
|
||||
metrics = get_metrics(
|
||||
lpm=weighted_total_lpm / total_time, apm=weighted_total_apm / total_time, adpm=weighted_total_adpm / total_time
|
||||
)
|
||||
return GameData(
|
||||
game_num=num,
|
||||
metrics=metrics,
|
||||
OR=total_offset / total_receive * 100,
|
||||
dspp=total_dig / total_pieses,
|
||||
ge=2 * ((total_attack * total_dig) / total_pieses**2),
|
||||
)
|
||||
|
||||
|
||||
async def make_query_image(user_info: UserInfoSuccess, game_data: GameData, event_user_info: UserInfo) -> bytes:
|
||||
metrics = game_data.metrics
|
||||
duration = timedelta(milliseconds=float(user_info.data.pb_sprint)).total_seconds()
|
||||
sprint_value = f'{duration:.3f}s' if duration < 60 else f'{duration // 60:.0f}m {duration % 60:.3f}s' # noqa: PLR2004
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/tos/info',
|
||||
Info(
|
||||
user=People(avatar=await get_avatar(event_user_info, 'Data URI', None), name=user_info.data.name),
|
||||
ranking=Ranking(rating=float(user_info.data.ranking), rd=round(float(user_info.data.rd_now), 2)),
|
||||
multiplayer=Multiplayer(
|
||||
pps=metrics.pps,
|
||||
lpm=metrics.lpm,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
vs=metrics.vs,
|
||||
adpm=metrics.adpm,
|
||||
adpl=metrics.adpl,
|
||||
),
|
||||
radar=Radar(
|
||||
app=(app := (metrics.apm / (60 * metrics.pps))),
|
||||
OR=game_data.OR,
|
||||
dspp=game_data.dspp,
|
||||
ci=150 * game_data.dspp - 125 * app + 50 * (metrics.vs / metrics.apm) - 25,
|
||||
ge=game_data.ge,
|
||||
),
|
||||
sprint=sprint_value,
|
||||
challenge=f'{int(user_info.data.pb_challenge):,}' if user_info.data.pb_challenge != '0' else 'N/A',
|
||||
marathon=f'{int(user_info.data.pb_marathon):,}' if user_info.data.pb_marathon != '0' else 'N/A',
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
|
||||
|
||||
def make_query_text(user_info: UserInfoSuccess, game_data: GameData | None) -> UniMessage:
|
||||
user_data = user_info.data
|
||||
message = f'用户 {user_data.name} ({user_data.teaid}) '
|
||||
if user_data.ranked_games == '0':
|
||||
message += '暂无段位统计数据'
|
||||
else:
|
||||
message += f', 段位分 {round(float(user_data.rating_now),2)}±{round(float(user_data.rd_now),2)} ({round(float(user_data.vol_now),2)}) '
|
||||
if game_data is None:
|
||||
message += ', 暂无游戏数据'
|
||||
else:
|
||||
message += f', 最近 {game_data.game_num} 局数据'
|
||||
message += f"\nL'PM: {game_data.metrics.lpm} ( {game_data.metrics.pps} pps )"
|
||||
message += f'\nAPM: {game_data.metrics.apm} ( x{game_data.metrics.apl} )'
|
||||
message += f'\nADPM: {game_data.metrics.adpm} ( x{game_data.metrics.adpl} ) ( {game_data.metrics.vs}vs )'
|
||||
message += f'\n40L: {float(user_data.pb_sprint)/1000:.2f}s' if user_data.pb_sprint != '2147483647' else ''
|
||||
message += f'\nMarathon: {user_data.pb_marathon}' if user_data.pb_marathon != '0' else ''
|
||||
message += f'\nChallenge: {user_data.pb_challenge}' if user_data.pb_challenge != '0' else ''
|
||||
return UniMessage(message)
|
||||
@@ -27,6 +27,14 @@ class MessageFormatError(NeedCatchError):
|
||||
"""用户发送的消息格式不正确"""
|
||||
|
||||
|
||||
class RecordNotFoundError(NeedCatchError):
|
||||
"""找不到用户的某种记录"""
|
||||
|
||||
|
||||
class FallbackError(NeedCatchError):
|
||||
"""需要回滚至更通用的方法"""
|
||||
|
||||
|
||||
class DoNotCatchError(TetrisStatsError):
|
||||
"""不应该被捕获的异常基类"""
|
||||
|
||||
@@ -35,5 +43,5 @@ class WhatTheFuckError(DoNotCatchError):
|
||||
"""用于表示不应该出现的情况 ("""
|
||||
|
||||
|
||||
class HandleNotFinishedError(DoNotCatchError):
|
||||
"""任务没有正常完成处理的错误"""
|
||||
class NoFallbackError(DoNotCatchError): # 暂时没用 但是先写了
|
||||
"""没有可用的回退方法"""
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
from hashlib import sha256
|
||||
from ipaddress import IPv4Address, IPv6Address
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from typing import TYPE_CHECKING, ClassVar, Literal
|
||||
|
||||
from fastapi import FastAPI, status
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi import FastAPI, Path, status
|
||||
from fastapi.responses import FileResponse, HTMLResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from nonebot import get_app, get_driver
|
||||
from nonebot.log import logger
|
||||
from nonebot_plugin_localstore import get_cache_dir # type: ignore[import-untyped]
|
||||
|
||||
from .templates import templates_dir
|
||||
from ..config.config import CACHE_PATH
|
||||
from .image import img_to_png
|
||||
from .request import Request
|
||||
from .templates import TEMPLATES_DIR
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pydantic import IPvAnyAddress
|
||||
|
||||
app = get_app()
|
||||
app: FastAPI = get_app()
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
global_config = driver.config
|
||||
|
||||
cache_dir = get_cache_dir('nonebot_plugin_tetris_stats')
|
||||
|
||||
if not isinstance(app, FastAPI):
|
||||
msg = '本插件需要 FastAPI 驱动器才能运行'
|
||||
@@ -47,7 +48,7 @@ class HostPage:
|
||||
def _():
|
||||
app.mount(
|
||||
'/host/assets',
|
||||
StaticFiles(directory=templates_dir / 'assets'),
|
||||
StaticFiles(directory=TEMPLATES_DIR / 'assets'),
|
||||
name='assets',
|
||||
)
|
||||
logger.success('assets mounted')
|
||||
@@ -60,6 +61,22 @@ async def _(page_hash: str) -> HTMLResponse:
|
||||
return NOT_FOUND
|
||||
|
||||
|
||||
@app.get('/host/resource/tetrio/{resource_type}/{user_id}', status_code=status.HTTP_200_OK)
|
||||
async def _(
|
||||
resource_type: Literal['avatars', 'banners'], revision: int, user_id: str = Path(regex=r'^[a-f0-9]{24}$')
|
||||
) -> Response:
|
||||
if not (path := CACHE_PATH / 'tetrio' / resource_type / f'{user_id}_{revision}.png').exists():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(
|
||||
img_to_png(
|
||||
await Request.request(
|
||||
f'https://tetr.io/user-content/{resource_type}/{user_id}.jpg?rv={revision}', is_json=False
|
||||
)
|
||||
)
|
||||
)
|
||||
return FileResponse(path)
|
||||
|
||||
|
||||
def get_self_netloc() -> str:
|
||||
host: IPv4Address | IPv6Address | IPvAnyAddress = global_config.host
|
||||
if isinstance(host, IPv4Address):
|
||||
|
||||
@@ -52,3 +52,11 @@ async def get_avatar(user: UserInfo, scheme: Literal['Data URI', 'bytes'], defau
|
||||
raise TypeError(msg)
|
||||
return f'data:{Image.MIME[avatar_format]};base64,{b64encode(bot_avatar).decode()}'
|
||||
return bot_avatar
|
||||
|
||||
|
||||
def img_to_png(image: bytes) -> bytes:
|
||||
"""将图片转换为 PNG 格式"""
|
||||
result = BytesIO()
|
||||
with Image.open(BytesIO(image)) as img:
|
||||
img.save(result, 'PNG')
|
||||
return result.getvalue()
|
||||
@@ -1,19 +0,0 @@
|
||||
from nonebot.adapters import Bot
|
||||
|
||||
|
||||
def get_platform(bot: Bot) -> str:
|
||||
try:
|
||||
from nonebot.adapters.onebot.v12 import Bot as OB12Bot
|
||||
|
||||
if isinstance(bot, OB12Bot):
|
||||
return bot.platform
|
||||
except ImportError:
|
||||
pass
|
||||
try:
|
||||
from nonebot.adapters.satori import Bot as SaBot
|
||||
|
||||
if isinstance(bot, SaBot):
|
||||
return bot.platform
|
||||
except ImportError:
|
||||
pass
|
||||
return bot.type
|
||||
@@ -3,27 +3,79 @@ from typing import Literal, overload
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from nonebot.compat import PYDANTIC_V2
|
||||
|
||||
from ..templates import templates_dir
|
||||
from ..templates import TEMPLATES_DIR
|
||||
from .schemas.bind import Bind
|
||||
from .schemas.tetrio_info import TETRIOInfo
|
||||
from .schemas.tetrio.tetrio_info import Info as TETRIOInfo
|
||||
from .schemas.tetrio.tetrio_rank_detail import Data as TETRIORankDetailData
|
||||
from .schemas.tetrio.tetrio_rank_v1 import Data as TETRIORankDataV1
|
||||
from .schemas.tetrio.tetrio_rank_v2 import Data as TETRIORankDataV2
|
||||
from .schemas.tetrio.tetrio_record_blitz import Record as TETRIORecordBlitz
|
||||
from .schemas.tetrio.tetrio_record_sprint import Record as TETRIORecordSprint
|
||||
from .schemas.tetrio.tetrio_user_info_v2 import Info as TETRIOUserInfoV2
|
||||
from .schemas.tetrio.tetrio_user_list_v2 import List as TETRIOUserListV2
|
||||
from .schemas.top_info import Info as TOPInfo
|
||||
from .schemas.tos_info import Info as TOSInfo
|
||||
|
||||
env = Environment(
|
||||
loader=FileSystemLoader(templates_dir), autoescape=True, trim_blocks=True, lstrip_blocks=True, enable_async=True
|
||||
loader=FileSystemLoader(TEMPLATES_DIR), autoescape=True, trim_blocks=True, lstrip_blocks=True, enable_async=True
|
||||
)
|
||||
|
||||
|
||||
@overload
|
||||
async def render(render_type: Literal['binding'], data: Bind) -> str: ...
|
||||
|
||||
|
||||
async def render(render_type: Literal['v1/binding'], data: Bind) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['tetrio/info'], data: TETRIOInfo) -> str: ...
|
||||
async def render(render_type: Literal['v1/tetrio/info'], data: TETRIOInfo) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v1/tetrio/rank'], data: TETRIORankDataV1) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v1/top/info'], data: TOPInfo) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v1/tos/info'], data: TOSInfo) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/user/info'], data: TETRIOUserInfoV2) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/user/list'], data: TETRIOUserListV2) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/record/40l'], data: TETRIORecordSprint) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/record/blitz'], data: TETRIORecordBlitz) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/rank'], data: TETRIORankDataV2) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/rank/detail'], data: TETRIORankDetailData) -> str: ...
|
||||
|
||||
|
||||
async def render(render_type: Literal['binding', 'tetrio/info'], data: Bind | TETRIOInfo) -> str:
|
||||
async def render(
|
||||
render_type: Literal[
|
||||
'v1/binding',
|
||||
'v1/tetrio/info',
|
||||
'v1/tetrio/rank',
|
||||
'v1/top/info',
|
||||
'v1/tos/info',
|
||||
'v2/tetrio/user/info',
|
||||
'v2/tetrio/user/list',
|
||||
'v2/tetrio/record/40l',
|
||||
'v2/tetrio/record/blitz',
|
||||
'v2/tetrio/rank',
|
||||
'v2/tetrio/rank/detail',
|
||||
],
|
||||
data: Bind
|
||||
| TETRIOInfo
|
||||
| TETRIORankDataV1
|
||||
| TOPInfo
|
||||
| TOSInfo
|
||||
| TETRIOUserInfoV2
|
||||
| TETRIOUserListV2
|
||||
| TETRIORecordSprint
|
||||
| TETRIORecordBlitz
|
||||
| TETRIORankDataV2
|
||||
| TETRIORankDetailData,
|
||||
) -> str:
|
||||
if PYDANTIC_V2:
|
||||
return await env.get_template('index.html').render_async(path=render_type, data=data.model_dump_json())
|
||||
return await env.get_template('index.html').render_async(path=render_type, data=data.json())
|
||||
return await env.get_template('index.html').render_async(
|
||||
path=render_type, data=data.model_dump_json(by_alias=True)
|
||||
)
|
||||
return await env.get_template('index.html').render_async(path=render_type, data=data.json(by_alias=True))
|
||||
|
||||
|
||||
__all__ = ['render', 'Bind', 'TETRIOInfo']
|
||||
__all__ = ['render']
|
||||
|
||||
@@ -2,6 +2,8 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ...typing import Number
|
||||
|
||||
|
||||
class Avatar(BaseModel):
|
||||
type: Literal['identicon']
|
||||
@@ -11,3 +13,8 @@ class Avatar(BaseModel):
|
||||
class People(BaseModel):
|
||||
avatar: str | Avatar
|
||||
name: str
|
||||
|
||||
|
||||
class Ranking(BaseModel):
|
||||
rating: Number
|
||||
rd: Number
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ....typing import Number
|
||||
|
||||
|
||||
class TetraLeagueHistoryData(BaseModel):
|
||||
record_at: datetime
|
||||
tr: Number
|
||||
@@ -0,0 +1,49 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .....games.tetrio.api.typing import Rank
|
||||
from ....typing import Number
|
||||
from ..base import People, Ranking
|
||||
from .base import TetraLeagueHistoryData
|
||||
|
||||
|
||||
class User(People):
|
||||
bio: str | None
|
||||
|
||||
|
||||
class TetraLeague(BaseModel):
|
||||
rank: Rank
|
||||
tr: Number
|
||||
global_rank: Number
|
||||
pps: Number
|
||||
lpm: Number
|
||||
apm: Number
|
||||
apl: Number
|
||||
vs: Number
|
||||
adpm: Number
|
||||
adpl: Number
|
||||
|
||||
|
||||
class TetraLeagueHistory(BaseModel):
|
||||
data: list[TetraLeagueHistoryData]
|
||||
split_interval: Number
|
||||
min_tr: Number
|
||||
max_tr: Number
|
||||
offset: Number
|
||||
|
||||
|
||||
class Radar(BaseModel):
|
||||
app: Number
|
||||
dsps: Number
|
||||
dspp: Number
|
||||
ci: Number
|
||||
ge: Number
|
||||
|
||||
|
||||
class Info(BaseModel):
|
||||
user: User
|
||||
ranking: Ranking
|
||||
tetra_league: TetraLeague
|
||||
tetra_league_history: TetraLeagueHistory
|
||||
radar: Radar
|
||||
sprint: str
|
||||
blitz: str
|
||||
@@ -0,0 +1,31 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .....games.tetrio.api.typing import ValidRank
|
||||
|
||||
|
||||
class SpecialData(BaseModel):
|
||||
apm: float
|
||||
pps: float
|
||||
lpm: float
|
||||
vs: float
|
||||
adpm: float
|
||||
apl: float | None = None
|
||||
adpl: float | None = None
|
||||
apm_holder: str | None = None
|
||||
pps_holder: str | None = None
|
||||
vs_holder: str | None = None
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
name: ValidRank
|
||||
trending: float
|
||||
require_tr: float
|
||||
players: int
|
||||
|
||||
minimum_data: SpecialData
|
||||
average_data: SpecialData
|
||||
maximum_data: SpecialData
|
||||
|
||||
updated_at: datetime
|
||||
@@ -0,0 +1,16 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .....games.tetrio.api.typing import ValidRank
|
||||
|
||||
|
||||
class ItemData(BaseModel):
|
||||
trending: float
|
||||
require_tr: float
|
||||
players: int
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
items: dict[ValidRank, ItemData]
|
||||
updated_at: datetime
|
||||
@@ -0,0 +1,25 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .....games.tetrio.api.typing import ValidRank
|
||||
|
||||
|
||||
class AverageData(BaseModel):
|
||||
pps: float
|
||||
apm: float
|
||||
apl: float
|
||||
vs: float
|
||||
adpl: float
|
||||
|
||||
|
||||
class ItemData(BaseModel):
|
||||
require_tr: float
|
||||
trending: float
|
||||
average_data: AverageData
|
||||
players: int
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
items: dict[ValidRank, ItemData]
|
||||
updated_at: datetime
|
||||
@@ -0,0 +1,75 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..base import People
|
||||
|
||||
|
||||
class User(People):
|
||||
id: str
|
||||
|
||||
|
||||
class Max(BaseModel):
|
||||
combo: int
|
||||
btb: int
|
||||
|
||||
|
||||
class Mini(BaseModel):
|
||||
total: int
|
||||
single: int
|
||||
double: int
|
||||
|
||||
|
||||
class Tspins(BaseModel):
|
||||
total: int
|
||||
single: int
|
||||
double: int
|
||||
triple: int
|
||||
|
||||
mini: Mini
|
||||
|
||||
|
||||
class Finesse(BaseModel):
|
||||
faults: int
|
||||
accuracy: float
|
||||
|
||||
|
||||
class Statistic(BaseModel):
|
||||
keys: int
|
||||
kpp: float
|
||||
kps: float
|
||||
|
||||
max: Max
|
||||
|
||||
pieces: int
|
||||
pps: float
|
||||
lines: int
|
||||
lpm: float
|
||||
holds: int | None
|
||||
score: int
|
||||
|
||||
single: int
|
||||
double: int
|
||||
triple: int
|
||||
quad: int
|
||||
|
||||
tspins: Tspins
|
||||
|
||||
all_clear: int
|
||||
|
||||
finesse: Finesse
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
type: Literal['best', 'personal_best', 'recent', 'disputed']
|
||||
|
||||
user: User
|
||||
|
||||
replay_id: str
|
||||
rank: int | None
|
||||
personal_rank: int | None
|
||||
|
||||
statistic: Statistic
|
||||
|
||||
play_at: datetime
|
||||
@@ -0,0 +1,12 @@
|
||||
from .tetrio_record_base import Record as BaseRecord
|
||||
from .tetrio_record_base import Statistic as BaseStatistic
|
||||
|
||||
|
||||
class Statistic(BaseStatistic):
|
||||
spp: float
|
||||
|
||||
level: int
|
||||
|
||||
|
||||
class Record(BaseRecord):
|
||||
statistic: Statistic
|
||||
@@ -0,0 +1,5 @@
|
||||
from .tetrio_record_base import Record as BaseRecord
|
||||
|
||||
|
||||
class Record(BaseRecord):
|
||||
time: str
|
||||
@@ -0,0 +1,100 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .....games.tetrio.api.schemas.user_records import Zen
|
||||
from .....games.tetrio.api.typing import Rank
|
||||
from ....typing import Number
|
||||
from ..base import Avatar
|
||||
from .base import TetraLeagueHistoryData
|
||||
|
||||
|
||||
class Badge(BaseModel):
|
||||
id: str
|
||||
description: str
|
||||
group: str | None
|
||||
receive_at: datetime | None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
country: str | None
|
||||
|
||||
role: Literal['anon', 'user', 'bot', 'halfmod', 'mod', 'admin', 'sysop', 'banned']
|
||||
|
||||
avatar: str | Avatar
|
||||
banner: str | None
|
||||
|
||||
bio: str | None
|
||||
|
||||
friend_count: int | None
|
||||
supporter_tier: int
|
||||
|
||||
verified: bool
|
||||
bad_standing: bool
|
||||
|
||||
badges: list[Badge]
|
||||
xp: Number
|
||||
|
||||
playtime: str | None
|
||||
join_at: datetime | None
|
||||
|
||||
|
||||
class Statistic(BaseModel):
|
||||
total: int | None
|
||||
wins: int | None
|
||||
|
||||
|
||||
class TetraLeagueStatistic(BaseModel):
|
||||
total: int
|
||||
wins: int
|
||||
|
||||
|
||||
class TetraLeague(BaseModel):
|
||||
rank: Rank
|
||||
highest_rank: Rank
|
||||
|
||||
tr: Number
|
||||
|
||||
glicko: Number
|
||||
rd: Number
|
||||
|
||||
global_rank: int | None
|
||||
country_rank: int | None
|
||||
|
||||
pps: Number
|
||||
|
||||
apm: Number
|
||||
apl: Number
|
||||
|
||||
vs: Number | None
|
||||
adpl: Number | None
|
||||
|
||||
statistic: TetraLeagueStatistic
|
||||
|
||||
decaying: bool
|
||||
|
||||
history: list[TetraLeagueHistoryData]
|
||||
|
||||
|
||||
class Sprint(BaseModel):
|
||||
time: str
|
||||
global_rank: int | None
|
||||
play_at: datetime
|
||||
|
||||
|
||||
class Blitz(BaseModel):
|
||||
score: int
|
||||
global_rank: int | None
|
||||
play_at: datetime
|
||||
|
||||
|
||||
class Info(BaseModel):
|
||||
user: User
|
||||
tetra_league: TetraLeague | None
|
||||
statistic: Statistic | None
|
||||
sprint: Sprint | None
|
||||
blitz: Blitz | None
|
||||
zen: Zen
|
||||
@@ -0,0 +1,37 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .....games.tetrio.api.typing import Rank
|
||||
from ....typing import Number
|
||||
from ..base import Avatar
|
||||
|
||||
|
||||
class TetraLeague(BaseModel):
|
||||
rank: Rank
|
||||
tr: Number
|
||||
|
||||
glicko: Number | None
|
||||
rd: Number | None
|
||||
decaying: bool
|
||||
pps: Number
|
||||
apm: Number
|
||||
apl: Number
|
||||
vs: Number | None
|
||||
adpl: Number | None
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
avatar: str | Avatar
|
||||
country: str | None
|
||||
verified: bool
|
||||
tetra_league: TetraLeague
|
||||
xp: Number
|
||||
join_at: datetime | None
|
||||
|
||||
|
||||
class List(BaseModel):
|
||||
show_index: bool
|
||||
users: list[User]
|
||||
@@ -1,77 +0,0 @@
|
||||
from datetime import datetime
|
||||
from typing import Annotated, ClassVar
|
||||
|
||||
from nonebot.compat import PYDANTIC_V2
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ....game_data_processor.io_data_processor.api.typing import Rank
|
||||
from ...typing import Number
|
||||
from .base import People
|
||||
|
||||
if PYDANTIC_V2:
|
||||
from pydantic import PlainSerializer
|
||||
|
||||
|
||||
def format_datetime_to_timestamp(dt: datetime) -> int:
|
||||
return int(dt.timestamp() * 1000)
|
||||
|
||||
|
||||
class User(People):
|
||||
bio: str | None
|
||||
|
||||
|
||||
class Ranking(BaseModel):
|
||||
rating: Number
|
||||
rd: Number
|
||||
|
||||
|
||||
class TetraLeague(BaseModel):
|
||||
rank: Rank
|
||||
tr: Number
|
||||
global_rank: Number
|
||||
pps: Number
|
||||
lpm: Number
|
||||
apm: Number
|
||||
apl: Number
|
||||
vs: Number
|
||||
adpm: Number
|
||||
adpl: Number
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
if PYDANTIC_V2:
|
||||
record_at: Annotated[datetime, PlainSerializer(format_datetime_to_timestamp, return_type=int)]
|
||||
else:
|
||||
record_at: datetime # type: ignore[no-redef]
|
||||
tr: Number
|
||||
|
||||
|
||||
class TetraLeagueHistory(BaseModel):
|
||||
data: list[Data]
|
||||
split_interval: Number
|
||||
min_tr: Number
|
||||
max_tr: Number
|
||||
offset: Number
|
||||
|
||||
|
||||
class Radar(BaseModel):
|
||||
app: Number
|
||||
dsps: Number
|
||||
dspp: Number
|
||||
ci: Number
|
||||
ge: Number
|
||||
|
||||
|
||||
class TETRIOInfo(BaseModel):
|
||||
user: User
|
||||
ranking: Ranking
|
||||
tetra_league: TetraLeague
|
||||
tetra_league_history: TetraLeagueHistory
|
||||
radar: Radar
|
||||
sprint: str
|
||||
blitz: str
|
||||
|
||||
if not PYDANTIC_V2:
|
||||
|
||||
class Config:
|
||||
json_encoders: ClassVar[dict] = {datetime: format_datetime_to_timestamp}
|
||||
17
nonebot_plugin_tetris_stats/utils/render/schemas/top_info.py
Normal file
17
nonebot_plugin_tetris_stats/utils/render/schemas/top_info.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ...typing import Number
|
||||
from .base import People
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
pps: Number
|
||||
lpm: Number
|
||||
apm: Number
|
||||
apl: Number
|
||||
|
||||
|
||||
class Info(BaseModel):
|
||||
user: People
|
||||
today: Data
|
||||
history: Data
|
||||
32
nonebot_plugin_tetris_stats/utils/render/schemas/tos_info.py
Normal file
32
nonebot_plugin_tetris_stats/utils/render/schemas/tos_info.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Number
|
||||
from .base import People, Ranking
|
||||
|
||||
|
||||
class Multiplayer(BaseModel):
|
||||
pps: Number
|
||||
lpm: Number
|
||||
apm: Number
|
||||
apl: Number
|
||||
vs: Number
|
||||
adpm: Number
|
||||
adpl: Number
|
||||
|
||||
|
||||
class Radar(BaseModel):
|
||||
app: Number
|
||||
OR: Number = Field(serialization_alias='or')
|
||||
dspp: Number
|
||||
ci: Number
|
||||
ge: Number
|
||||
|
||||
|
||||
class Info(BaseModel):
|
||||
user: People
|
||||
ranking: Ranking
|
||||
multiplayer: Multiplayer
|
||||
radar: Radar
|
||||
sprint: str
|
||||
challenge: str
|
||||
marathon: str
|
||||
@@ -1,38 +1,44 @@
|
||||
from asyncio import sleep
|
||||
from collections.abc import Awaitable, Callable
|
||||
from collections.abc import Callable, Coroutine
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
from functools import wraps
|
||||
from typing import TypeVar, cast
|
||||
from typing import Any, ParamSpec, TypeVar
|
||||
|
||||
from nonebot.log import logger
|
||||
from nonebot_plugin_alconna.uniseg import SerializeFailed, UniMessage
|
||||
|
||||
T = TypeVar('T')
|
||||
P = ParamSpec('P')
|
||||
|
||||
|
||||
def retry(
|
||||
max_attempts: int = 3,
|
||||
exception_type: type[BaseException] | tuple[type[BaseException], ...] = Exception,
|
||||
delay: timedelta | None = None,
|
||||
) -> Callable[[Callable[..., Awaitable[T]]], Callable[..., Awaitable[T]]]:
|
||||
def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
|
||||
reply: str | UniMessage | None = None,
|
||||
) -> Callable[[Callable[P, Coroutine[Any, Any, T]]], Callable[P, Coroutine[Any, Any, T]]]:
|
||||
def decorator(func: Callable[P, Coroutine[Any, Any, T]]) -> Callable[P, Coroutine[Any, Any, T]]:
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs) -> T: # noqa: ANN002, ANN003
|
||||
attempts = 0
|
||||
while attempts < max_attempts + 1:
|
||||
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
|
||||
for i in range(max_attempts + 1):
|
||||
if i > 0:
|
||||
message = f'Retrying: {func.__name__} ({i}/{max_attempts})'
|
||||
logger.debug(message)
|
||||
with suppress(SerializeFailed):
|
||||
await UniMessage(reply or message).send()
|
||||
if i == max_attempts:
|
||||
break
|
||||
try:
|
||||
return await func(*args, **kwargs)
|
||||
except exception_type as e: # noqa: PERF203
|
||||
except exception_type as e:
|
||||
if i == max_attempts:
|
||||
raise
|
||||
logger.exception(e)
|
||||
attempts += 1
|
||||
if attempts <= max_attempts:
|
||||
if delay is not None:
|
||||
await sleep(delay.total_seconds())
|
||||
logger.debug(f'Retrying: {func.__name__} ({attempts}/{max_attempts})')
|
||||
continue
|
||||
raise
|
||||
msg = 'Unexpectedly reached the end of the retry loop'
|
||||
raise RuntimeError(msg)
|
||||
if delay is not None:
|
||||
await sleep(delay.total_seconds())
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
return cast(Callable[..., Awaitable[T]], wrapper)
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
from nonebot import get_plugin_config
|
||||
from playwright.async_api import TimeoutError, ViewportSize
|
||||
|
||||
from ..config.config import Config
|
||||
from .browser import BrowserManager
|
||||
from .retry import retry
|
||||
|
||||
config = get_plugin_config(Config)
|
||||
|
||||
|
||||
@retry(exception_type=TimeoutError, reply='截图失败, 重试中')
|
||||
async def screenshot(url: str) -> bytes:
|
||||
browser = await BrowserManager.get_browser()
|
||||
async with (
|
||||
await browser.new_page(no_viewport=True, viewport={'width': 0, 'height': 0}) as page,
|
||||
await browser.new_page(device_scale_factor=config.tetris_screenshot_quality) as page,
|
||||
):
|
||||
await page.goto(url)
|
||||
await page.wait_for_load_state('networkidle')
|
||||
return await page.screenshot(full_page=True, type='png')
|
||||
size: ViewportSize = await page.evaluate("""
|
||||
() => {
|
||||
const element = document.querySelector('#content');
|
||||
return {
|
||||
width: element.offsetWidth,
|
||||
height: element.offsetHeight,
|
||||
};
|
||||
};
|
||||
""")
|
||||
await page.set_viewport_size(size)
|
||||
return await page.locator('id=content').screenshot(timeout=5000, type='png')
|
||||
|
||||
@@ -1,71 +1,130 @@
|
||||
from asyncio.subprocess import PIPE, create_subprocess_exec
|
||||
from hashlib import sha256
|
||||
from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
from shutil import rmtree
|
||||
from time import time_ns
|
||||
from zipfile import ZipFile
|
||||
|
||||
from aiofiles import open
|
||||
from httpx import AsyncClient
|
||||
from nonebot import get_driver
|
||||
from nonebot.log import logger
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot_plugin_alconna import on_alconna
|
||||
from nonebot_plugin_localstore import get_data_dir # type: ignore[import-untyped]
|
||||
from nonebot_plugin_alconna import Alconna, Args, Option, on_alconna
|
||||
from nonebot_plugin_localstore import get_cache_file, get_data_dir
|
||||
from rich.progress import Progress
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
templates_dir = get_data_dir('nonebot_plugin_tetris_stats') / 'templates'
|
||||
TEMPLATES_DIR = get_data_dir('nonebot_plugin_tetris_stats') / 'templates'
|
||||
|
||||
alc = on_alconna('更新模板', permission=SUPERUSER)
|
||||
alc = on_alconna(Alconna('更新模板', Option('--revision', Args['revision', str], alias={'-R'})), permission=SUPERUSER)
|
||||
|
||||
|
||||
async def download_templates(tag: str) -> Path:
|
||||
logger.info(f'开始下载模板 {tag}')
|
||||
async with AsyncClient() as client:
|
||||
if tag == 'latest':
|
||||
logger.info('目标为 latest, 正在获取最新版本号')
|
||||
tag = (
|
||||
(
|
||||
await client.get(
|
||||
'https://github.com/A-Minos/tetris-stats-templates/releases/latest', follow_redirects=True
|
||||
)
|
||||
)
|
||||
.url.path.strip('/')
|
||||
.rsplit('/', 1)[-1]
|
||||
)
|
||||
logger.success(f'获取到的最新版本号: {tag}')
|
||||
path = get_cache_file('nonebot_plugin_tetris_stats', f'dist_{time_ns()}.zip')
|
||||
with Progress() as progress:
|
||||
task_id = progress.add_task('[red]Downloading...', total=None)
|
||||
async with (
|
||||
client.stream(
|
||||
'GET',
|
||||
f'https://github.com/A-Minos/tetris-stats-templates/releases/download/{tag}/dist.zip',
|
||||
follow_redirects=True,
|
||||
) as response,
|
||||
open(path, 'wb') as file,
|
||||
):
|
||||
response.raise_for_status()
|
||||
progress.update(task_id, total=int(response.headers.get('content-length', 0)) or None)
|
||||
async for chunk in response.aiter_bytes():
|
||||
await file.write(chunk)
|
||||
progress.update(task_id, advance=len(chunk))
|
||||
logger.success('模板下载完成')
|
||||
return path
|
||||
|
||||
|
||||
async def unzip_templates(zip_path: Path) -> Path:
|
||||
logger.info('开始解压模板')
|
||||
temp_path = TEMPLATES_DIR.parent / f'temp_{time_ns()}'
|
||||
with ZipFile(zip_path) as zip_file:
|
||||
zip_file.extractall(temp_path)
|
||||
zip_path.unlink()
|
||||
logger.success('模板解压完成')
|
||||
return temp_path
|
||||
|
||||
|
||||
async def check_hash(hash_file_path: Path) -> bool:
|
||||
logger.info('开始校验模板哈希值')
|
||||
for i in hash_file_path.read_text().splitlines():
|
||||
file_sha256, file_relative_path = i.split(maxsplit=1)
|
||||
file_path = hash_file_path.parent / file_relative_path
|
||||
hasher = sha256()
|
||||
if not file_path.is_file():
|
||||
logger.error(f'{file_path.name} 不存在或不是文件')
|
||||
return False
|
||||
async with open(file_path, 'rb') as file:
|
||||
while True:
|
||||
chunk = await file.read(65535)
|
||||
if not chunk:
|
||||
break
|
||||
hasher.update(chunk)
|
||||
if hasher.hexdigest() != file_sha256:
|
||||
logger.error(f'{file_path.name} hash 不匹配')
|
||||
return False
|
||||
logger.debug(f'{file_path.name} hash 匹配成功')
|
||||
logger.success('模板哈希值校验成功')
|
||||
return True
|
||||
|
||||
|
||||
async def init_templates(tag: str) -> bool:
|
||||
logger.info(f'开始初始化模板 {tag}')
|
||||
temp_path = await unzip_templates(await download_templates(tag))
|
||||
if not await check_hash(temp_path / 'hash.sha256'):
|
||||
rmtree(temp_path)
|
||||
return False
|
||||
if TEMPLATES_DIR.exists():
|
||||
logger.info('清除旧模板文件')
|
||||
rmtree(TEMPLATES_DIR)
|
||||
temp_path.rename(TEMPLATES_DIR)
|
||||
logger.info('模板初始化完成')
|
||||
return True
|
||||
|
||||
|
||||
async def check_tag(tag: str) -> bool:
|
||||
async with AsyncClient() as client:
|
||||
return (
|
||||
await client.get(f'https://github.com/A-Minos/tetris-stats-templates/releases/tag/{tag}')
|
||||
).status_code != HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def init_templates() -> None:
|
||||
try:
|
||||
await create_subprocess_exec('git', '--version', stdout=PIPE)
|
||||
except FileNotFoundError as e:
|
||||
msg = '未找到 git, 请确保 git 已安装并在环境变量中\n安装步骤请参阅: https://git-scm.com/book/zh/v2/%E8%B5%B7%E6%AD%A5-%E5%AE%89%E8%A3%85-Git'
|
||||
raise RuntimeError(msg) from e
|
||||
if not templates_dir.exists():
|
||||
logger.info('模板仓库不存在, 正在尝试初始化...')
|
||||
proc = await create_subprocess_exec(
|
||||
'git',
|
||||
'clone',
|
||||
'-b',
|
||||
'gh-pages',
|
||||
'https://github.com/A-Minos/tetris-stats-templates',
|
||||
templates_dir,
|
||||
'--depth=1',
|
||||
stdout=PIPE,
|
||||
stderr=PIPE,
|
||||
)
|
||||
stdout, stderr = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
for i in stderr.decode().splitlines():
|
||||
logger.error(i)
|
||||
msg = '初始化模板仓库失败'
|
||||
raise RuntimeError(msg)
|
||||
logger.success('模板仓库初始化成功')
|
||||
async def _():
|
||||
if (path := (TEMPLATES_DIR / 'hash.sha256')).is_file() and await check_hash(path):
|
||||
logger.success('模板验证成功')
|
||||
return
|
||||
proc = await create_subprocess_exec(
|
||||
'git', 'rev-parse', '--is-inside-work-tree', stdout=PIPE, stderr=PIPE, cwd=templates_dir
|
||||
)
|
||||
stdout, stderr = await proc.communicate()
|
||||
if proc.returncode != 0:
|
||||
for i in stderr.decode().splitlines():
|
||||
logger.error(i)
|
||||
logger.warning('模板仓库状态异常, 尝试重新初始化')
|
||||
rmtree(templates_dir)
|
||||
await init_templates()
|
||||
return
|
||||
logger.info('正在更新模板仓库...')
|
||||
proc = await create_subprocess_exec('git', 'pull', stdout=PIPE, stderr=PIPE, cwd=templates_dir)
|
||||
stdout, stderr = await proc.communicate()
|
||||
logger.info(stdout.decode().strip())
|
||||
if proc.returncode != 0:
|
||||
for i in stderr.decode().splitlines():
|
||||
logger.error(i)
|
||||
msg = '更新模板仓库失败'
|
||||
if not await init_templates('latest'):
|
||||
msg = '模板初始化失败'
|
||||
raise RuntimeError(msg)
|
||||
logger.success('模板仓库更新成功')
|
||||
|
||||
|
||||
@alc.handle()
|
||||
async def _():
|
||||
await init_templates()
|
||||
await alc.finish('模板仓库更新成功')
|
||||
async def _(revision: str | None = None):
|
||||
if revision is not None and not await check_tag(revision):
|
||||
await alc.finish(f'{revision} 不是模板仓库中的有效标签')
|
||||
logger.info('开始更新模板')
|
||||
if await init_templates(revision or 'latest'):
|
||||
await alc.finish('更新模板成功')
|
||||
await alc.finish('更新模板失败')
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any, Literal
|
||||
from typing import Literal
|
||||
|
||||
Number = float | int
|
||||
GameType = Literal['IO', 'TOP', 'TOS']
|
||||
CommandType = Literal['bind', 'query']
|
||||
AsyncCallable = Callable[..., Awaitable[Any]]
|
||||
BaseCommandType = Literal['bind', 'query']
|
||||
TETRIOCommandType = BaseCommandType | Literal['rank', 'config', 'list', 'record']
|
||||
AllCommandType = BaseCommandType | TETRIOCommandType
|
||||
Me = Literal[
|
||||
'我',
|
||||
'自己',
|
||||
|
||||
2183
poetry.lock
generated
2183
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = 'nonebot-plugin-tetris-stats'
|
||||
version = '1.2.6'
|
||||
version = '1.4.2'
|
||||
description = '一款基于 NoneBot2 的用于查询 Tetris 相关游戏数据的插件'
|
||||
authors = ['scdhh <wallfjjd@gmail.com>']
|
||||
readme = 'README.md'
|
||||
@@ -11,15 +11,18 @@ license = 'AGPL-3.0'
|
||||
[tool.poetry.dependencies]
|
||||
python = '^3.10'
|
||||
nonebot2 = { extras = ["fastapi"], version = "^2.3.0" }
|
||||
nonebot-plugin-alconna = ">=0.40"
|
||||
nonebot-plugin-apscheduler = "^0.4.0"
|
||||
nonebot-plugin-localstore = "^0.6.0"
|
||||
nonebot-plugin-alconna = ">=0.48.0"
|
||||
nonebot-plugin-apscheduler = ">=0.4,<0.6"
|
||||
nonebot-plugin-localstore = ">=0.6,<0.8"
|
||||
nonebot-plugin-orm = ">=0.1.1,<0.8.0"
|
||||
nonebot-plugin-session = "^0.3.1"
|
||||
nonebot-plugin-session-orm = "^0.2.0"
|
||||
nonebot-plugin-user = ">=0.2,<0.4"
|
||||
nonebot-plugin-userinfo = "^0.2.4"
|
||||
aiocache = "^0.12.2"
|
||||
aiofiles = "^23.2.1"
|
||||
aiofiles = ">=23.2.1,<25.0.0"
|
||||
arclet-alconna = "^1.8.19"
|
||||
async-lru = "^2.0.4"
|
||||
httpx = "^0.27.0"
|
||||
jinja2 = "^3.1.3"
|
||||
lxml = '^5.1.0'
|
||||
@@ -28,24 +31,26 @@ pillow = "^10.3.0"
|
||||
playwright = '^1.41.2'
|
||||
rich = "^13.7.1"
|
||||
ujson = '^5.9.0'
|
||||
zstandard = "^0.22.0"
|
||||
zstandard = ">=0.22,<0.24"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
mypy = '>=1.9'
|
||||
ruff = '>=0.3.0'
|
||||
types-aiofiles = "^23.2.0.20240106"
|
||||
types-aiofiles = ">=23.2.0.20240106,<25.0.0.0"
|
||||
types-lxml = "^2024.2.9"
|
||||
types-pillow = "^10.2.0.20240423"
|
||||
types-ujson = '^5.9.0'
|
||||
pandas-stubs = '>=1.5.2,<3.0.0'
|
||||
nonebot-plugin-orm = { extras = ["default"], version = ">=0.3,<0.8" }
|
||||
nonebot2 = { extras = ["all"], version = "^2.3.0" }
|
||||
nonebot-adapter-discord = "^0.1.3"
|
||||
nonebot-adapter-kaiheila = "^0.3.4"
|
||||
nonebot-adapter-onebot = "^2.4.1"
|
||||
nonebot-adapter-qq = "^1.4.4"
|
||||
nonebot-adapter-satori = "^0.11.4"
|
||||
nonebot-adapter-satori = ">=0.11.4,<0.13.0"
|
||||
nonebot-plugin-orm = { extras = ["default"], version = ">=0.3,<0.8" }
|
||||
|
||||
[tool.poetry.group.debug.dependencies]
|
||||
memory-profiler = "^0.61.0"
|
||||
objprint = '^0.2.2'
|
||||
viztracer = "^0.16.2"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user