mirror of
https://github.com/A-Minos/nonebot-plugin-tetris-stats.git
synced 2026-03-05 05:36:54 +08:00
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6493aba7e0 | |||
|
|
b82053be11 | ||
|
|
11bc486420 | ||
|
|
9916902c10 | ||
|
|
e347b41ba6 | ||
|
|
40d0bf06bb | ||
| 026ceaec6c | |||
|
|
e80e1bcda3 | ||
|
|
72e9a2fd87 | ||
|
|
f0b1a1c4f5 | ||
| 0bc3b86820 | |||
|
|
57d0b15242 | ||
|
|
56fe45efcf | ||
| 13f005179f | |||
| 243a8a286d | |||
| 8b7de6745b | |||
| d0fc82d88d | |||
| bb4da8accc | |||
| 56e06a7001 | |||
|
|
7c0b3cd240 | ||
| dca0619021 | |||
|
|
f56dce6918 | ||
|
|
ff3eb79967 | ||
|
|
0ac917f95e | ||
| 9806050e33 | |||
| 461327749f | |||
|
|
208582d313 | ||
|
|
90f655259d | ||
|
|
2ef400ca28 | ||
|
|
616a64bd6a | ||
|
|
bb8943d4c3 | ||
| 5e45db8cf5 | |||
|
|
2020deadac | ||
|
|
ce7bce6e20 | ||
|
|
d4b690f682 | ||
| c4bde71546 | |||
|
|
f56f993c69 | ||
|
|
cfcda6f597 | ||
|
|
96f5d4559d | ||
|
|
23f412b4f4 | ||
|
|
25b0d2bcdc | ||
|
|
a116f9901c | ||
|
|
82befd631e | ||
| 232389dd07 | |||
|
|
ce81015406 | ||
|
|
3d7b903f59 | ||
|
|
c5d499434e | ||
|
|
194fed24c9 | ||
|
|
1173c39e7a | ||
|
|
dfb19f150a | ||
|
|
7555297e1e | ||
|
|
587aa4a0de |
8
.github/workflows/Release.yml
vendored
8
.github/workflows/Release.yml
vendored
@@ -3,7 +3,7 @@ name: Release CI
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "*"
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
@@ -14,15 +14,15 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: astral-sh/setup-uv@v3
|
||||
- uses: astral-sh/setup-uv@v6
|
||||
name: Setup UV
|
||||
with:
|
||||
enable-cache: true
|
||||
|
||||
- name: "Set up Python"
|
||||
- name: 'Set up Python'
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version-file: ".python-version"
|
||||
python-version-file: '.python-version'
|
||||
|
||||
- run: uv sync
|
||||
shell: bash
|
||||
|
||||
58
.github/workflows/Test.yml
vendored
Normal file
58
.github/workflows/Test.yml
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
name: Code Coverage
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
# python-version: ['3.10', '3.11', '3.12', '3.13']
|
||||
python-version: ['3.10', '3.11', '3.12']
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
fail-fast: false
|
||||
env:
|
||||
OS: ${{ matrix.os }}
|
||||
PYTHON_VERSION: ${{ matrix.python-version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v6
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-suffix: ${{ env.PYTHON_VERSION }}_${{ env.OS }}
|
||||
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
uv python pin ${{ env.PYTHON_VERSION }}
|
||||
uv sync --group test
|
||||
|
||||
- name: Run tests
|
||||
run: uv run pytest --cov=nonebot_plugin_tetris_stats --cov-report xml
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
env_vars: OS,PYTHON_VERSION
|
||||
|
||||
check:
|
||||
if: always()
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
uses: re-actors/alls-green@223e4bb7a751b91f43eda76992bcfbf23b8b0302
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
6
.github/workflows/TypeCheck.yml
vendored
6
.github/workflows/TypeCheck.yml
vendored
@@ -9,15 +9,15 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: astral-sh/setup-uv@v3
|
||||
- uses: astral-sh/setup-uv@v6
|
||||
name: Setup UV
|
||||
with:
|
||||
enable-cache: true
|
||||
|
||||
- name: "Set up Python"
|
||||
- name: 'Set up Python'
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version-file: ".python-version"
|
||||
python-version-file: '.python-version'
|
||||
|
||||
- run: uv sync
|
||||
shell: bash
|
||||
|
||||
61
.github/workflows/codeql-analysis.yml
vendored
61
.github/workflows/codeql-analysis.yml
vendored
@@ -9,14 +9,14 @@
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "CodeQL"
|
||||
name: 'CodeQL'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
branches: [main]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ main ]
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: '17 6 * * 5'
|
||||
|
||||
@@ -32,41 +32,40 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'python' ]
|
||||
language: ['python']
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
|
||||
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
|
||||
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||
# queries: security-extended,security-and-quality
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v3
|
||||
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||
# queries: security-extended,security-and-quality
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v3
|
||||
|
||||
# If the Autobuild fails above, remove it and uncomment the following three lines.
|
||||
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
|
||||
# - run: |
|
||||
# echo "Run, Build Application using script"
|
||||
# ./location_of_script_within_repo/buildscript.sh
|
||||
# If the Autobuild fails above, remove it and uncomment the following three lines.
|
||||
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
# - run: |
|
||||
# echo "Run, Build Application using script"
|
||||
# ./location_of_script_within_repo/buildscript.sh
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
|
||||
546
.gitignore
vendored
546
.gitignore
vendored
@@ -1,24 +1,528 @@
|
||||
.idea
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/linux,macos,python,pycharm,windows,visualstudiocode,node
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=linux,macos,python,pycharm,windows,visualstudiocode,node
|
||||
|
||||
### Linux ###
|
||||
*~
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### macOS Patch ###
|
||||
# iCloud generated files
|
||||
*.icloud
|
||||
|
||||
### Node ###
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
test_*
|
||||
Untitled*
|
||||
*copy*
|
||||
.vscode
|
||||
*dev*
|
||||
*_cache*
|
||||
*backup*
|
||||
*.pyc
|
||||
node_modules
|
||||
.prettier*
|
||||
package.json
|
||||
pnpm-lock.yaml
|
||||
*.drawio.svg
|
||||
package-lock.json
|
||||
*Zone.Identifier
|
||||
.env*
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
|
||||
### Node Patch ###
|
||||
# Serverless Webpack directories
|
||||
.webpack/
|
||||
|
||||
# Optional stylelint cache
|
||||
|
||||
# SvelteKit build / generate output
|
||||
.svelte-kit
|
||||
|
||||
### PyCharm ###
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/**/usage.statistics.xml
|
||||
.idea/**/dictionaries
|
||||
.idea/**/shelf
|
||||
|
||||
# AWS User-specific
|
||||
.idea/**/aws.xml
|
||||
|
||||
# Generated files
|
||||
.idea/**/contentModel.xml
|
||||
|
||||
# Sensitive or high-churn files
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
.idea/**/dbnavigator.xml
|
||||
|
||||
# Gradle
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# Gradle and Maven with auto-import
|
||||
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||
# since they will be recreated, and may cause churn. Uncomment if using
|
||||
# auto-import.
|
||||
# .idea/artifacts
|
||||
# .idea/compiler.xml
|
||||
# .idea/jarRepositories.xml
|
||||
# .idea/modules.xml
|
||||
# .idea/*.iml
|
||||
# .idea/modules
|
||||
# *.iml
|
||||
# *.ipr
|
||||
|
||||
# CMake
|
||||
cmake-build-*/
|
||||
|
||||
# Mongo Explorer plugin
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
# File-based project format
|
||||
*.iws
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# SonarLint plugin
|
||||
.idea/sonarlint/
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
|
||||
# Editor-based Rest Client
|
||||
.idea/httpRequests
|
||||
|
||||
# Android studio 3.1+ serialized cache file
|
||||
.idea/caches/build_file_checksums.ser
|
||||
|
||||
### PyCharm Patch ###
|
||||
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
|
||||
|
||||
# *.iml
|
||||
# modules.xml
|
||||
# .idea/misc.xml
|
||||
# *.ipr
|
||||
|
||||
# Sonarlint plugin
|
||||
# https://plugins.jetbrains.com/plugin/7973-sonarlint
|
||||
.idea/**/sonarlint/
|
||||
|
||||
# SonarQube Plugin
|
||||
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
|
||||
.idea/**/sonarIssues.xml
|
||||
|
||||
# Markdown Navigator plugin
|
||||
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
|
||||
.idea/**/markdown-navigator.xml
|
||||
.idea/**/markdown-navigator-enh.xml
|
||||
.idea/**/markdown-navigator/
|
||||
|
||||
# Cache file creation bug
|
||||
# See https://youtrack.jetbrains.com/issue/JBR-2257
|
||||
.idea/$CACHE_FILE$
|
||||
|
||||
# CodeStream plugin
|
||||
# https://plugins.jetbrains.com/plugin/12206-codestream
|
||||
.idea/codestream.xml
|
||||
|
||||
# Azure Toolkit for IntelliJ plugin
|
||||
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
|
||||
.idea/**/azureSettings.xml
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
### Python Patch ###
|
||||
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||
poetry.toml
|
||||
|
||||
# ruff
|
||||
.ruff_cache/
|
||||
|
||||
# LSP config files
|
||||
pyrightconfig.json
|
||||
|
||||
### VisualStudioCode ###
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
### VisualStudioCode Patch ###
|
||||
# Ignore all local history of files
|
||||
.history
|
||||
.ionide
|
||||
|
||||
### Windows ###
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
Thumbs.db:encryptable
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/linux,macos,python,pycharm,windows,visualstudiocode,node
|
||||
|
||||
# NoneBot2
|
||||
bot.py
|
||||
TODO
|
||||
*.fish
|
||||
extracted_skin_mino_*
|
||||
sample_*
|
||||
.env*
|
||||
|
||||
# Misc
|
||||
ignore_*
|
||||
*.backup
|
||||
TODO*
|
||||
|
||||
@@ -1,22 +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: main
|
||||
autoupdate_schedule: weekly
|
||||
autoupdate_commit_msg: ':arrow_up: auto update by pre-commit hooks'
|
||||
autofix_commit_msg: ':rotating_light: auto fix by pre-commit hooks'
|
||||
autofix_prs: true
|
||||
autoupdate_branch: main
|
||||
autoupdate_schedule: weekly
|
||||
autoupdate_commit_msg: ':arrow_up: auto update by pre-commit hooks'
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.7.0
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
stages: [pre-commit]
|
||||
- id: ruff-format
|
||||
stages: [pre-commit]
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.12.4
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
stages: [pre-commit]
|
||||
- id: ruff-format
|
||||
stages: [pre-commit]
|
||||
|
||||
- repo: https://github.com/nonebot/nonemoji
|
||||
rev: v0.1.4
|
||||
hooks:
|
||||
- id: nonemoji
|
||||
stages: [prepare-commit-msg]
|
||||
- repo: https://github.com/nonebot/nonemoji
|
||||
rev: v0.1.4
|
||||
hooks:
|
||||
- id: nonemoji
|
||||
stages: [prepare-commit-msg]
|
||||
|
||||
@@ -42,7 +42,7 @@ This project uses [Tarina](https://github.com/ArcletProject/Tarina) for internat
|
||||
#### Adding a New Language
|
||||
|
||||
1. Navigate to the `./nonebot_plugin_tetris_stats/i18n/` directory.
|
||||
2. Run `tarina-lang create {language_code}` * Please note that the language code should preferably follow the [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag) standard.
|
||||
2. Run `tarina-lang create {language_code}` \* Please note that the language code should preferably follow the [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag) standard.
|
||||
3. Edit the generated `./nonebot_plugin_tetris_stats/i18n/{language_code}.json` file.
|
||||
|
||||
#### Updating an Existing Language
|
||||
|
||||
@@ -24,7 +24,7 @@ uv sync
|
||||
1. 代码静态检查使用 [ruff](https://docs.astral.sh/ruff/),你可以为你的ide安装对应插件来使用,也可以在命令行使用`ruff check ./nonebot_plugin_tetris_stats/`来检查代码。
|
||||
2. 代码格式化使用 [ruff](https://docs.astral.sh/ruff/),你可以为你的ide安装对应插件来使用,也可以在命令行使用`ruff format ./nonebot_plugin_tetris_stats/`来格式化代码。
|
||||
3. 类型检查同时使用 [basedpyright](https://docs.basedpyright.com/latest/) 和 [mypy](https://www.mypy-lang.org/),你可以为你的ide安装对应插件来使用。
|
||||
也可以在命令行使用下面的命令来检查代码:
|
||||
也可以在命令行使用下面的命令来检查代码:
|
||||
|
||||
```bash
|
||||
# basedpyright
|
||||
@@ -41,7 +41,7 @@ mypy ./nonebot_plugin_tetris_stats/
|
||||
#### 添加新的语言
|
||||
|
||||
1. 进入 `./nonebot_plugin_tetris_stats/i18n/` 目录。
|
||||
2. 运行 `tarina-lang create {语言代码}` * 请注意,语言代码最好符合 [IETF语言标签](https://zh.wikipedia.org/wiki/IETF%E8%AF%AD%E8%A8%80%E6%A0%87%E7%AD%BE) 的规范。
|
||||
2. 运行 `tarina-lang create {语言代码}` \* 请注意,语言代码最好符合 [IETF语言标签](https://zh.wikipedia.org/wiki/IETF%E8%AF%AD%E8%A8%80%E6%A0%87%E7%AD%BE) 的规范。
|
||||
3. 编辑生成的 `./nonebot_plugin_tetris_stats/i18n/{语言代码}.json` 文件。
|
||||
|
||||
#### 更新已有语言
|
||||
|
||||
@@ -6,10 +6,9 @@ require_plugins = {
|
||||
'nonebot_plugin_apscheduler',
|
||||
'nonebot_plugin_localstore',
|
||||
'nonebot_plugin_orm',
|
||||
'nonebot_plugin_session_orm',
|
||||
'nonebot_plugin_session',
|
||||
'nonebot_plugin_uninfo',
|
||||
'nonebot_plugin_user',
|
||||
'nonebot_plugin_userinfo',
|
||||
'nonebot_plugin_waiter',
|
||||
}
|
||||
|
||||
for i in require_plugins:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from nonebot import get_plugin_config
|
||||
from nonebot import get_driver, get_plugin_config
|
||||
from nonebot_plugin_localstore import get_plugin_cache_dir, get_plugin_data_dir
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
@@ -18,6 +18,7 @@ class ScopedConfig(BaseModel):
|
||||
request_timeout: float = 30.0
|
||||
screenshot_quality: float = 2
|
||||
proxy: Proxy = Field(default_factory=Proxy)
|
||||
development: bool = False
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
@@ -25,3 +26,4 @@ class Config(BaseModel):
|
||||
|
||||
|
||||
config = get_plugin_config(Config)
|
||||
global_config = get_driver().config
|
||||
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.alter_column('create_time', new_column_name='update_time', existing_type=sa.DateTime())
|
||||
@@ -41,6 +43,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.alter_column('update_time', new_column_name='create_time')
|
||||
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('file_hash', sa.String(length=128), nullable=True))
|
||||
@@ -38,6 +40,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_iorank_file_hash'))
|
||||
|
||||
@@ -16,7 +16,6 @@ from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, MofNCompleteColumn, Progress, TaskProgressColumn, TextColumn, TimeRemainingColumn
|
||||
from sqlalchemy import desc, select
|
||||
from sqlalchemy.dialects import sqlite
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -30,7 +29,7 @@ depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def migrate_old_data() -> None: # noqa: C901
|
||||
from json import dumps, loads
|
||||
from json import dumps, loads # noqa: PLC0415
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=op.get_bind())
|
||||
@@ -109,6 +108,8 @@ def migrate_old_data() -> None: # noqa: C901
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_tetriohistoricaldata',
|
||||
@@ -219,23 +220,25 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_historicaldata',
|
||||
sa.Column('id', sa.INTEGER(), nullable=False),
|
||||
sa.Column('trigger_time', sa.DATETIME(), nullable=False),
|
||||
sa.Column('bot_platform', sa.VARCHAR(length=32), nullable=True),
|
||||
sa.Column('bot_account', sa.VARCHAR(), nullable=True),
|
||||
sa.Column('source_type', sa.VARCHAR(length=32), nullable=True),
|
||||
sa.Column('source_account', sa.VARCHAR(), nullable=True),
|
||||
sa.Column('message', sa.BLOB(), nullable=True),
|
||||
sa.Column('game_platform', sa.VARCHAR(length=32), nullable=False),
|
||||
sa.Column('command_type', sa.VARCHAR(length=16), nullable=False),
|
||||
sa.Column('command_args', sqlite.JSON(), nullable=False),
|
||||
sa.Column('game_user', sqlite.JSON(), nullable=False),
|
||||
sa.Column('processed_data', sqlite.JSON(), nullable=False),
|
||||
sa.Column('finish_time', sa.DATETIME(), nullable=False),
|
||||
sa.Column('user_unique_identifier', sa.VARCHAR(length=32), nullable=False),
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('trigger_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('bot_platform', sa.String(length=32), nullable=True),
|
||||
sa.Column('bot_account', sa.String(), nullable=True),
|
||||
sa.Column('source_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('source_account', sa.String(), nullable=True),
|
||||
sa.Column('message', sa.PickleType(), nullable=True),
|
||||
sa.Column('game_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('command_type', sa.String(length=16), nullable=False),
|
||||
sa.Column('command_args', sa.JSON(), nullable=False),
|
||||
sa.Column('game_user', sa.JSON(), nullable=False),
|
||||
sa.Column('processed_data', sa.JSON(), nullable=False),
|
||||
sa.Column('finish_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('user_unique_identifier', sa.String(length=32), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name='pk_nonebot_plugin_tetris_stats_historicaldata'),
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_tetrioleaguestats
|
||||
|
||||
迁移 ID: 3d900bb0e8d4
|
||||
父迁移: 405c6936a164
|
||||
创建时间: 2025-07-18 02:22:03.771903
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = '3d900bb0e8d4'
|
||||
down_revision: str | Sequence[str] | None = '405c6936a164'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_tetrioleaguestats' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_tetrioleaguestats # noqa: N806
|
||||
New = Base.classes.nb_t_io_tl_stats # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
update_time=i.update_time,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -0,0 +1,85 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_tetrioleaguehistorical
|
||||
|
||||
迁移 ID: 405c6936a164
|
||||
父迁移: bbbdfd94e6fa
|
||||
创建时间: 2025-07-18 01:55:27.406032
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = '405c6936a164'
|
||||
down_revision: str | Sequence[str] | None = 'bbbdfd94e6fa'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_tetrioleaguehistorical' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_tetrioleaguehistorical # noqa: N806
|
||||
New = Base.classes.nb_t_io_tl_hist # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
request_id=i.request_id,
|
||||
data=i.data,
|
||||
update_time=i.update_time,
|
||||
stats_id=i.stats_id,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_tetrioleaguestats',
|
||||
@@ -102,6 +104,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_tetrioleaguestatsfield', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_tetrioleaguestatsfield_rank'))
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Create a new table
|
||||
|
||||
迁移 ID: 612d8b00d9ac
|
||||
父迁移: 5a1b93948494
|
||||
创建时间: 2025-05-26 04:49:29.664480
|
||||
|
||||
"""
|
||||
|
||||
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 = '612d8b00d9ac'
|
||||
down_revision: str | Sequence[str] | None = '5a1b93948494'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_triggerhistoricaldatav2',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('trigger_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('session_persist_id', sa.Integer(), nullable=False),
|
||||
sa.Column('game_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('command_type', sa.String(length=16), nullable=False),
|
||||
sa.Column('command_args', sa.JSON(), nullable=False),
|
||||
sa.Column('finish_time', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nonebot_plugin_tetris_stats_triggerhistoricaldatav2')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_triggerhistoricaldatav2', schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nonebot_plugin_tetris_stats_triggerhistoricaldatav2_command_type'),
|
||||
['command_type'],
|
||||
unique=False,
|
||||
)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nonebot_plugin_tetris_stats_triggerhistoricaldatav2_game_platform'),
|
||||
['game_platform'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_triggerhistoricaldatav2', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_triggerhistoricaldatav2_game_platform'))
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_triggerhistoricaldatav2_command_type'))
|
||||
|
||||
op.drop_table('nonebot_plugin_tetris_stats_triggerhistoricaldatav2')
|
||||
@@ -26,7 +26,9 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
from json import dumps, loads
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
from json import dumps, loads # noqa: PLC0415
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
connection = op.get_bind()
|
||||
@@ -50,7 +52,9 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
from json import dumps, loads
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
from json import dumps, loads # noqa: PLC0415
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
connection = op.get_bind()
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Migrate to uninfo
|
||||
|
||||
迁移 ID: 766cc7e75a62
|
||||
父迁移: 612d8b00d9ac
|
||||
创建时间: 2025-05-26 04:51:54.665200
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = '766cc7e75a62'
|
||||
down_revision: str | Sequence[str] | None = '612d8b00d9ac'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_triggerhistoricaldata' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
TriggerHistoricalData = Base.classes.nonebot_plugin_tetris_stats_triggerhistoricaldata # noqa: N806
|
||||
TriggerHistoricalDataV2 = Base.classes.nonebot_plugin_tetris_stats_triggerhistoricaldatav2 # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(TriggerHistoricalData).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
try:
|
||||
from nonebot_session_to_uninfo import ( # type: ignore[import-untyped] # noqa: PLC0415
|
||||
check_tables,
|
||||
get_id_map,
|
||||
)
|
||||
except ImportError as err:
|
||||
msg = '请安装 `nonebot-session-to-uninfo` 以迁移数据'
|
||||
raise ValueError(msg) from err
|
||||
|
||||
check_tables()
|
||||
|
||||
migration_limit = 10000 # 每次迁移的数据量为 10000 条
|
||||
last_id = -1
|
||||
id_map: dict[int, int] = {}
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for _ in range(math.ceil(count / migration_limit)):
|
||||
records = (
|
||||
db_session.query(TriggerHistoricalData)
|
||||
.order_by(TriggerHistoricalData.id)
|
||||
.where(TriggerHistoricalData.id > last_id)
|
||||
.limit(migration_limit)
|
||||
.all()
|
||||
)
|
||||
last_id = records[-1].id
|
||||
|
||||
session_ids = [
|
||||
record.session_persist_id for record in records if record.session_persist_id not in id_map
|
||||
]
|
||||
if session_ids:
|
||||
id_map.update(get_id_map(session_ids))
|
||||
|
||||
db_session.add_all(
|
||||
TriggerHistoricalDataV2(
|
||||
id=record.id,
|
||||
session_persist_id=id_map[record.session_persist_id],
|
||||
trigger_time=record.trigger_time,
|
||||
game_platform=record.game_platform,
|
||||
command_type=record.command_type,
|
||||
command_args=record.command_args,
|
||||
finish_time=record.finish_time,
|
||||
)
|
||||
for record in records
|
||||
)
|
||||
|
||||
progress.update(task, advance=len(records))
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
@@ -0,0 +1,94 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_tetrioleaguestatsfield
|
||||
|
||||
迁移 ID: 8459b2a4b7a3
|
||||
父迁移: 3d900bb0e8d4
|
||||
创建时间: 2025-07-18 02:24:59.560252
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = '8459b2a4b7a3'
|
||||
down_revision: str | Sequence[str] | None = '3d900bb0e8d4'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_tetrioleaguestatsfield' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_tetrioleaguestatsfield # noqa: N806
|
||||
New = Base.classes.nb_t_io_tl_stats_field # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
rank=i.rank,
|
||||
tr_line=i.tr_line,
|
||||
player_count=i.player_count,
|
||||
low_pps=i.low_pps,
|
||||
low_apm=i.low_apm,
|
||||
low_vs=i.low_vs,
|
||||
avg_pps=i.avg_pps,
|
||||
avg_apm=i.avg_apm,
|
||||
avg_vs=i.avg_vs,
|
||||
high_pps=i.high_pps,
|
||||
high_apm=i.high_apm,
|
||||
high_vs=i.high_vs,
|
||||
stats_id=i.stats_id,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -28,10 +28,12 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None: # noqa: C901
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
from nonebot.compat import PYDANTIC_V2, type_validate_json
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from rich.progress import (
|
||||
from nonebot.compat import PYDANTIC_V2, type_validate_json # noqa: PLC0415
|
||||
from pydantic import BaseModel, ValidationError # noqa: PLC0415
|
||||
from rich.progress import ( # noqa: PLC0415
|
||||
BarColumn,
|
||||
MofNCompleteColumn,
|
||||
Progress,
|
||||
@@ -58,14 +60,14 @@ def upgrade(name: str = '') -> None: # noqa: C901
|
||||
logger.info('空表, 跳过')
|
||||
return
|
||||
|
||||
from nonebot_plugin_tetris_stats.version import __version__
|
||||
from nonebot_plugin_tetris_stats.version import __version__ # noqa: PLC0415
|
||||
|
||||
if __version__ != '1.0.3':
|
||||
msg = '本迁移需要1.0.3版本, 请先锁定版本至1.0.3版本再执行本迁移'
|
||||
logger.critical(msg)
|
||||
raise RuntimeError(msg)
|
||||
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import ( # type: ignore[import-untyped]
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import ( # type: ignore[import-untyped] # noqa: PLC0415
|
||||
BaseProcessedData,
|
||||
)
|
||||
|
||||
@@ -101,3 +103,5 @@ def upgrade(name: str = '') -> None: # noqa: C901
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_bind',
|
||||
@@ -122,6 +124,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_iorank', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_iorank_rank'))
|
||||
|
||||
@@ -63,6 +63,8 @@ def migrate_old_data(connection: Connection) -> None:
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
try:
|
||||
db_path = Path(config.db_url)
|
||||
except AttributeError:
|
||||
@@ -91,3 +93,5 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
@@ -12,7 +12,6 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import sqlite
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
@@ -26,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
batch_op.drop_index('ix_nonebot_plugin_tetris_stats_historicaldata_command_type')
|
||||
@@ -71,6 +72,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_historicaldata_source_type'))
|
||||
@@ -82,19 +85,19 @@ def downgrade(name: str = '') -> None:
|
||||
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_historicaldata',
|
||||
sa.Column('id', sa.INTEGER(), nullable=False),
|
||||
sa.Column('trigger_time', sa.DATETIME(), nullable=False),
|
||||
sa.Column('bot_platform', sa.VARCHAR(length=32), nullable=True),
|
||||
sa.Column('bot_account', sa.VARCHAR(), nullable=True),
|
||||
sa.Column('source_type', sa.VARCHAR(length=32), nullable=True),
|
||||
sa.Column('source_account', sa.VARCHAR(), nullable=True),
|
||||
sa.Column('message', sa.BLOB(), nullable=True),
|
||||
sa.Column('game_platform', sa.VARCHAR(length=32), nullable=False),
|
||||
sa.Column('command_type', sa.VARCHAR(length=16), nullable=False),
|
||||
sa.Column('command_args', sqlite.JSON(), nullable=False),
|
||||
sa.Column('game_user', sa.BLOB(), nullable=False),
|
||||
sa.Column('processed_data', sa.BLOB(), nullable=False),
|
||||
sa.Column('finish_time', sa.DATETIME(), nullable=False),
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('trigger_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('bot_platform', sa.String(length=32), nullable=True),
|
||||
sa.Column('bot_account', sa.String(), nullable=True),
|
||||
sa.Column('source_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('source_account', sa.String(), nullable=True),
|
||||
sa.Column('message', sa.PickleType(), nullable=True),
|
||||
sa.Column('game_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('command_type', sa.String(length=16), nullable=False),
|
||||
sa.Column('command_args', sa.JSON(), nullable=False),
|
||||
sa.Column('game_user', sa.PickleType(), nullable=False),
|
||||
sa.Column('processed_data', sa.PickleType(), nullable=False),
|
||||
sa.Column('finish_time', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name='pk_nonebot_plugin_tetris_stats_historicaldata'),
|
||||
)
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
'nonebot_plugin_tetris_stats_tetriouserconfig',
|
||||
@@ -39,6 +41,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('nonebot_plugin_tetris_stats_tetriouserconfig')
|
||||
# ### end Alembic commands ###
|
||||
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
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')
|
||||
@@ -49,6 +51,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
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'))
|
||||
@@ -57,11 +61,11 @@ def downgrade(name: str = '') -> None:
|
||||
|
||||
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.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('chat_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('chat_account', sa.String(), nullable=False),
|
||||
sa.Column('game_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('game_account', sa.String(), 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:
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
"""create new tables
|
||||
|
||||
迁移 ID: b2075a5ce371
|
||||
父迁移: 766cc7e75a62
|
||||
创建时间: 2025-07-17 22:57:32.245327
|
||||
|
||||
"""
|
||||
|
||||
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 = 'b2075a5ce371'
|
||||
down_revision: str | Sequence[str] | None = '766cc7e75a62'
|
||||
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(
|
||||
'nb_t_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_nb_t_bind')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_bind', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_bind_user_id'), ['user_id'], unique=False)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_io_hist_data',
|
||||
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=32), nullable=False),
|
||||
sa.Column('data', sa.JSON(), nullable=False),
|
||||
sa.Column('update_time', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_hist_data')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_io_hist_data', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_hist_data_api_type'), ['api_type'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_hist_data_update_time'), ['update_time'], unique=False)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nb_t_io_hist_data_user_unique_identifier'), ['user_unique_identifier'], unique=False
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_io_tl_stats',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('update_time', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_tl_stats')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_io_tl_stats', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_tl_stats_update_time'), ['update_time'], unique=False)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_io_u_cfg',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('query_template', sa.String(length=2), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_u_cfg')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
op.create_table(
|
||||
'nb_t_top_hist_data',
|
||||
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_nb_t_top_hist_data')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_top_hist_data', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_top_hist_data_api_type'), ['api_type'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_top_hist_data_update_time'), ['update_time'], unique=False)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nb_t_top_hist_data_user_unique_identifier'), ['user_unique_identifier'], unique=False
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_tos_hist_data',
|
||||
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_nb_t_tos_hist_data')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_tos_hist_data', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_tos_hist_data_api_type'), ['api_type'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_tos_hist_data_update_time'), ['update_time'], unique=False)
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nb_t_tos_hist_data_user_unique_identifier'), ['user_unique_identifier'], unique=False
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_trigger_hist_v2',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('trigger_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('session_persist_id', sa.Integer(), nullable=False),
|
||||
sa.Column('game_platform', sa.String(length=32), nullable=False),
|
||||
sa.Column('command_type', sa.String(length=16), nullable=False),
|
||||
sa.Column('command_args', sa.JSON(), nullable=False),
|
||||
sa.Column('finish_time', sa.DateTime(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_trigger_hist_v2')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_trigger_hist_v2', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_trigger_hist_v2_command_type'), ['command_type'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_trigger_hist_v2_game_platform'), ['game_platform'], unique=False)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_io_tl_hist',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('request_id', sa.Uuid(), nullable=False),
|
||||
sa.Column('data', sa.JSON(), nullable=False),
|
||||
sa.Column('update_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('stats_id', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
['stats_id'], ['nb_t_io_tl_stats.id'], name=op.f('fk_nb_t_io_tl_hist_stats_id_nb_t_io_tl_stats')
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_tl_hist')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_io_tl_hist', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_tl_hist_request_id'), ['request_id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_tl_hist_update_time'), ['update_time'], unique=False)
|
||||
|
||||
op.create_table(
|
||||
'nb_t_io_tl_stats_field',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('rank', sa.String(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('stats_id', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
['stats_id'], ['nb_t_io_tl_stats.id'], name=op.f('fk_nb_t_io_tl_stats_field_stats_id_nb_t_io_tl_stats')
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_tl_stats_field')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_io_tl_stats_field', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_tl_stats_field_rank'), ['rank'], 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('nb_t_io_tl_stats_field', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_tl_stats_field_rank'))
|
||||
|
||||
op.drop_table('nb_t_io_tl_stats_field')
|
||||
with op.batch_alter_table('nb_t_io_tl_hist', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_tl_hist_update_time'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_tl_hist_request_id'))
|
||||
|
||||
op.drop_table('nb_t_io_tl_hist')
|
||||
with op.batch_alter_table('nb_t_trigger_hist_v2', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_trigger_hist_v2_game_platform'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_trigger_hist_v2_command_type'))
|
||||
|
||||
op.drop_table('nb_t_trigger_hist_v2')
|
||||
with op.batch_alter_table('nb_t_tos_hist_data', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_tos_hist_data_user_unique_identifier'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_tos_hist_data_update_time'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_tos_hist_data_api_type'))
|
||||
|
||||
op.drop_table('nb_t_tos_hist_data')
|
||||
with op.batch_alter_table('nb_t_top_hist_data', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_top_hist_data_user_unique_identifier'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_top_hist_data_update_time'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_top_hist_data_api_type'))
|
||||
|
||||
op.drop_table('nb_t_top_hist_data')
|
||||
op.drop_table('nb_t_io_u_cfg')
|
||||
with op.batch_alter_table('nb_t_io_tl_stats', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_tl_stats_update_time'))
|
||||
|
||||
op.drop_table('nb_t_io_tl_stats')
|
||||
with op.batch_alter_table('nb_t_io_hist_data', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_hist_data_user_unique_identifier'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_hist_data_update_time'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_hist_data_api_type'))
|
||||
|
||||
op.drop_table('nb_t_io_hist_data')
|
||||
with op.batch_alter_table('nb_t_bind', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_bind_user_id'))
|
||||
|
||||
op.drop_table('nb_t_bind')
|
||||
# ### end Alembic commands ###
|
||||
@@ -23,13 +23,15 @@ branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
def upgrade(name: str = '') -> None: # noqa: C901
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
from nonebot.compat import type_validate_json
|
||||
from pydantic import ValidationError
|
||||
from rich.progress import (
|
||||
from nonebot.compat import type_validate_json # noqa: PLC0415
|
||||
from pydantic import ValidationError # noqa: PLC0415
|
||||
from rich.progress import ( # noqa: PLC0415
|
||||
BarColumn,
|
||||
MofNCompleteColumn,
|
||||
Progress,
|
||||
@@ -37,9 +39,9 @@ def upgrade(name: str = '') -> None:
|
||||
TextColumn,
|
||||
TimeRemainingColumn,
|
||||
)
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import select # noqa: PLC0415
|
||||
from sqlalchemy.ext.automap import automap_base # noqa: PLC0415
|
||||
from sqlalchemy.orm import Session # noqa: PLC0415
|
||||
|
||||
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))
|
||||
@@ -58,13 +60,15 @@ def upgrade(name: str = '') -> None:
|
||||
if count == 0:
|
||||
logger.info('空表, 跳过')
|
||||
else:
|
||||
from nonebot_plugin_tetris_stats.version import __version__
|
||||
from nonebot_plugin_tetris_stats.version import __version__ # noqa: PLC0415
|
||||
|
||||
if __version__ != '1.0.4':
|
||||
msg = '本迁移需要1.0.4版本, 请先锁定版本至1.0.4版本再执行本迁移'
|
||||
logger.critical(msg)
|
||||
raise RuntimeError(msg)
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import BaseUser # type: ignore[import-untyped]
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import ( # type: ignore[import-untyped] # noqa: PLC0415
|
||||
BaseUser,
|
||||
)
|
||||
|
||||
models: list[type[BaseUser]] = BaseUser.__subclasses__()
|
||||
|
||||
@@ -103,6 +107,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nonebot_plugin_tetris_stats_historicaldata_user_unique_identifier'))
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_tetriouserconfig
|
||||
|
||||
迁移 ID: b96c8c18b79a
|
||||
父迁移: 8459b2a4b7a3
|
||||
创建时间: 2025-07-18 04:25:44.190319
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'b96c8c18b79a'
|
||||
down_revision: str | Sequence[str] | None = '8459b2a4b7a3'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_tetriouserconfig' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_tetriouserconfig # noqa: N806
|
||||
New = Base.classes.nb_t_io_u_cfg # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
query_template=i.query_template,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -26,6 +26,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
connection = op.get_bind()
|
||||
@@ -40,3 +42,5 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_tetriohistoricaldata
|
||||
|
||||
迁移 ID: bbbdfd94e6fa
|
||||
父迁移: d61e6ae36586
|
||||
创建时间: 2025-07-18 00:42:33.730885
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'bbbdfd94e6fa'
|
||||
down_revision: str | Sequence[str] | None = 'd61e6ae36586'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_tetriohistoricaldata' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_tetriohistoricaldata # noqa: N806
|
||||
New = Base.classes.nb_t_io_hist_data # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
user_unique_identifier=i.user_unique_identifier,
|
||||
api_type=i.api_type,
|
||||
data=i.data,
|
||||
update_time=i.update_time,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -0,0 +1,87 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_triggerhistoricaldatav2
|
||||
|
||||
迁移 ID: bc6abd57928f
|
||||
父迁移: ee76ae37d70a
|
||||
创建时间: 2025-07-18 04:33:04.222045
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'bc6abd57928f'
|
||||
down_revision: str | Sequence[str] | None = 'ee76ae37d70a'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_triggerhistoricaldatav2' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_triggerhistoricaldatav2 # noqa: N806
|
||||
New = Base.classes.nb_t_trigger_hist_v2 # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
trigger_time=i.trigger_time,
|
||||
session_persist_id=i.session_persist_id,
|
||||
game_platform=i.game_platform,
|
||||
command_type=i.command_type,
|
||||
command_args=i.command_args,
|
||||
finish_time=i.finish_time,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -0,0 +1,85 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_tophistoricaldata
|
||||
|
||||
迁移 ID: ce073d279d19
|
||||
父迁移: b96c8c18b79a
|
||||
创建时间: 2025-07-18 04:28:13.820635
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'ce073d279d19'
|
||||
down_revision: str | Sequence[str] | None = 'b96c8c18b79a'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_tophistoricaldata' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_tophistoricaldata # noqa: N806
|
||||
New = Base.classes.nb_t_top_hist_data # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
user_unique_identifier=i.user_unique_identifier,
|
||||
api_type=i.api_type,
|
||||
data=i.data,
|
||||
update_time=i.update_time,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -26,6 +26,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_tetriohistoricaldata', schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
@@ -38,6 +40,8 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
logger.warning('新数据可能不支持降级!')
|
||||
logger.warning('请确认数据库内数据可以迁移到旧版本!')
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_bind
|
||||
|
||||
迁移 ID: d61e6ae36586
|
||||
父迁移: b2075a5ce371
|
||||
创建时间: 2025-07-17 23:58:13.408384
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'd61e6ae36586'
|
||||
down_revision: str | Sequence[str] | None = 'b2075a5ce371'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_bind' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_bind # noqa: N806
|
||||
New = Base.classes.nb_t_bind # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(100):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
user_id=i.user_id,
|
||||
game_platform=i.game_platform,
|
||||
game_account=i.game_account,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -0,0 +1,85 @@
|
||||
"""migrate nonebot_plugin_tetris_stats_toshistoricaldata
|
||||
|
||||
迁移 ID: ee76ae37d70a
|
||||
父迁移: ce073d279d19
|
||||
创建时间: 2025-07-18 04:29:52.976624
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = 'ee76ae37d70a'
|
||||
down_revision: str | Sequence[str] | None = 'ce073d279d19'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def data_migrate() -> None:
|
||||
conn = op.get_bind()
|
||||
insp = inspect(conn)
|
||||
table_names = insp.get_table_names()
|
||||
if 'nonebot_plugin_tetris_stats_toshistoricaldata' not in table_names:
|
||||
return
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Old = Base.classes.nonebot_plugin_tetris_stats_toshistoricaldata # noqa: N806
|
||||
New = Base.classes.nb_t_tos_hist_data # noqa: N806
|
||||
|
||||
with Session(conn) as db_session:
|
||||
count = db_session.query(Old).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在迁移数据, 请不要关闭程序...')
|
||||
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
TaskProgressColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('迁移数据...', total=count)
|
||||
|
||||
for i in db_session.query(Old).yield_per(1):
|
||||
db_session.add(
|
||||
New(
|
||||
id=i.id,
|
||||
user_unique_identifier=i.user_unique_identifier,
|
||||
api_type=i.api_type,
|
||||
data=i.data,
|
||||
update_time=i.update_time,
|
||||
)
|
||||
)
|
||||
|
||||
progress.update(task, advance=1)
|
||||
|
||||
if progress.tasks[task].completed % 100 == 0:
|
||||
db_session.commit()
|
||||
|
||||
db_session.commit()
|
||||
|
||||
logger.success('tetris_stats: 数据迁移完成!')
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
data_migrate()
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -25,6 +25,8 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
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')
|
||||
@@ -66,23 +68,25 @@ def upgrade(name: str = '') -> None:
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
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('id', sa.Integer(), nullable=False),
|
||||
sa.Column('rank', sa.String(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('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.Column('update_time', sa.DateTime(), nullable=False),
|
||||
sa.Column('file_hash', sa.String(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:
|
||||
|
||||
@@ -11,8 +11,8 @@ from nonebot_plugin_orm import AsyncSession, get_session
|
||||
from nonebot_plugin_user import User
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..utils.typing import AllCommandType, BaseCommandType, GameType, TETRIOCommandType
|
||||
from .models import Bind, TriggerHistoricalData
|
||||
from ..utils.typedefs import AllCommandType, BaseCommandType, GameType, TETRIOCommandType
|
||||
from .models import Bind, TriggerHistoricalDataV2
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
@@ -63,6 +63,23 @@ async def create_or_update_bind(
|
||||
return status
|
||||
|
||||
|
||||
async def remove_bind(
|
||||
session: AsyncSession,
|
||||
user: User,
|
||||
game_platform: GameType,
|
||||
) -> bool:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=user,
|
||||
game_platform=game_platform,
|
||||
)
|
||||
if bind is not None:
|
||||
await session.delete(bind)
|
||||
await session.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
T = TypeVar('T', 'TETRIOHistoricalData', 'TOPHistoricalData', 'TOSHistoricalData')
|
||||
|
||||
lock = Lock()
|
||||
@@ -122,7 +139,7 @@ async def trigger(
|
||||
except FinishedException:
|
||||
async with get_session() as session:
|
||||
session.add(
|
||||
TriggerHistoricalData(
|
||||
TriggerHistoricalDataV2(
|
||||
trigger_time=trigger_time,
|
||||
session_persist_id=session_persist_id,
|
||||
game_platform=game_platform,
|
||||
|
||||
@@ -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 AllCommandType, GameType
|
||||
from ..utils.typedefs import AllCommandType, GameType
|
||||
|
||||
|
||||
class PydanticType(TypeDecorator):
|
||||
@@ -65,13 +65,17 @@ class PydanticType(TypeDecorator):
|
||||
|
||||
|
||||
class Bind(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_bind'
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(index=True)
|
||||
game_platform: Mapped[GameType] = mapped_column(String(32))
|
||||
game_account: Mapped[str]
|
||||
|
||||
|
||||
class TriggerHistoricalData(MappedAsDataclass, Model):
|
||||
class TriggerHistoricalDataV2(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_trigger_hist_v2'
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
trigger_time: Mapped[datetime] = mapped_column(DateTime)
|
||||
session_persist_id: Mapped[int]
|
||||
|
||||
@@ -44,7 +44,7 @@ async def _(matcher: Matcher, account: MessageFormatError):
|
||||
|
||||
@alc.handle()
|
||||
async def _(matcher: Matcher, matches: AlcMatches):
|
||||
if matches.head_matched and matches.options != {} or matches.main_args == {}:
|
||||
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"查看帮助'
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..utils.typing import GameType
|
||||
from ..utils.typedefs import GameType
|
||||
|
||||
T = TypeVar('T', bound=GameType)
|
||||
|
||||
@@ -22,3 +22,5 @@ class BaseUser(BaseModel, ABC, Generic[T]):
|
||||
@abstractmethod
|
||||
def unique_identifier(self) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
__hash__ = BaseModel.__hash__
|
||||
|
||||
@@ -23,7 +23,7 @@ command = Subcommand(
|
||||
)
|
||||
|
||||
|
||||
from . import bind, config, list, query, rank, record # noqa: E402
|
||||
from . import bind, config, list, query, rank, record, unbind # noqa: A004, E402
|
||||
|
||||
main_command.add(command)
|
||||
|
||||
@@ -35,4 +35,5 @@ __all__ = [
|
||||
'query',
|
||||
'rank',
|
||||
'record',
|
||||
'unbind',
|
||||
]
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
from typing import Literal, overload
|
||||
from uuid import UUID
|
||||
|
||||
from nonebot import __version__ as __nonebot_version__
|
||||
from nonebot.compat import type_validate_json
|
||||
from yarl import URL
|
||||
|
||||
from ....utils.exception import RequestError
|
||||
from ....version import __version__
|
||||
from ..constant import BASE_URL
|
||||
from .cache import Cache
|
||||
from .schemas.base import FailedModel
|
||||
@@ -22,7 +24,12 @@ async def by(
|
||||
await get(
|
||||
BASE_URL / f'users/by/{by_type}',
|
||||
parameter,
|
||||
{'X-Session-ID': str(x_session_id)} if x_session_id is not None else None,
|
||||
{
|
||||
'X-Session-ID': str(x_session_id),
|
||||
'User-Agent': f'nonebot-plugin-tetris-stats/{__version__} (Windows NT 10.0; Win64; x64) NoneBot2/{__nonebot_version__}',
|
||||
}
|
||||
if x_session_id is not None
|
||||
else None,
|
||||
),
|
||||
)
|
||||
if isinstance(model, FailedModel):
|
||||
|
||||
@@ -7,10 +7,12 @@ from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
from ....db.models import PydanticType
|
||||
from .schemas.base import SuccessModel
|
||||
from .typing import Records, Summaries
|
||||
from .typedefs import Records, Summaries
|
||||
|
||||
|
||||
class TETRIOHistoricalData(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_hist_data'
|
||||
|
||||
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', Records, Summaries]] = mapped_column(String(32), index=True)
|
||||
|
||||
@@ -27,7 +27,7 @@ from .schemas.summaries.base import User as SummariesUser
|
||||
from .schemas.summaries.league import LeagueSuccessModel
|
||||
from .schemas.user import User
|
||||
from .schemas.user_info import UserInfo, UserInfoSuccess
|
||||
from .typing import Records, Summaries
|
||||
from .typedefs import Records, Summaries
|
||||
|
||||
|
||||
class RecordModeType(str, Enum):
|
||||
@@ -46,7 +46,7 @@ class RecordKey(NamedTuple):
|
||||
record_type: RecordType
|
||||
|
||||
def to_records(self) -> Records:
|
||||
return cast(Records, f'{self.mode_type.value}_{self.record_type.value}')
|
||||
return cast('Records', f'{self.mode_type.value}_{self.record_type.value}')
|
||||
|
||||
|
||||
class Player:
|
||||
@@ -89,7 +89,7 @@ class Player:
|
||||
|
||||
@property
|
||||
def _request_user_parameter(self) -> str:
|
||||
return self.user_id or cast(str, self.user_name).lower()
|
||||
return self.user_id or cast('str', self.user_name).lower()
|
||||
|
||||
@property
|
||||
async def user(self) -> User:
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Prisecter
|
||||
from ...typedefs import Prisecter
|
||||
|
||||
|
||||
class AggregateStats(BaseModel):
|
||||
|
||||
@@ -12,11 +12,11 @@ class Time(BaseModel):
|
||||
zero: bool
|
||||
locked: bool
|
||||
prev: int
|
||||
frameoffset: int
|
||||
frameoffset: int | None = None
|
||||
|
||||
|
||||
class Stats(BaseModel):
|
||||
seed: int | None = None # ?: 不知道是之后都没有了还是还会有
|
||||
seed: float | None = None # ?: 不知道是之后都没有了还是还会有
|
||||
lines: int
|
||||
level_lines: int
|
||||
level_lines_needed: int
|
||||
@@ -24,8 +24,8 @@ class Stats(BaseModel):
|
||||
holds: int = 0
|
||||
time: Time | None = None # ?: 不知道是之后都没有了还是还会有
|
||||
score: int
|
||||
zenlevel: int
|
||||
zenprogress: int
|
||||
zenlevel: int | None = None
|
||||
zenprogress: int | None = None
|
||||
level: int
|
||||
combo: int
|
||||
currentcombopower: int | None = None
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Any
|
||||
from nonebot.compat import PYDANTIC_V2
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Prisecter
|
||||
from ...typedefs import Prisecter
|
||||
|
||||
|
||||
class Parameter(BaseModel):
|
||||
|
||||
@@ -3,11 +3,11 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Rank, ValidRank
|
||||
from ...typedefs import Rank, ValidRank
|
||||
from ..base import ArCounts, FailedModel, P, SuccessModel
|
||||
|
||||
|
||||
class League(BaseModel):
|
||||
class BaseLeague(BaseModel):
|
||||
gamesplayed: int
|
||||
gameswon: int
|
||||
tr: float
|
||||
@@ -16,13 +16,22 @@ class League(BaseModel):
|
||||
bestrank: ValidRank
|
||||
glicko: float
|
||||
rd: float
|
||||
apm: float
|
||||
pps: float
|
||||
vs: float
|
||||
decaying: bool
|
||||
|
||||
|
||||
class Entry(BaseModel):
|
||||
class InvalidLeague(BaseLeague):
|
||||
pps: float | None
|
||||
apm: None
|
||||
vs: None
|
||||
|
||||
|
||||
class League(BaseLeague):
|
||||
pps: float
|
||||
apm: float
|
||||
vs: float
|
||||
|
||||
|
||||
class BaseEntry(BaseModel):
|
||||
id: str = Field(..., alias='_id')
|
||||
username: str
|
||||
role: Literal['anon', 'user', 'bot', 'halfmod', 'mod', 'admin', 'sysop']
|
||||
@@ -30,7 +39,6 @@ class Entry(BaseModel):
|
||||
xp: float
|
||||
country: str | None = None
|
||||
supporter: bool | None = None
|
||||
league: League
|
||||
gamesplayed: int
|
||||
gameswon: int
|
||||
gametime: float
|
||||
@@ -39,8 +47,16 @@ class Entry(BaseModel):
|
||||
p: P
|
||||
|
||||
|
||||
class InvalidEntry(BaseEntry):
|
||||
league: InvalidLeague
|
||||
|
||||
|
||||
class Entry(BaseEntry):
|
||||
league: League
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
entries: list[Entry]
|
||||
entries: list[Entry | InvalidEntry]
|
||||
|
||||
|
||||
class BySuccessModel(SuccessModel):
|
||||
|
||||
@@ -14,8 +14,8 @@ __all__ = [
|
||||
'SoloSuccessModel',
|
||||
'SummariesModel',
|
||||
'Zen',
|
||||
'ZenSuccessModel',
|
||||
'Zenith',
|
||||
'ZenithEx',
|
||||
'ZenithSuccessModel',
|
||||
'ZenSuccessModel',
|
||||
]
|
||||
|
||||
@@ -1,25 +1,93 @@
|
||||
from typing import TypeAlias
|
||||
from datetime import datetime
|
||||
from enum import IntEnum
|
||||
from typing import Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..base import FailedModel, SuccessModel
|
||||
|
||||
|
||||
class RankType(IntEnum):
|
||||
PERCENTILE = 1
|
||||
ISSUE = 2
|
||||
ZENITH = 3
|
||||
PERCENTILELAX = 4
|
||||
PERCENTILEVLAX = 5
|
||||
PERCENTILEMLAX = 6
|
||||
|
||||
|
||||
class ValueType(IntEnum):
|
||||
NONE = 0
|
||||
NUMBER = 1
|
||||
TIME = 2
|
||||
TIME_INV = 3
|
||||
FLOOR = 4
|
||||
ISSUE = 5
|
||||
NUMBER_INV = 6
|
||||
|
||||
|
||||
class ArType(IntEnum):
|
||||
UNRANKED = 0
|
||||
RANKED = 1
|
||||
COMPETITIVE = 2
|
||||
|
||||
|
||||
class Rank(IntEnum):
|
||||
NONE = 0
|
||||
BRONZE = 1
|
||||
SILVER = 2
|
||||
GOLD = 3
|
||||
PLATINUM = 4
|
||||
DIAMOND = 5
|
||||
ISSUED = 100
|
||||
|
||||
|
||||
class Ally(BaseModel):
|
||||
id: str = Field(alias='_id')
|
||||
username: str
|
||||
role: Literal['anon', 'user', 'bot', 'halfmod', 'mod', 'admin', 'sysop', 'hidden', 'banned']
|
||||
country: str | None = None
|
||||
supporter: bool
|
||||
avatar_revision: int | None = None
|
||||
|
||||
|
||||
class X(BaseModel):
|
||||
ally: Ally | None = None
|
||||
|
||||
|
||||
class Achievement(BaseModel):
|
||||
# 这**都是些啥
|
||||
k: int
|
||||
o: int
|
||||
rt: int
|
||||
vt: int
|
||||
achievement_id: int = Field(alias='k')
|
||||
category: str
|
||||
primary_name: str = Field(alias='name')
|
||||
objective: str = Field(alias='object')
|
||||
flavor_text: str = Field(alias='desc')
|
||||
order: int = Field(alias='o')
|
||||
rank_type: RankType = Field(alias='rt')
|
||||
value_type: ValueType = Field(alias='vt')
|
||||
ar_type: ArType = Field(alias='art')
|
||||
min: int
|
||||
deci: int
|
||||
name: str
|
||||
object: str
|
||||
category: str
|
||||
hidden: bool
|
||||
desc: str
|
||||
nolb: bool
|
||||
event: str | None = None
|
||||
event_past: bool | None = None
|
||||
disabled: bool | None = None
|
||||
pair: bool | None = None
|
||||
achieved_score: float | None = Field(None, alias='v')
|
||||
a: float | None = None
|
||||
t: datetime | None = None
|
||||
pos: int | None = None
|
||||
total: int | None = None
|
||||
rank: Rank | None = None
|
||||
x: X | None = None
|
||||
n: str
|
||||
stub: bool
|
||||
|
||||
tiebreak: int
|
||||
notifypb: bool
|
||||
id: str | None = Field(None, alias='_id')
|
||||
progress: float | None = None
|
||||
stub: bool | None = None
|
||||
|
||||
|
||||
class AchievementsSuccessModel(SuccessModel):
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Literal
|
||||
from nonebot.compat import PYDANTIC_V2
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Rank, S1Rank, S1ValidRank
|
||||
from ...typedefs import Rank, S1Rank, S1ValidRank
|
||||
from ..base import SuccessModel
|
||||
|
||||
if PYDANTIC_V2:
|
||||
|
||||
@@ -86,7 +86,7 @@ class Record(BaseModel):
|
||||
pb: bool
|
||||
oncepb: bool
|
||||
ts: datetime
|
||||
revolution: None
|
||||
revolution: str | None
|
||||
user: User
|
||||
otherusers: list
|
||||
leaderboards: list[str]
|
||||
@@ -97,7 +97,7 @@ class Record(BaseModel):
|
||||
|
||||
|
||||
class Best(BaseModel):
|
||||
record: None # WTF
|
||||
record: Record | None
|
||||
rank: int
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Literal, NewType
|
||||
|
||||
S1ValidRank = Literal[
|
||||
'x+',
|
||||
'x',
|
||||
'u',
|
||||
'ss',
|
||||
@@ -1,18 +1,21 @@
|
||||
from hashlib import md5
|
||||
from secrets import choice
|
||||
|
||||
from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot_plugin_alconna import Args, Subcommand
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import QryItrface, Uninfo
|
||||
from nonebot_plugin_uninfo import User as UninfoUser
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from nonebot_plugin_userinfo import BotUserInfo, UserInfo
|
||||
from yarl import URL
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import BindStatus, create_or_update_bind, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import Avatar, People
|
||||
from ...utils.screenshot import screenshot
|
||||
@@ -43,7 +46,7 @@ alc.shortcut(
|
||||
|
||||
|
||||
@alc.assign('TETRIO.bind')
|
||||
async def _(nb_user: User, account: Player, event_session: EventSession, bot_info: UserInfo = BotUserInfo()): # noqa: B008
|
||||
async def _(nb_user: User, account: Player, event_session: Uninfo, interface: QryItrface):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -65,7 +68,7 @@ async def _(nb_user: User, account: Player, event_session: EventSession, bot_inf
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
status='unknown',
|
||||
type='unknown',
|
||||
user=People(
|
||||
avatar=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}')
|
||||
@@ -76,10 +79,18 @@ async def _(nb_user: User, account: Player, event_session: EventSession, bot_inf
|
||||
name=user.name.upper(),
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(bot_info, 'Data URI', '../../static/logo/logo.svg'),
|
||||
name=bot_info.user_name,
|
||||
avatar=await get_avatar(
|
||||
(
|
||||
bot_user := await interface.get_user(event_session.self_id)
|
||||
or UninfoUser(id=event_session.self_id)
|
||||
),
|
||||
'Data URI',
|
||||
'../../static/logo/logo.svg',
|
||||
),
|
||||
name=bot_user.nick or bot_user.name or choice(list(global_config.nickname) or ['bot']),
|
||||
),
|
||||
command='io查我',
|
||||
prompt='io查我',
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -2,8 +2,8 @@ from arclet.alconna import Arg
|
||||
from nonebot_plugin_alconna import Option, Subcommand
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import async_scoped_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from sqlalchemy import select
|
||||
|
||||
@@ -11,7 +11,7 @@ from ...db import trigger
|
||||
from . import alc, command
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TETRIOUserConfig
|
||||
from .typing import Template
|
||||
from .typedefs import Template
|
||||
|
||||
command.add(
|
||||
Subcommand(
|
||||
@@ -34,7 +34,7 @@ alc.shortcut(
|
||||
|
||||
|
||||
@alc.assign('TETRIO.config')
|
||||
async def _(user: User, session: async_scoped_session, event_session: EventSession, template: Template):
|
||||
async def _(user: User, session: async_scoped_session, event_session: Uninfo, template: Template):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from re import compile
|
||||
from re import compile # noqa: A004
|
||||
from typing import Literal
|
||||
|
||||
from yarl import URL
|
||||
|
||||
from .api.typing import ValidRank
|
||||
from .api.typedefs import ValidRank
|
||||
|
||||
GAME_TYPE: Literal['IO'] = 'IO'
|
||||
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
from nonebot_plugin_alconna import Args, Option, Subcommand
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
|
||||
from ...db import trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.metrics import get_metrics
|
||||
from ...utils.render import render
|
||||
from ...utils.render.schemas.tetrio.user.list_v2 import List, TetraLeague, User
|
||||
from ...utils.render.schemas.v2.tetrio.user.list import Data, List, TetraLeague, User
|
||||
from ...utils.screenshot import screenshot
|
||||
from .. import alc
|
||||
from . import command
|
||||
from .api.leaderboards import by
|
||||
from .api.schemas.base import P
|
||||
from .api.schemas.leaderboards import Parameter
|
||||
from .api.schemas.leaderboards.by import Entry
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
command.add(
|
||||
@@ -30,7 +32,7 @@ command.add(
|
||||
|
||||
@alc.assign('TETRIO.list')
|
||||
async def _(
|
||||
event_session: EventSession,
|
||||
event_session: Uninfo,
|
||||
max_tr: float | None = None,
|
||||
min_tr: float | None = None,
|
||||
limit: int | None = None,
|
||||
@@ -62,12 +64,15 @@ async def _(
|
||||
'v2/tetrio/user/list',
|
||||
List(
|
||||
show_index=True,
|
||||
users=[
|
||||
User(
|
||||
id=i.id,
|
||||
name=i.username.upper(),
|
||||
avatar=f'https://tetr.io/user-content/avatars/{i.id}.jpg',
|
||||
country=i.country,
|
||||
data=[
|
||||
Data(
|
||||
user=User(
|
||||
id=i.id,
|
||||
name=i.username.upper(),
|
||||
avatar=f'https://tetr.io/user-content/avatars/{i.id}.jpg',
|
||||
country=i.country,
|
||||
xp=i.xp,
|
||||
),
|
||||
tetra_league=TetraLeague(
|
||||
rank=i.league.rank,
|
||||
tr=round(i.league.tr, 2),
|
||||
@@ -80,11 +85,11 @@ async def _(
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
),
|
||||
xp=i.xp,
|
||||
join_at=None,
|
||||
)
|
||||
for i in league.data.entries
|
||||
if isinstance(i, Entry)
|
||||
],
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -7,16 +7,20 @@ from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column, relationshi
|
||||
|
||||
from ...db.models import PydanticType
|
||||
from .api.schemas.leaderboards.by import BySuccessModel, Entry
|
||||
from .api.typing import ValidRank
|
||||
from .typing import Template
|
||||
from .api.typedefs import ValidRank
|
||||
from .typedefs import Template
|
||||
|
||||
|
||||
class TETRIOUserConfig(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_u_cfg'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
query_template: Mapped[Template] = mapped_column(String(2))
|
||||
|
||||
|
||||
class TETRIOLeagueStats(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_tl_stats'
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
raw: Mapped[list['TETRIOLeagueHistorical']] = relationship(back_populates='stats', lazy='noload')
|
||||
fields: Mapped[list['TETRIOLeagueStatsField']] = relationship(back_populates='stats')
|
||||
@@ -24,11 +28,13 @@ class TETRIOLeagueStats(MappedAsDataclass, Model):
|
||||
|
||||
|
||||
class TETRIOLeagueHistorical(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_tl_hist'
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
request_id: Mapped[UUID] = mapped_column(index=True)
|
||||
data: Mapped[BySuccessModel] = mapped_column(PydanticType([], {BySuccessModel}))
|
||||
update_time: Mapped[datetime] = mapped_column(DateTime, index=True)
|
||||
stats_id: Mapped[int] = mapped_column(ForeignKey('nonebot_plugin_tetris_stats_tetrioleaguestats.id'), init=False)
|
||||
stats_id: Mapped[int] = mapped_column(ForeignKey('nb_t_io_tl_stats.id'), init=False)
|
||||
stats: Mapped['TETRIOLeagueStats'] = relationship(back_populates='raw')
|
||||
|
||||
|
||||
@@ -36,6 +42,8 @@ entry_type = PydanticType([], {Entry})
|
||||
|
||||
|
||||
class TETRIOLeagueStatsField(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_tl_stats_field'
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
rank: Mapped[ValidRank] = mapped_column(String(2), index=True)
|
||||
tr_line: Mapped[float]
|
||||
@@ -49,5 +57,5 @@ class TETRIOLeagueStatsField(MappedAsDataclass, Model):
|
||||
high_pps: Mapped[Entry] = mapped_column(entry_type)
|
||||
high_apm: Mapped[Entry] = mapped_column(entry_type)
|
||||
high_vs: Mapped[Entry] = mapped_column(entry_type)
|
||||
stats_id: Mapped[int] = mapped_column(ForeignKey('nonebot_plugin_tetris_stats_tetrioleaguestats.id'), init=False)
|
||||
stats_id: Mapped[int] = mapped_column(ForeignKey('nb_t_io_tl_stats.id'), init=False)
|
||||
stats: Mapped['TETRIOLeagueStats'] = relationship(back_populates='fields')
|
||||
|
||||
@@ -7,8 +7,8 @@ from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import Args, At, Option, Subcommand
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User as NBUser
|
||||
from nonebot_plugin_user import get_user
|
||||
from sqlalchemy import select
|
||||
@@ -16,13 +16,13 @@ from sqlalchemy import select
|
||||
from ....db import query_bind_info, trigger
|
||||
from ....i18n import Lang
|
||||
from ....utils.exception import FallbackError
|
||||
from ....utils.typing import Me
|
||||
from ....utils.typedefs import Me
|
||||
from ... import add_block_handlers, alc
|
||||
from .. import command, get_player
|
||||
from ..api import Player
|
||||
from ..constant import GAME_TYPE
|
||||
from ..models import TETRIOUserConfig
|
||||
from ..typing import Template
|
||||
from ..typedefs import Template
|
||||
from .v1 import make_query_image_v1
|
||||
from .v2 import make_query_image_v2
|
||||
|
||||
@@ -90,7 +90,7 @@ async def _( # noqa: PLR0913
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_session: Uninfo,
|
||||
template: Template | None = None,
|
||||
):
|
||||
async with trigger(
|
||||
@@ -103,7 +103,7 @@ async def _( # noqa: PLR0913
|
||||
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()
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
@@ -120,7 +120,7 @@ async def _( # noqa: PLR0913
|
||||
|
||||
|
||||
@alc.assign('TETRIO.query')
|
||||
async def _(user: NBUser, account: Player, event_session: EventSession, template: Template | None = None):
|
||||
async def _(user: NBUser, account: Player, event_session: Uninfo, template: Template | None = None):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
|
||||
@@ -4,22 +4,22 @@ from typing import TypeVar, overload
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from ....utils.exception import FallbackError
|
||||
from ....utils.render.schemas.tetrio.user.base import TetraLeagueHistoryData
|
||||
from ....utils.render.schemas.base import HistoryData
|
||||
from ..api.schemas.labs.leagueflow import Empty, LeagueFlowSuccess
|
||||
from ..api.schemas.summaries.league import InvalidData, LeagueSuccessModel, NeverPlayedData, NeverRatedData, RatedData
|
||||
|
||||
|
||||
def flow_to_history(
|
||||
leagueflow: LeagueFlowSuccess,
|
||||
handle: Callable[[list[TetraLeagueHistoryData]], list[TetraLeagueHistoryData]] | None = None,
|
||||
) -> list[TetraLeagueHistoryData]:
|
||||
handle: Callable[[list[HistoryData]], list[HistoryData]] | None = None,
|
||||
) -> list[HistoryData]:
|
||||
if isinstance(leagueflow.data, Empty):
|
||||
raise FallbackError
|
||||
start_time = leagueflow.data.start_time.astimezone(ZoneInfo('Asia/Shanghai'))
|
||||
ret = [
|
||||
TetraLeagueHistoryData(
|
||||
HistoryData(
|
||||
record_at=start_time + timedelta(milliseconds=i.timestamp_offset),
|
||||
tr=i.post_match_tr,
|
||||
score=i.post_match_tr,
|
||||
)
|
||||
for i in leagueflow.data.points
|
||||
if start_time + timedelta(milliseconds=i.timestamp_offset)
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
from asyncio import gather
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import timedelta
|
||||
from hashlib import md5
|
||||
from math import ceil, floor
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from yarl import URL
|
||||
|
||||
from ....utils.exception import FallbackError, WhatTheFuckError
|
||||
from ....utils.chart import get_split, get_value_bounds, handle_history_data
|
||||
from ....utils.exception import FallbackError
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.base import Avatar, Ranking
|
||||
from ....utils.render.schemas.tetrio.user.base import TetraLeagueHistoryData
|
||||
from ....utils.render.schemas.tetrio.user.info_v1 import Info, Radar, TetraLeague, TetraLeagueHistory, User
|
||||
from ....utils.render.schemas.base import Avatar, Trending
|
||||
from ....utils.render.schemas.v1.base import History
|
||||
from ....utils.render.schemas.v1.tetrio.user.info import Info, Multiplayer, Singleplayer, User
|
||||
from ....utils.screenshot import screenshot
|
||||
from ..api import Player
|
||||
from ..api.schemas.summaries.league import RatedData
|
||||
@@ -19,109 +20,6 @@ from ..constant import TR_MAX, TR_MIN
|
||||
from .tools import flow_to_history, get_league_data
|
||||
|
||||
|
||||
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: TetraLeagueHistoryData,
|
||||
behind_point: TetraLeagueHistoryData,
|
||||
point_time: datetime,
|
||||
) -> TetraLeagueHistoryData:
|
||||
"""根据给出的 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 TetraLeagueHistoryData(
|
||||
record_at=point_time,
|
||||
tr=previous_point.tr + slope * (datetime.timestamp(point_time) - datetime.timestamp(previous_point.record_at)),
|
||||
)
|
||||
|
||||
|
||||
def handle_history_data(data: list[TetraLeagueHistoryData]) -> list[TetraLeagueHistoryData]: # noqa: C901, PLR0912
|
||||
# 按照 记录时间 对数据进行排序
|
||||
data.sort(key=lambda x: x.record_at)
|
||||
|
||||
# 定义时间边界, 右边界为当前时间的当天零点, 左边界为右边界前推9天
|
||||
# 返回值的[0]和[-1]分别应满足left_border和right_border
|
||||
zero = datetime.now(ZoneInfo('Asia/Shanghai')).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
left_border = zero - timedelta(days=9)
|
||||
right_border = zero.replace(microsecond=1000)
|
||||
|
||||
lefts: list[TetraLeagueHistoryData] = []
|
||||
in_border: list[TetraLeagueHistoryData] = []
|
||||
rights: list[TetraLeagueHistoryData] = []
|
||||
|
||||
# 根据 记录时间 将数据分类到对应的列表中
|
||||
for i in data:
|
||||
if i.record_at < left_border:
|
||||
lefts.append(i)
|
||||
elif i.record_at < right_border:
|
||||
in_border.append(i)
|
||||
else:
|
||||
rights.append(i)
|
||||
|
||||
ret: list[TetraLeagueHistoryData] = []
|
||||
|
||||
# 处理左边界的点
|
||||
if lefts and in_border: # 如果边界左侧和边界内都有值则推算
|
||||
ret.append(get_specified_point(lefts[-1], in_border[0], left_border))
|
||||
elif lefts and not in_border: # 如果边界左侧有值但是边界内没有值则直接取左侧的最后一个值
|
||||
ret.append(TetraLeagueHistoryData(tr=lefts[-1].tr, record_at=left_border))
|
||||
elif not lefts and in_border: # 如果边界左侧没有值但是边界内有值则直接取边界内的第一个值
|
||||
ret.append(TetraLeagueHistoryData(tr=in_border[0].tr, record_at=left_border))
|
||||
elif not lefts and not in_border and rights: # 如果边界左侧和边界内都没有值但是边界右侧有值则直接取边界右侧的第一个值 # fmt: skip
|
||||
ret.append(TetraLeagueHistoryData(tr=rights[0].tr, record_at=left_border))
|
||||
else: # 暂时没想到其他情况
|
||||
raise WhatTheFuckError
|
||||
|
||||
# 添加边界内数据
|
||||
ret.extend(in_border)
|
||||
|
||||
# 处理右边界的点
|
||||
if in_border and rights: # 如果边界内和边界右侧都有值则推算
|
||||
ret.append(get_specified_point(in_border[-1], rights[0], right_border))
|
||||
elif not in_border and rights: # 如果边界内没有值但是边界右侧有值则直接取右侧的第一个值
|
||||
ret.append(TetraLeagueHistoryData(tr=rights[0].tr, record_at=right_border))
|
||||
elif in_border and not rights: # 如果边界内有值但是边界右侧没有值则直接取边界内的最后一个值
|
||||
ret.append(TetraLeagueHistoryData(tr=in_border[-1].tr, record_at=right_border))
|
||||
elif not in_border and not rights and lefts: # 如果边界内和边界右侧都没有值但是边界左侧有值则直接取边界左侧的最后一个值 # fmt: skip
|
||||
ret.append(TetraLeagueHistoryData(tr=lefts[-1].tr, record_at=right_border))
|
||||
else: # 暂时没想到其他情况
|
||||
raise WhatTheFuckError
|
||||
return ret
|
||||
|
||||
|
||||
async def make_query_image_v1(player: Player) -> bytes:
|
||||
(
|
||||
(user, user_info, league, sprint, blitz, leagueflow),
|
||||
@@ -134,8 +32,8 @@ async def make_query_image_v1(player: Player) -> bytes:
|
||||
if league_data.vs is None:
|
||||
raise FallbackError
|
||||
histories = flow_to_history(leagueflow, handle_history_data)
|
||||
value_max, value_min = get_value_bounds([i.tr for i in histories])
|
||||
split_value, offset = get_split(value_max, value_min)
|
||||
values = get_value_bounds([i.score for i in histories])
|
||||
split_value, offset = get_split(values, TR_MAX, TR_MIN)
|
||||
if sprint.data.record is not None:
|
||||
duration = timedelta(milliseconds=sprint.data.record.results.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
|
||||
@@ -143,6 +41,9 @@ async def make_query_image_v1(player: Player) -> bytes:
|
||||
sprint_value = 'N/A'
|
||||
blitz_value = f'{blitz.data.record.results.stats.score:,}' if blitz.data.record is not None else 'N/A'
|
||||
netloc = get_self_netloc()
|
||||
dsps: float
|
||||
dspp: float
|
||||
# make mypy happy
|
||||
async with HostPage(
|
||||
page=await render(
|
||||
'v1/tetrio/info',
|
||||
@@ -159,38 +60,40 @@ async def make_query_image_v1(player: Player) -> bytes:
|
||||
name=user.name.upper(),
|
||||
bio=user_info.data.bio,
|
||||
),
|
||||
ranking=Ranking(
|
||||
rating=round(league_data.glicko, 2),
|
||||
multiplayer=Multiplayer(
|
||||
glicko=f'{round(league_data.glicko, 2):,}',
|
||||
rd=round(league_data.rd, 2),
|
||||
),
|
||||
tetra_league=TetraLeague(
|
||||
rank=league_data.rank,
|
||||
tr=round(league_data.tr, 2),
|
||||
tr=f'{round(league_data.tr, 2):,}',
|
||||
global_rank=league_data.standing,
|
||||
pps=league_data.pps,
|
||||
lpm=round(lpm := (league_data.pps * 24), 2),
|
||||
apm=league_data.apm,
|
||||
apl=round(league_data.apm / lpm, 2),
|
||||
vs=league_data.vs,
|
||||
adpm=round(adpm := (league_data.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(
|
||||
history=History(
|
||||
data=histories,
|
||||
split_interval=split_value,
|
||||
min_value=values.value_min,
|
||||
max_value=values.value_max,
|
||||
offset=offset,
|
||||
),
|
||||
lpm=(metrics := get_metrics(pps=league_data.pps, apm=league_data.apm, vs=league_data.vs)).lpm,
|
||||
pps=metrics.pps,
|
||||
lpm_trending=Trending.KEEP,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
apm_trending=Trending.KEEP,
|
||||
adpm=metrics.adpm,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
adpm_trending=Trending.KEEP,
|
||||
app=(app := (league_data.apm / (60 * league_data.pps))),
|
||||
dsps=(dsps := ((league_data.vs / 100) - (league_data.apm / 60))),
|
||||
dspp=(dspp := (dsps / league_data.pps)),
|
||||
ci=150 * dspp - 125 * app + 50 * (league_data.vs / league_data.apm) - 25,
|
||||
ge=2 * ((app * dsps) / league_data.pps),
|
||||
),
|
||||
sprint=sprint_value,
|
||||
blitz=blitz_value,
|
||||
singleplayer=Singleplayer(
|
||||
sprint=sprint_value,
|
||||
blitz=blitz_value,
|
||||
),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -6,11 +6,14 @@ from yarl import URL
|
||||
|
||||
from ....utils.exception import FallbackError
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.base import Avatar
|
||||
from ....utils.render.schemas.tetrio.user.info_v2 import (
|
||||
from ....utils.render.schemas.v2.tetrio.user.info import (
|
||||
Achievement,
|
||||
Badge,
|
||||
Best,
|
||||
Blitz,
|
||||
Info,
|
||||
Sprint,
|
||||
@@ -18,7 +21,9 @@ from ....utils.render.schemas.tetrio.user.info_v2 import (
|
||||
TetraLeague,
|
||||
TetraLeagueStatistic,
|
||||
User,
|
||||
Week,
|
||||
Zen,
|
||||
Zenith,
|
||||
)
|
||||
from ....utils.screenshot import screenshot
|
||||
from ..api import Player
|
||||
@@ -29,10 +34,24 @@ from .tools import flow_to_history, handling_special_value
|
||||
async def make_query_image_v2(player: Player) -> bytes:
|
||||
(
|
||||
(user, user_info, league, sprint, blitz, zen),
|
||||
(avatar_revision, banner_revision, leagueflow),
|
||||
(avatar_revision, banner_revision, leagueflow, zenith, zenithex, achievements),
|
||||
) = await gather(
|
||||
gather(player.user, player.get_info(), player.league, player.sprint, player.blitz, player.zen),
|
||||
gather(player.avatar_revision, player.banner_revision, player.get_leagueflow()),
|
||||
gather(
|
||||
player.user,
|
||||
player.get_info(),
|
||||
player.league,
|
||||
player.sprint,
|
||||
player.blitz,
|
||||
player.zen,
|
||||
),
|
||||
gather(
|
||||
player.avatar_revision,
|
||||
player.banner_revision,
|
||||
player.get_leagueflow(),
|
||||
player.get_summaries('zenith'),
|
||||
player.get_summaries('zenithex'),
|
||||
player.get_summaries('achievements'),
|
||||
),
|
||||
)
|
||||
if sprint.data.record is not None:
|
||||
duration = timedelta(milliseconds=sprint.data.record.results.stats.finaltime).total_seconds()
|
||||
@@ -43,9 +62,9 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
play_time: str | None
|
||||
if (game_time := handling_special_value(user_info.data.gametime)) is not None:
|
||||
if game_time // 3600 > 0:
|
||||
play_time = f'{game_time//3600:.0f}h {game_time % 3600 // 60:.0f}m {game_time % 60:.0f}s'
|
||||
play_time = f'{game_time // 3600:.0f}h {game_time % 3600 // 60:.0f}m {game_time % 60:.0f}s'
|
||||
elif game_time // 60 > 0:
|
||||
play_time = f'{game_time//60:.0f}m {game_time % 60:.0f}s'
|
||||
play_time = f'{game_time // 60:.0f}m {game_time % 60:.0f}s'
|
||||
else:
|
||||
play_time = f'{game_time:.0f}s'
|
||||
else:
|
||||
@@ -62,12 +81,9 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
bio=user_info.data.bio,
|
||||
banner=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/banners/{user.ID}') % {'revision': banner_revision}
|
||||
)
|
||||
if banner_revision is not None and banner_revision != 0
|
||||
else None,
|
||||
country=user_info.data.country,
|
||||
role=user_info.data.role,
|
||||
botmaster=user_info.data.botmaster,
|
||||
avatar=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}') % {'revision': avatar_revision}
|
||||
)
|
||||
@@ -76,6 +92,15 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
type='identicon',
|
||||
hash=md5(user.ID.encode()).hexdigest(), # noqa: S324
|
||||
),
|
||||
banner=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/banners/{user.ID}') % {'revision': banner_revision}
|
||||
)
|
||||
if banner_revision is not None and banner_revision != 0
|
||||
else None,
|
||||
bio=user_info.data.bio,
|
||||
friend_count=user_info.data.friend_count,
|
||||
supporter_tier=user_info.data.supporter_tier,
|
||||
bad_standing=user_info.data.badstanding or False,
|
||||
badges=[
|
||||
Badge(
|
||||
id=i.id,
|
||||
@@ -85,12 +110,22 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
)
|
||||
for i in user_info.data.badges
|
||||
],
|
||||
country=user_info.data.country,
|
||||
role=user_info.data.role,
|
||||
xp=user_info.data.xp,
|
||||
friend_count=user_info.data.friend_count,
|
||||
supporter_tier=user_info.data.supporter_tier,
|
||||
bad_standing=user_info.data.badstanding or False,
|
||||
ar=user_info.data.ar,
|
||||
achievements=[
|
||||
Achievement(
|
||||
key=i.achievement_id,
|
||||
rank_type=i.rank_type,
|
||||
ar_type=i.ar_type,
|
||||
stub=i.stub,
|
||||
rank=i.rank,
|
||||
achieved_score=i.achieved_score,
|
||||
pos=i.pos,
|
||||
progress=i.progress,
|
||||
total=i.total,
|
||||
)
|
||||
for i in achievements.data
|
||||
],
|
||||
playtime=play_time,
|
||||
join_at=user_info.data.ts,
|
||||
),
|
||||
@@ -113,6 +148,40 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
)
|
||||
if not isinstance(league.data, NeverPlayedData | InvalidData)
|
||||
else None,
|
||||
zenith=Zenith(
|
||||
week=Week(
|
||||
altitude=zenith.data.record.results.stats.zenith.altitude,
|
||||
global_rank=zenith.data.rank,
|
||||
country_rank=zenith.data.rank_local,
|
||||
play_at=zenith.data.record.ts,
|
||||
)
|
||||
if zenith.data.record is not None
|
||||
else None,
|
||||
best=Best(
|
||||
altitude=zenith.data.best.record.results.stats.zenith.altitude,
|
||||
global_rank=zenith.data.best.rank,
|
||||
play_at=zenith.data.best.record.ts,
|
||||
)
|
||||
if zenith.data.best.record is not None
|
||||
else None,
|
||||
),
|
||||
zenithex=Zenith(
|
||||
week=Week(
|
||||
altitude=zenithex.data.record.results.stats.zenith.altitude,
|
||||
global_rank=zenithex.data.rank,
|
||||
country_rank=zenithex.data.rank_local,
|
||||
play_at=zenithex.data.record.ts,
|
||||
)
|
||||
if zenithex.data.record is not None
|
||||
else None,
|
||||
best=Best(
|
||||
altitude=zenithex.data.best.record.results.stats.zenith.altitude,
|
||||
global_rank=zenithex.data.best.rank,
|
||||
play_at=zenithex.data.best.record.ts,
|
||||
)
|
||||
if zenithex.data.best.record is not None
|
||||
else None,
|
||||
),
|
||||
statistic=Statistic(
|
||||
total=handling_special_value(user_info.data.gamesplayed),
|
||||
wins=handling_special_value(user_info.data.gameswon),
|
||||
@@ -120,6 +189,7 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
sprint=Sprint(
|
||||
time=sprint_value,
|
||||
global_rank=sprint.data.rank,
|
||||
country_rank=sprint.data.rank_local,
|
||||
play_at=sprint.data.record.ts,
|
||||
)
|
||||
if sprint.data.record is not None
|
||||
@@ -127,11 +197,13 @@ async def make_query_image_v2(player: Player) -> bytes:
|
||||
blitz=Blitz(
|
||||
score=blitz.data.record.results.stats.score,
|
||||
global_rank=blitz.data.rank,
|
||||
country_rank=blitz.data.rank_local,
|
||||
play_at=blitz.data.record.ts,
|
||||
)
|
||||
if blitz.data.record is not None
|
||||
else None,
|
||||
zen=Zen(level=zen.data.level, score=zen.data.score),
|
||||
lang=get_lang(),
|
||||
),
|
||||
),
|
||||
) as page_hash:
|
||||
|
||||
@@ -12,6 +12,7 @@ from nonebot_plugin_apscheduler import scheduler
|
||||
from nonebot_plugin_orm import get_session
|
||||
from sqlalchemy import select
|
||||
|
||||
from ....config.config import config
|
||||
from ....utils.exception import RequestError
|
||||
from ....utils.retry import retry
|
||||
from .. import alc
|
||||
@@ -25,7 +26,7 @@ from ..models import TETRIOLeagueHistorical, TETRIOLeagueStats, TETRIOLeagueStat
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..api.schemas.leaderboards.by import BySuccessModel
|
||||
from ..api.typing import Rank
|
||||
from ..api.typedefs import Rank
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
@@ -95,7 +96,7 @@ async def get_tetra_league_data() -> None:
|
||||
|
||||
players: list[Entry] = []
|
||||
for result in results:
|
||||
players.extend(result.data.entries)
|
||||
players.extend([i for i in result.data.entries if isinstance(i, Entry)])
|
||||
players.sort(key=lambda x: x.league.tr, reverse=True)
|
||||
|
||||
rank_player_mapping: defaultdict[Rank, list[Entry]] = defaultdict(list)
|
||||
@@ -136,17 +137,19 @@ async def get_tetra_league_data() -> None:
|
||||
await session.commit()
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def _() -> None:
|
||||
async with get_session() as session:
|
||||
latest_time = await session.scalar(
|
||||
select(TETRIOLeagueStats.update_time).order_by(TETRIOLeagueStats.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()
|
||||
if not config.tetris.development:
|
||||
|
||||
@driver.on_startup
|
||||
async def _() -> None:
|
||||
async with get_session() as session:
|
||||
latest_time = await session.scalar(
|
||||
select(TETRIOLeagueStats.update_time).order_by(TETRIOLeagueStats.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()
|
||||
|
||||
|
||||
from . import all, detail # noqa: E402
|
||||
from . import all, detail # noqa: A004, E402
|
||||
|
||||
base_command.add(command)
|
||||
|
||||
|
||||
@@ -3,25 +3,26 @@ from datetime import timedelta
|
||||
from arclet.alconna import Arg
|
||||
from nonebot_plugin_alconna import Option, Subcommand, UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from ....db import trigger
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.tetrio.rank.v1 import Data as DataV1
|
||||
from ....utils.render.schemas.tetrio.rank.v1 import ItemData as ItemDataV1
|
||||
from ....utils.render.schemas.tetrio.rank.v2 import AverageData as AverageDataV2
|
||||
from ....utils.render.schemas.tetrio.rank.v2 import Data as DataV2
|
||||
from ....utils.render.schemas.tetrio.rank.v2 import ItemData as ItemDataV2
|
||||
from ....utils.render.schemas.v1.tetrio.rank import Data as DataV1
|
||||
from ....utils.render.schemas.v1.tetrio.rank import ItemData as ItemDataV1
|
||||
from ....utils.render.schemas.v2.tetrio.rank import AverageData as AverageDataV2
|
||||
from ....utils.render.schemas.v2.tetrio.rank import Data as DataV2
|
||||
from ....utils.render.schemas.v2.tetrio.rank import ItemData as ItemDataV2
|
||||
from ....utils.screenshot import screenshot
|
||||
from .. import alc
|
||||
from ..constant import GAME_TYPE
|
||||
from ..models import TETRIOLeagueStats
|
||||
from ..typing import Template
|
||||
from ..typedefs import Template
|
||||
from . import command
|
||||
|
||||
command.add(
|
||||
@@ -32,7 +33,7 @@ command.add(
|
||||
|
||||
|
||||
@alc.assign('TETRIO.rank.all')
|
||||
async def _(event_session: EventSession, template: Template | None = None):
|
||||
async def _(event_session: Uninfo, template: Template | None = None):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -82,6 +83,7 @@ async def make_image_v1(latest_data: TETRIOLeagueStats, compare_data: TETRIOLeag
|
||||
for i in zip(latest_data.fields, compare_data.fields, strict=True)
|
||||
},
|
||||
updated_at=latest_data.update_time,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
@@ -109,6 +111,7 @@ async def make_image_v2(latest_data: TETRIOLeagueStats, compare_data: TETRIOLeag
|
||||
for i in zip(latest_data.fields, compare_data.fields, strict=True)
|
||||
},
|
||||
updated_at=latest_data.update_time,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -5,19 +5,20 @@ from arclet.alconna import Arg
|
||||
from nonebot import get_driver
|
||||
from nonebot_plugin_alconna import Option, UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from ....db import trigger
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.tetrio.rank.detail import Data, SpecialData
|
||||
from ....utils.render.schemas.v2.tetrio.rank.detail import Data, SpecialData
|
||||
from ....utils.screenshot import screenshot
|
||||
from .. import alc
|
||||
from ..api.typing import ValidRank
|
||||
from ..api.typedefs import ValidRank
|
||||
from ..constant import GAME_TYPE
|
||||
from ..models import TETRIOLeagueStats
|
||||
from . import command
|
||||
@@ -30,7 +31,7 @@ command.add(Option('--detail', Arg('rank', ValidRank), alias=['-D']))
|
||||
|
||||
|
||||
@alc.assign('TETRIO.rank')
|
||||
async def _(rank: ValidRank, event_session: EventSession):
|
||||
async def _(rank: ValidRank, event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -122,6 +123,7 @@ async def make_image(rank: ValidRank, latest: TETRIOLeagueStats, compare: TETRIO
|
||||
vs_holder=latest_data.high_vs.username.upper(),
|
||||
),
|
||||
updated_at=latest.update_time.replace(tzinfo=UTC).astimezone(ZoneInfo('Asia/Shanghai')),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot_plugin_alconna import Args, At, Subcommand
|
||||
|
||||
from ....utils.typing import Me
|
||||
from ....utils.typedefs import Me
|
||||
from .. import command as base_command
|
||||
from .. import get_player
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At, Option
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import get_user
|
||||
from yarl import URL
|
||||
|
||||
@@ -16,13 +16,14 @@ from ....db import query_bind_info, trigger
|
||||
from ....i18n import Lang
|
||||
from ....utils.exception import RecordNotFoundError
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.base import Avatar
|
||||
from ....utils.render.schemas.tetrio.record.base import Finesse, Max, Mini, Tspins, User
|
||||
from ....utils.render.schemas.tetrio.record.blitz import Record, Statistic
|
||||
from ....utils.render.schemas.v2.tetrio.record.base import Finesse, Max, Mini, Tspins, User
|
||||
from ....utils.render.schemas.v2.tetrio.record.blitz import Record, Statistic
|
||||
from ....utils.screenshot import screenshot
|
||||
from ....utils.typing import Me
|
||||
from ....utils.typedefs import Me
|
||||
from .. import alc
|
||||
from ..api.player import Player
|
||||
from ..constant import GAME_TYPE
|
||||
@@ -42,7 +43,7 @@ async def _(
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_session: Uninfo,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -54,7 +55,7 @@ async def _(
|
||||
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()
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
@@ -67,7 +68,7 @@ async def _(
|
||||
|
||||
|
||||
@alc.assign('TETRIO.record.blitz')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async def _(account: Player, event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -145,6 +146,7 @@ async def make_blitz_image(player: Player) -> bytes:
|
||||
level=stats.level,
|
||||
),
|
||||
play_at=blitz.data.record.ts,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -7,8 +7,8 @@ from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import At, Option
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import get_user
|
||||
from yarl import URL
|
||||
|
||||
@@ -16,13 +16,14 @@ from ....db import query_bind_info, trigger
|
||||
from ....i18n import Lang
|
||||
from ....utils.exception import RecordNotFoundError
|
||||
from ....utils.host import HostPage, get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render.schemas.base import Avatar
|
||||
from ....utils.render.schemas.tetrio.record.base import Finesse, Max, Mini, Statistic, Tspins, User
|
||||
from ....utils.render.schemas.tetrio.record.sprint import Record
|
||||
from ....utils.render.schemas.v2.tetrio.record.base import Finesse, Max, Mini, Statistic, Tspins, User
|
||||
from ....utils.render.schemas.v2.tetrio.record.sprint import Record
|
||||
from ....utils.screenshot import screenshot
|
||||
from ....utils.typing import Me
|
||||
from ....utils.typedefs import Me
|
||||
from .. import alc
|
||||
from ..api.player import Player
|
||||
from ..constant import GAME_TYPE
|
||||
@@ -42,7 +43,7 @@ async def _(
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_session: Uninfo,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -54,7 +55,7 @@ async def _(
|
||||
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()
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
@@ -67,7 +68,7 @@ async def _(
|
||||
|
||||
|
||||
@alc.assign('TETRIO.record.sprint')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async def _(account: Player, event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -90,7 +91,7 @@ async def make_sprint_image(player: Player) -> bytes:
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
page=await render(
|
||||
'v2/tetrio/record/40l',
|
||||
'v2/tetrio/record/sprint',
|
||||
Record(
|
||||
type='best',
|
||||
user=User(
|
||||
@@ -145,6 +146,7 @@ async def make_sprint_image(player: Player) -> bytes:
|
||||
),
|
||||
),
|
||||
play_at=sprint.data.record.ts,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
86
nonebot_plugin_tetris_stats/games/tetrio/unbind.py
Normal file
86
nonebot_plugin_tetris_stats/games/tetrio/unbind.py
Normal file
@@ -0,0 +1,86 @@
|
||||
from hashlib import md5
|
||||
from secrets import choice
|
||||
|
||||
from nonebot_plugin_alconna import Subcommand
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_uninfo import QryItrface, Uninfo
|
||||
from nonebot_plugin_uninfo import User as UninfoUser
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from nonebot_plugin_waiter import suggest # type: ignore[import-untyped]
|
||||
from yarl import URL
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import query_bind_info, remove_bind, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import Avatar, People
|
||||
from ...utils.screenshot import screenshot
|
||||
from . import alc, command
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
command.add(Subcommand('unbind', help_text='解除绑定 TETR.IO 账号'))
|
||||
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:解除绑定|解绑|unbind)',
|
||||
command='tstats TETR.IO unbind',
|
||||
humanized='io解绑',
|
||||
)
|
||||
|
||||
|
||||
@alc.assign('TETRIO.unbind')
|
||||
async def _(nb_user: User, event_session: Uninfo, interface: QryItrface):
|
||||
async with (
|
||||
trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='unbind',
|
||||
command_args=[],
|
||||
),
|
||||
get_session() as session,
|
||||
):
|
||||
if (bind := await query_bind_info(session=session, user=nb_user, game_platform=GAME_TYPE)) is None:
|
||||
await UniMessage('您还未绑定 TETR.IO 账号').finish()
|
||||
resp = await suggest('您确定要解绑吗?', ['是', '否'])
|
||||
if resp is None or resp.extract_plain_text() == '否':
|
||||
return
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
user = await player.user
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
type='unlink',
|
||||
user=People(
|
||||
avatar=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}')
|
||||
% {'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
|
||||
name=user.name.upper(),
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(
|
||||
(
|
||||
bot_user := await interface.get_user(event_session.self_id)
|
||||
or UninfoUser(id=event_session.self_id)
|
||||
),
|
||||
'Data URI',
|
||||
'../../static/logo/logo.svg',
|
||||
),
|
||||
name=bot_user.nick or bot_user.name or choice(list(global_config.nickname) or ['bot']),
|
||||
),
|
||||
prompt='io绑定{游戏ID}',
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(raw=await screenshot(f'http://{netloc}/host/{page_hash}.html')).send()
|
||||
await remove_bind(session=session, user=nb_user, game_platform=GAME_TYPE)
|
||||
@@ -2,7 +2,7 @@ from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot_plugin_alconna import Args, At, Subcommand
|
||||
|
||||
from ...utils.exception import MessageFormatError
|
||||
from ...utils.typing import Me
|
||||
from ...utils.typedefs import Me
|
||||
from .. import add_block_handlers, alc, command
|
||||
from .api import Player
|
||||
from .constant import USER_NAME
|
||||
@@ -29,6 +29,10 @@ command.add(
|
||||
),
|
||||
help_text='绑定 TOP 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'unbind',
|
||||
help_text='解除绑定 TOP 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
@@ -51,9 +55,22 @@ command.add(
|
||||
)
|
||||
)
|
||||
|
||||
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查'})
|
||||
alc.shortcut(
|
||||
'(?i:top)(?i:绑定|绑|bind)',
|
||||
command='tstats TOP bind',
|
||||
humanized='top绑定',
|
||||
)
|
||||
alc.shortcut(
|
||||
'(?i:top)(?i:解除绑定|解绑|unbind)',
|
||||
command='tstats TOP unbind',
|
||||
humanized='top解绑',
|
||||
)
|
||||
alc.shortcut(
|
||||
'(?i:top)(?i:查询|查|query|stats)',
|
||||
command='tstats TOP query',
|
||||
humanized='top查',
|
||||
)
|
||||
|
||||
add_block_handlers(alc.assign('TOP.query'))
|
||||
|
||||
from . import bind, query # noqa: E402, F401
|
||||
from . import bind, query, unbind # noqa: E402, F401
|
||||
|
||||
@@ -10,6 +10,8 @@ from .schemas.user_profile import UserProfile
|
||||
|
||||
|
||||
class TOPHistoricalData(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_top_hist_data'
|
||||
|
||||
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 Profile']] = mapped_column(String(16), index=True)
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
from secrets import choice
|
||||
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import QryItrface, Uninfo
|
||||
from nonebot_plugin_uninfo import User as UninfoUser
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from nonebot_plugin_userinfo import BotUserInfo, EventUserInfo, UserInfo
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import BindStatus, create_or_update_bind, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
@@ -17,13 +21,7 @@ from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('TOP.bind')
|
||||
async def _(
|
||||
nb_user: User,
|
||||
account: Player,
|
||||
event_session: EventSession,
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
bot_info: UserInfo = BotUserInfo(), # noqa: B008
|
||||
):
|
||||
async def _(nb_user: User, account: Player, event_session: Uninfo, interface: QryItrface):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -44,16 +42,28 @@ async def _(
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform=GAME_TYPE,
|
||||
status='unknown',
|
||||
type='unknown',
|
||||
user=People(
|
||||
avatar=await get_avatar(event_user_info, 'Data URI', None),
|
||||
avatar=await get_avatar(
|
||||
event_session.user,
|
||||
'Data URI',
|
||||
None,
|
||||
),
|
||||
name=user.user_name,
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(bot_info, 'Data URI', '../../static/logo/logo.svg'),
|
||||
name=bot_info.user_name,
|
||||
avatar=await get_avatar(
|
||||
(
|
||||
bot_user := await interface.get_user(event_session.self_id)
|
||||
or UninfoUser(id=event_session.self_id)
|
||||
),
|
||||
'Data URI',
|
||||
'../../static/logo/logo.svg',
|
||||
),
|
||||
name=bot_user.nick or bot_user.name or choice(list(global_config.nickname) or ['bot']),
|
||||
),
|
||||
command='top查我',
|
||||
prompt='top查我',
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from re import compile
|
||||
from re import compile # noqa: A004
|
||||
from typing import Literal
|
||||
|
||||
from yarl import URL
|
||||
|
||||
@@ -3,22 +3,23 @@ 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
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import get_user
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...i18n import Lang
|
||||
from ...utils.exception import FallbackError
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.metrics import TetrisMetricsBasicWithLPM, get_metrics
|
||||
from ...utils.render import render
|
||||
from ...utils.render.avatar import get_avatar
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.render.schemas.top_info import Data as InfoData
|
||||
from ...utils.render.schemas.top_info import Info
|
||||
from ...utils.render.schemas.base import People, Trending
|
||||
from ...utils.render.schemas.v1.top.info import Data as InfoData
|
||||
from ...utils.render.schemas.v1.top.info import Info
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.typing import Me
|
||||
from ...utils.typedefs import Me
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .api.schemas.user_profile import Data, UserProfile
|
||||
@@ -26,7 +27,7 @@ from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('TOP.query')
|
||||
async def _(event: Event, matcher: Matcher, target: At | Me, event_session: EventSession):
|
||||
async def _(event: Event, matcher: Matcher, target: At | Me, event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -37,7 +38,7 @@ async def _(event: Event, matcher: Matcher, target: At | Me, event_session: Even
|
||||
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()
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
@@ -50,7 +51,7 @@ async def _(event: Event, matcher: Matcher, target: At | Me, event_session: Even
|
||||
|
||||
|
||||
@alc.assign('TOP.query')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async def _(account: Player, event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -79,8 +80,23 @@ async def make_query_image(profile: UserProfile) -> bytes:
|
||||
'v1/top/info',
|
||||
Info(
|
||||
user=People(avatar=get_avatar(profile.user_name), name=profile.user_name),
|
||||
today=InfoData(pps=today.pps, lpm=today.lpm, apm=today.apm, apl=today.apl),
|
||||
history=InfoData(pps=history.pps, lpm=history.lpm, apm=history.apm, apl=history.apl),
|
||||
today=InfoData(
|
||||
pps=today.pps,
|
||||
lpm=today.lpm,
|
||||
lpm_trending=Trending.KEEP,
|
||||
apm=today.apm,
|
||||
apl=today.apl,
|
||||
apm_trending=Trending.KEEP,
|
||||
),
|
||||
historical=InfoData(
|
||||
pps=history.pps,
|
||||
lpm=history.lpm,
|
||||
lpm_trending=Trending.KEEP,
|
||||
apm=history.apm,
|
||||
apl=history.apl,
|
||||
apm_trending=Trending.KEEP,
|
||||
),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
78
nonebot_plugin_tetris_stats/games/top/unbind.py
Normal file
78
nonebot_plugin_tetris_stats/games/top/unbind.py
Normal file
@@ -0,0 +1,78 @@
|
||||
from secrets import choice
|
||||
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_uninfo import QryItrface, Uninfo
|
||||
from nonebot_plugin_uninfo import User as UninfoUser
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from nonebot_plugin_waiter import suggest # type: ignore[import-untyped]
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import query_bind_info, remove_bind, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('TOP.unbind')
|
||||
async def _(
|
||||
nb_user: User,
|
||||
event_session: Uninfo,
|
||||
interface: QryItrface,
|
||||
):
|
||||
async with (
|
||||
trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='unbind',
|
||||
command_args=[],
|
||||
),
|
||||
get_session() as session,
|
||||
):
|
||||
if (bind := await query_bind_info(session=session, user=nb_user, game_platform=GAME_TYPE)) is None:
|
||||
await UniMessage('您还未绑定 TOP 账号').finish()
|
||||
resp = await suggest('您确定要解绑吗?', ['是', '否'])
|
||||
if resp is None or resp.extract_plain_text() == '否':
|
||||
return
|
||||
player = Player(user_name=bind.game_account, trust=True)
|
||||
user = await player.user
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform='TOP',
|
||||
type='unlink',
|
||||
user=People(
|
||||
avatar=await get_avatar(
|
||||
event_session.user,
|
||||
'Data URI',
|
||||
None,
|
||||
),
|
||||
name=user.user_name,
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(
|
||||
(
|
||||
bot_user := await interface.get_user(event_session.self_id)
|
||||
or UninfoUser(id=event_session.self_id)
|
||||
),
|
||||
'Data URI',
|
||||
'../../static/logo/logo.svg',
|
||||
),
|
||||
name=bot_user.nick or bot_user.name or choice(list(global_config.nickname) or ['bot']),
|
||||
),
|
||||
prompt='top绑定{游戏ID}',
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(raw=await screenshot(f'http://{netloc}/host/{page_hash}.html')).send()
|
||||
await remove_bind(session=session, user=nb_user, game_platform=GAME_TYPE)
|
||||
@@ -2,7 +2,7 @@ from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot_plugin_alconna import Args, At, Subcommand
|
||||
|
||||
from ...utils.exception import MessageFormatError
|
||||
from ...utils.typing import Me
|
||||
from ...utils.typedefs import Me
|
||||
from .. import add_block_handlers, alc, command
|
||||
from .api import Player
|
||||
from .constant import USER_NAME
|
||||
@@ -34,6 +34,10 @@ command.add(
|
||||
),
|
||||
help_text='绑定 茶服 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'unbind',
|
||||
help_text='解除绑定 TOS 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
@@ -56,9 +60,22 @@ command.add(
|
||||
)
|
||||
)
|
||||
|
||||
alc.shortcut('(?i:tos|茶服)(?i:绑定|绑|bind)', {'command': 'tstats TOS bind', 'humanized': '茶服绑定'})
|
||||
alc.shortcut('(?i:tos|茶服)(?i:查询|查|query|stats)', {'command': 'tstats TOS query', 'humanized': '茶服查'})
|
||||
alc.shortcut(
|
||||
'(?i:tos|茶服)(?i:绑定|绑|bind)',
|
||||
command='tstats TOS bind',
|
||||
humanized='茶服绑定',
|
||||
)
|
||||
alc.shortcut(
|
||||
'(?i:tos|茶服)(?i:解除绑定|解绑|unbind)',
|
||||
command='tstats TOS unbind',
|
||||
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
|
||||
from . import bind, query, unbind # noqa: E402, F401
|
||||
|
||||
@@ -11,6 +11,8 @@ from .schemas.user_profile import UserProfile
|
||||
|
||||
|
||||
class TOSHistoricalData(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_tos_hist_data'
|
||||
|
||||
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 Profile']] = mapped_column(String(16), index=True)
|
||||
|
||||
@@ -64,7 +64,7 @@ class Player:
|
||||
query = {'teaId': self.teaid}
|
||||
else:
|
||||
path = 'getUsernameInfo'
|
||||
query = {'username': cast(str, self.user_name)}
|
||||
query = {'username': cast('str', self.user_name)}
|
||||
raw_user_info = await request.failover_request(
|
||||
[i / path % query for i in BASE_URL], failover_code=[502], failover_exc=(TimeoutException,)
|
||||
)
|
||||
@@ -91,7 +91,7 @@ class Player:
|
||||
if self._user_profile.get(params) is None:
|
||||
raw_user_profile = await request.failover_request(
|
||||
[
|
||||
i / 'getProfile' % {'id': self.teaid or cast(str, self.user_name), **other_parameter}
|
||||
i / 'getProfile' % {'id': self.teaid or cast('str', self.user_name), **other_parameter}
|
||||
for i in BASE_URL
|
||||
],
|
||||
failover_code=[502],
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
from secrets import choice
|
||||
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import EventSession
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import QryItrface, Uninfo
|
||||
from nonebot_plugin_uninfo import User as UninfoUser
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from nonebot_plugin_userinfo import BotUserInfo, EventUserInfo, UserInfo
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import BindStatus, create_or_update_bind, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
@@ -20,9 +24,8 @@ from .constant import GAME_TYPE
|
||||
async def _(
|
||||
nb_user: User,
|
||||
account: Player,
|
||||
event_session: EventSession,
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
bot_info: UserInfo = BotUserInfo(), # noqa: B008
|
||||
event_session: Uninfo,
|
||||
interface: QryItrface,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -45,15 +48,28 @@ async def _(
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform=GAME_TYPE,
|
||||
status='unknown',
|
||||
type='unknown',
|
||||
user=People(
|
||||
avatar=await get_avatar(event_user_info, 'Data URI', None), name=user_info.data.name
|
||||
avatar=await get_avatar(
|
||||
event_session.user,
|
||||
'Data URI',
|
||||
None,
|
||||
),
|
||||
name=user_info.data.name,
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(bot_info, 'Data URI', '../../static/logo/logo.svg'),
|
||||
name=bot_info.user_remark or bot_info.user_displayname or bot_info.user_name,
|
||||
avatar=await get_avatar(
|
||||
(
|
||||
bot_user := await interface.get_user(event_session.self_id)
|
||||
or UninfoUser(id=event_session.self_id)
|
||||
),
|
||||
'Data URI',
|
||||
'../../static/logo/logo.svg',
|
||||
),
|
||||
name=bot_user.nick or bot_user.name or choice(list(global_config.nickname) or ['bot']),
|
||||
),
|
||||
command='茶服查我',
|
||||
prompt='茶服查我',
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from re import compile
|
||||
from re import compile # noqa: A004
|
||||
from typing import Literal
|
||||
|
||||
from yarl import URL
|
||||
|
||||
@@ -1,32 +1,38 @@
|
||||
from asyncio import gather
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from http import HTTPStatus
|
||||
from typing import Literal, NamedTuple
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
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
|
||||
from nonebot_plugin_session_orm import get_session_persist_id # type: ignore[import-untyped]
|
||||
from nonebot_plugin_uninfo import Uninfo, User
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import get_user
|
||||
from nonebot_plugin_userinfo import EventUserInfo, UserInfo
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...i18n import Lang
|
||||
from ...utils.chart import get_split, get_value_bounds, handle_history_data
|
||||
from ...utils.exception import RequestError
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.metrics import TetrisMetricsProWithLPMADPM, get_metrics
|
||||
from ...utils.render import render
|
||||
from ...utils.render.avatar import get_avatar as get_random_avatar
|
||||
from ...utils.render.schemas.base import People, Ranking
|
||||
from ...utils.render.schemas.tos_info import Info, Multiplayer, Radar
|
||||
from ...utils.render.schemas.base import HistoryData, People, Trending
|
||||
from ...utils.render.schemas.v1.base import History
|
||||
from ...utils.render.schemas.v1.tos.info import Info, Multiplayer, Singleplayer
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.typing import Me, Number
|
||||
from ...utils.time_it import time_it
|
||||
from ...utils.typedefs import Me, Number
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .api.models import TOSHistoricalData
|
||||
from .api.schemas.user_info import UserInfoSuccess
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
@@ -38,8 +44,7 @@ def add_special_handlers(
|
||||
async def _(
|
||||
event: Event,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
event_session: Uninfo,
|
||||
):
|
||||
if isinstance(event, match_event):
|
||||
async with trigger(
|
||||
@@ -59,7 +64,9 @@ def add_special_handlers(
|
||||
if game_data is not None:
|
||||
await UniMessage.image(
|
||||
raw=await make_query_image(
|
||||
user_info, game_data, None if isinstance(target, At) else event_user_info
|
||||
user_info,
|
||||
game_data,
|
||||
None if isinstance(target, At) else event_session.user,
|
||||
)
|
||||
).finish()
|
||||
await make_query_text(user_info, game_data).finish()
|
||||
@@ -105,8 +112,7 @@ async def _(
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
event_user_info: UserInfo = EventUserInfo(), # noqa: B008
|
||||
event_session: Uninfo,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
@@ -118,7 +124,7 @@ async def _(
|
||||
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()
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
@@ -132,7 +138,9 @@ async def _(
|
||||
message
|
||||
+ UniMessage.image(
|
||||
raw=await make_query_image(
|
||||
user_info, game_data, None if isinstance(target, At) else event_user_info
|
||||
user_info,
|
||||
game_data,
|
||||
None if isinstance(target, At) else event_session.user,
|
||||
)
|
||||
)
|
||||
).finish()
|
||||
@@ -140,7 +148,7 @@ async def _(
|
||||
|
||||
|
||||
@alc.assign('TOS.query')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async def _(account: Player, event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -148,6 +156,7 @@ async def _(account: Player, event_session: EventSession):
|
||||
command_args=[],
|
||||
):
|
||||
user_info, game_data = await gather(account.get_info(), get_game_data(account))
|
||||
await get_historical_data(user_info.data.teaid)
|
||||
if game_data is not None:
|
||||
await UniMessage.image(raw=await make_query_image(user_info, game_data, None)).finish()
|
||||
await make_query_text(user_info, game_data).finish()
|
||||
@@ -156,7 +165,7 @@ async def _(account: Player, event_session: EventSession):
|
||||
class GameData(NamedTuple):
|
||||
game_num: int
|
||||
metrics: TetrisMetricsProWithLPMADPM
|
||||
OR: Number
|
||||
or_: Number
|
||||
dspp: Number
|
||||
ge: Number
|
||||
|
||||
@@ -199,13 +208,50 @@ async def get_game_data(player: Player, query_num: int = 50) -> GameData | None:
|
||||
return GameData(
|
||||
game_num=num,
|
||||
metrics=metrics,
|
||||
OR=total_offset / total_receive * 100,
|
||||
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 | None) -> bytes:
|
||||
@time_it
|
||||
async def get_historical_data(unique_identifier: str) -> list[HistoryData]:
|
||||
async with get_session() as session:
|
||||
user_infos = (
|
||||
await session.scalars(
|
||||
select(TOSHistoricalData)
|
||||
.where(TOSHistoricalData.user_unique_identifier == unique_identifier)
|
||||
.where(TOSHistoricalData.api_type == 'User Info')
|
||||
.where(
|
||||
TOSHistoricalData.update_time
|
||||
> (
|
||||
datetime.now(ZoneInfo('Asia/Shanghai')).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
- timedelta(days=9)
|
||||
).replace(tzinfo=timezone.utc)
|
||||
)
|
||||
.order_by(TOSHistoricalData.id.asc())
|
||||
)
|
||||
).all()
|
||||
if user_infos:
|
||||
extra_info = (
|
||||
await session.scalars(
|
||||
select(TOSHistoricalData)
|
||||
.where(TOSHistoricalData.id < user_infos[0].id)
|
||||
.where(TOSHistoricalData.user_unique_identifier == unique_identifier)
|
||||
.where(TOSHistoricalData.api_type == 'User Info')
|
||||
.limit(1)
|
||||
)
|
||||
).one_or_none()
|
||||
if extra_info is not None:
|
||||
user_infos = [extra_info, *user_infos]
|
||||
return [
|
||||
HistoryData(score=float(i.data.data.rating_now), record_at=i.update_time.astimezone(ZoneInfo('Asia/Shanghai')))
|
||||
for i in user_infos
|
||||
if isinstance(i.data, UserInfoSuccess)
|
||||
]
|
||||
|
||||
|
||||
async def make_query_image(user_info: UserInfoSuccess, game_data: GameData, event_user_info: User | None) -> bytes:
|
||||
metrics = game_data.metrics
|
||||
sprint_value = (
|
||||
(
|
||||
@@ -216,6 +262,8 @@ async def make_query_image(user_info: UserInfoSuccess, game_data: GameData, even
|
||||
if user_info.data.pb_sprint != '2147483647'
|
||||
else 'N/A'
|
||||
)
|
||||
data = handle_history_data(await get_historical_data(user_info.data.teaid))
|
||||
values = get_value_bounds([i.score for i in data])
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/tos/info',
|
||||
@@ -226,26 +274,38 @@ async def make_query_image(user_info: UserInfoSuccess, game_data: GameData, even
|
||||
else get_random_avatar(user_info.data.teaid),
|
||||
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,
|
||||
history=History(
|
||||
data=data,
|
||||
max_value=values.value_max,
|
||||
min_value=values.value_min,
|
||||
split_interval=(split := get_split(value_bound=values, min_value=0)).split_value,
|
||||
offset=split.offset,
|
||||
),
|
||||
rating=round(float(user_info.data.rating_now), 2),
|
||||
rd=round(float(user_info.data.rd_now), 2),
|
||||
lpm=metrics.lpm,
|
||||
pps=metrics.pps,
|
||||
lpm_trending=Trending.KEEP,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
vs=metrics.vs,
|
||||
apm_trending=Trending.KEEP,
|
||||
adpm=metrics.adpm,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
),
|
||||
radar=Radar(
|
||||
adpm_trending=Trending.KEEP,
|
||||
app=(app := (metrics.apm / (60 * metrics.pps))),
|
||||
OR=game_data.OR,
|
||||
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',
|
||||
singleplayer=Singleplayer(
|
||||
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',
|
||||
),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
@@ -258,7 +318,7 @@ def make_query_text(user_info: UserInfoSuccess, game_data: GameData | None) -> U
|
||||
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)}) '
|
||||
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:
|
||||
@@ -266,7 +326,7 @@ def make_query_text(user_info: UserInfoSuccess, game_data: GameData | None) -> U
|
||||
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'\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)
|
||||
|
||||
74
nonebot_plugin_tetris_stats/games/tos/unbind.py
Normal file
74
nonebot_plugin_tetris_stats/games/tos/unbind.py
Normal file
@@ -0,0 +1,74 @@
|
||||
from secrets import choice
|
||||
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_uninfo import QryItrface, Uninfo
|
||||
from nonebot_plugin_uninfo import User as UninfoUser
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from nonebot_plugin_user import User
|
||||
from nonebot_plugin_waiter import suggest # type: ignore[import-untyped]
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import query_bind_info, remove_bind, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
|
||||
@alc.assign('TOP.unbind')
|
||||
async def _(
|
||||
nb_user: User,
|
||||
event_session: Uninfo,
|
||||
interface: QryItrface,
|
||||
):
|
||||
async with (
|
||||
trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='unbind',
|
||||
command_args=[],
|
||||
),
|
||||
get_session() as session,
|
||||
):
|
||||
if (bind := await query_bind_info(session=session, user=nb_user, game_platform=GAME_TYPE)) is None:
|
||||
await UniMessage('您还未绑定 TOP 账号').finish()
|
||||
resp = await suggest('您确定要解绑吗?', ['是', '否'])
|
||||
if resp is None or resp.extract_plain_text() == '否':
|
||||
return
|
||||
player = Player(user_name=bind.game_account, trust=True)
|
||||
user = await player.user
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform='TOS',
|
||||
type='unlink',
|
||||
user=People(
|
||||
avatar=await get_avatar(event_session.user, 'Data URI', None),
|
||||
name=user.name,
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(
|
||||
(
|
||||
bot_user := await interface.get_user(event_session.self_id)
|
||||
or UninfoUser(id=event_session.self_id)
|
||||
),
|
||||
'Data URI',
|
||||
'../../static/logo/logo.svg',
|
||||
),
|
||||
name=bot_user.nick or bot_user.name or choice(list(global_config.nickname) or ['bot']),
|
||||
),
|
||||
prompt='茶服绑定{游戏ID}',
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(raw=await screenshot(f'http://{netloc}/host/{page_hash}.html')).send()
|
||||
await remove_bind(session=session, user=nb_user, game_platform=GAME_TYPE)
|
||||
@@ -67,6 +67,19 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"template": {
|
||||
"title": "Template",
|
||||
"description": "Scope 'template' of lang item",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"template_language": {
|
||||
"title": "template_language",
|
||||
"description": "value of lang item type 'template_language'",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
{
|
||||
"scope": "error",
|
||||
"types": [{ "subtype": "MessageFormatError", "types": ["TETR.IO", "TOS", "TOP"] }]
|
||||
}
|
||||
},
|
||||
{ "scope": "template", "types": ["template_language"] }
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# This file is @generated by tarina.lang CLI tool
|
||||
# It is not intended for manual editing.
|
||||
|
||||
# ruff: noqa: E402, F401, PLC0414
|
||||
# ruff: noqa: E402
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -12,5 +12,8 @@
|
||||
"TOS": "Username/ID is invalid",
|
||||
"TOP": "Username is invalid"
|
||||
}
|
||||
},
|
||||
"template": {
|
||||
"template_language": "en-US"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# This file is @generated by tarina.lang CLI tool
|
||||
# It is not intended for manual editing.
|
||||
|
||||
from tarina.lang.model import LangItem, LangModel # type: ignore[import-untyped]
|
||||
from tarina.lang.model import LangItem, LangModel
|
||||
|
||||
|
||||
class InteractionWrong:
|
||||
@@ -27,6 +27,11 @@ class Error:
|
||||
MessageFormatError = ErrorMessageformaterror
|
||||
|
||||
|
||||
class Template:
|
||||
template_language: LangItem = LangItem('template', 'template_language')
|
||||
|
||||
|
||||
class Lang(LangModel):
|
||||
interaction = Interaction
|
||||
error = Error
|
||||
template = Template
|
||||
|
||||
@@ -10,5 +10,8 @@
|
||||
"TOS": "用户名/ID不合法",
|
||||
"TOP": "用户名不合法"
|
||||
}
|
||||
},
|
||||
"template": {
|
||||
"template_language": "zh-CN"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ from nonebot.log import logger
|
||||
from playwright.__main__ import main
|
||||
from playwright.async_api import Browser, BrowserContext, async_playwright
|
||||
|
||||
from ..config.config import config
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
global_config = driver.config
|
||||
@@ -76,6 +78,7 @@ class BrowserManager:
|
||||
"""启动浏览器实例"""
|
||||
playwright = await async_playwright().start()
|
||||
cls._browser = await playwright.firefox.launch(
|
||||
headless=not config.tetris.development,
|
||||
firefox_user_prefs={
|
||||
'network.http.max-persistent-connections-per-server': 64,
|
||||
},
|
||||
|
||||
122
nonebot_plugin_tetris_stats/utils/chart.py
Normal file
122
nonebot_plugin_tetris_stats/utils/chart.py
Normal file
@@ -0,0 +1,122 @@
|
||||
from datetime import datetime, timedelta
|
||||
from math import ceil, floor, inf
|
||||
from typing import NamedTuple
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .exception import WhatTheFuckError
|
||||
from .render.schemas.base import HistoryData
|
||||
from .typedefs import Number
|
||||
|
||||
|
||||
class ValueBound(NamedTuple):
|
||||
value_max: int
|
||||
value_min: int
|
||||
|
||||
|
||||
class Split(NamedTuple):
|
||||
split_value: int
|
||||
offset: int
|
||||
|
||||
|
||||
def get_value_bounds(values: list[int | float]) -> ValueBound:
|
||||
value_max = 10 * ceil(max(values) / 10)
|
||||
value_min = 10 * floor(min(values) / 10)
|
||||
return ValueBound(value_max, value_min)
|
||||
|
||||
|
||||
def get_split(value_bound: ValueBound, max_value: Number = inf, min_value: Number = -inf) -> Split:
|
||||
offset = 0
|
||||
overflow = 0
|
||||
|
||||
while True:
|
||||
if (new_max_value := value_bound.value_max + offset + overflow) > max_value:
|
||||
overflow -= 1
|
||||
continue
|
||||
if (new_min_value := value_bound.value_min - offset + overflow) < min_value:
|
||||
overflow += 1
|
||||
continue
|
||||
if ((new_max_value - new_min_value) / 40).is_integer():
|
||||
split_value = int((value_bound.value_max + offset - (value_bound.value_min - offset)) / 4)
|
||||
break
|
||||
offset += 1
|
||||
return Split(split_value, offset + overflow)
|
||||
|
||||
|
||||
def get_specified_point(
|
||||
previous_point: HistoryData,
|
||||
behind_point: HistoryData,
|
||||
point_time: datetime,
|
||||
) -> HistoryData:
|
||||
"""根据给出的 previous_point 和 behind_point, 推算 point_time 点处的数据
|
||||
|
||||
Args:
|
||||
previous_point (Data): 前面的数据点
|
||||
behind_point (Data): 后面的数据点
|
||||
point_time (datetime): 要推算的点的位置
|
||||
|
||||
Returns:
|
||||
Data: 要推算的点的数据
|
||||
"""
|
||||
# 求两个点的斜率
|
||||
slope = (behind_point.score - previous_point.score) / (
|
||||
datetime.timestamp(behind_point.record_at) - datetime.timestamp(previous_point.record_at)
|
||||
)
|
||||
return HistoryData(
|
||||
record_at=point_time,
|
||||
score=previous_point.score
|
||||
+ slope * (datetime.timestamp(point_time) - datetime.timestamp(previous_point.record_at)),
|
||||
)
|
||||
|
||||
|
||||
def handle_history_data(data: list[HistoryData]) -> list[HistoryData]: # noqa: C901, PLR0912
|
||||
# 按照 记录时间 对数据进行排序
|
||||
data.sort(key=lambda x: x.record_at)
|
||||
|
||||
# 定义时间边界, 右边界为当前时间的当天零点, 左边界为右边界前推9天
|
||||
# 返回值的[0]和[-1]分别应满足left_border和right_border
|
||||
zero = datetime.now(ZoneInfo('Asia/Shanghai')).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
left_border = zero - timedelta(days=9)
|
||||
right_border = zero.replace(microsecond=1000)
|
||||
|
||||
lefts: list[HistoryData] = []
|
||||
in_border: list[HistoryData] = []
|
||||
rights: list[HistoryData] = []
|
||||
|
||||
# 根据 记录时间 将数据分类到对应的列表中
|
||||
for i in data:
|
||||
if i.record_at < left_border:
|
||||
lefts.append(i)
|
||||
elif i.record_at < right_border:
|
||||
in_border.append(i)
|
||||
else:
|
||||
rights.append(i)
|
||||
|
||||
ret: list[HistoryData] = []
|
||||
|
||||
# 处理左边界的点
|
||||
if lefts and in_border: # 如果边界左侧和边界内都有值则推算
|
||||
ret.append(get_specified_point(lefts[-1], in_border[0], left_border))
|
||||
elif lefts and not in_border: # 如果边界左侧有值但是边界内没有值则直接取左侧的最后一个值
|
||||
ret.append(HistoryData(score=lefts[-1].score, record_at=left_border))
|
||||
elif not lefts and in_border: # 如果边界左侧没有值但是边界内有值则直接取边界内的第一个值
|
||||
ret.append(HistoryData(score=in_border[0].score, record_at=left_border))
|
||||
elif not lefts and not in_border and rights: # 如果边界左侧和边界内都没有值但是边界右侧有值则直接取边界右侧的第一个值 # fmt: skip
|
||||
ret.append(HistoryData(score=rights[0].score, record_at=left_border))
|
||||
else: # 暂时没想到其他情况
|
||||
raise WhatTheFuckError
|
||||
|
||||
# 添加边界内数据
|
||||
ret.extend(in_border)
|
||||
|
||||
# 处理右边界的点
|
||||
if in_border and rights: # 如果边界内和边界右侧都有值则推算
|
||||
ret.append(get_specified_point(in_border[-1], rights[0], right_border))
|
||||
elif not in_border and rights: # 如果边界内没有值但是边界右侧有值则直接取右侧的第一个值
|
||||
ret.append(HistoryData(score=rights[0].score, record_at=right_border))
|
||||
elif in_border and not rights: # 如果边界内有值但是边界右侧没有值则直接取边界内的最后一个值
|
||||
ret.append(HistoryData(score=in_border[-1].score, record_at=right_border))
|
||||
elif not in_border and not rights and lefts: # 如果边界内和边界右侧都没有值但是边界左侧有值则直接取边界左侧的最后一个值 # fmt: skip
|
||||
ret.append(HistoryData(score=lefts[-1].score, record_at=right_border))
|
||||
else: # 暂时没想到其他情况
|
||||
raise WhatTheFuckError
|
||||
return ret
|
||||
@@ -2,9 +2,9 @@ from functools import cache
|
||||
from hashlib import sha256
|
||||
from ipaddress import IPv4Address, IPv6Address
|
||||
from pathlib import Path as FilePath
|
||||
from typing import TYPE_CHECKING, ClassVar, Literal
|
||||
from typing import TYPE_CHECKING, Annotated, ClassVar, Literal
|
||||
|
||||
from aiofiles import open
|
||||
from aiofiles import open as aopen
|
||||
from fastapi import BackgroundTasks, FastAPI, Path, status
|
||||
from fastapi.responses import FileResponse, HTMLResponse, Response
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -12,7 +12,7 @@ from nonebot import get_app, get_driver
|
||||
from nonebot.log import logger
|
||||
from yarl import URL
|
||||
|
||||
from ..config.config import CACHE_PATH
|
||||
from ..config.config import CACHE_PATH, config
|
||||
from ..games.tetrio.api.cache import request
|
||||
from .image import img_to_png
|
||||
from .templates import TEMPLATES_DIR
|
||||
@@ -45,15 +45,21 @@ class HostPage:
|
||||
async def __aenter__(self) -> str:
|
||||
return self.page_hash
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> None: # noqa: ANN001
|
||||
self.pages.pop(self.page_hash, None)
|
||||
if not config.tetris.development:
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> None: # noqa: ANN001
|
||||
self.pages.pop(self.page_hash, None)
|
||||
else:
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> None: # noqa: ANN001
|
||||
pass
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
def _():
|
||||
app.mount(
|
||||
'/host/assets',
|
||||
StaticFiles(directory=TEMPLATES_DIR / 'assets'),
|
||||
'/host/_nuxt',
|
||||
StaticFiles(directory=TEMPLATES_DIR / '_nuxt'),
|
||||
name='assets',
|
||||
)
|
||||
logger.success('assets mounted')
|
||||
@@ -69,9 +75,9 @@ def _(page_hash: str) -> HTMLResponse:
|
||||
@app.get('/host/resource/tetrio/{resource_type}/{user_id}', status_code=status.HTTP_200_OK)
|
||||
async def _(
|
||||
resource_type: Literal['avatars', 'banners'],
|
||||
user_id: Annotated[str, Path(regex=r'^[a-f0-9]{24}$')],
|
||||
revision: int,
|
||||
background_tasks: BackgroundTasks,
|
||||
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():
|
||||
image = img_to_png(
|
||||
@@ -87,7 +93,7 @@ async def _(
|
||||
|
||||
async def write_cache(path: FilePath, data: bytes) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
async with open(path, 'wb') as file:
|
||||
async with aopen(path, 'wb') as file:
|
||||
await file.write(data)
|
||||
|
||||
|
||||
|
||||
@@ -2,16 +2,22 @@ from base64 import b64encode
|
||||
from io import BytesIO
|
||||
from typing import Literal, overload
|
||||
|
||||
from nonebot_plugin_userinfo import UserInfo
|
||||
from nonebot_plugin_uninfo import User
|
||||
from PIL import Image
|
||||
from yarl import URL
|
||||
|
||||
from ..config.config import config
|
||||
from .request import Request
|
||||
|
||||
request = Request(config.tetris.proxy.main)
|
||||
|
||||
|
||||
@overload
|
||||
async def get_avatar(user: UserInfo, scheme: Literal['Data URI'], default: str | None) -> str:
|
||||
async def get_avatar(user: User, scheme: Literal['Data URI'], default: str | None) -> str:
|
||||
"""获取用户头像的指定格式
|
||||
|
||||
Args:
|
||||
user (UserInfo): 要获取的用户
|
||||
user (User): 要获取的用户
|
||||
scheme (Literal['Data URI']): 格式
|
||||
default (str | None): 获取不到时的默认值
|
||||
|
||||
@@ -25,11 +31,11 @@ async def get_avatar(user: UserInfo, scheme: Literal['Data URI'], default: str |
|
||||
|
||||
|
||||
@overload
|
||||
async def get_avatar(user: UserInfo, scheme: Literal['bytes'], default: str | None) -> bytes:
|
||||
async def get_avatar(user: User, scheme: Literal['bytes'], default: str | None) -> bytes:
|
||||
"""获取用户头像的指定格式
|
||||
|
||||
Args:
|
||||
user (UserInfo): 要获取的用户
|
||||
user (User): 要获取的用户
|
||||
scheme (Literal['bytes']): 格式
|
||||
default (str | None): 获取不到时的默认值
|
||||
|
||||
@@ -38,20 +44,20 @@ async def get_avatar(user: UserInfo, scheme: Literal['bytes'], default: str | No
|
||||
"""
|
||||
|
||||
|
||||
async def get_avatar(user: UserInfo, scheme: Literal['Data URI', 'bytes'], default: str | None) -> str | bytes:
|
||||
if user.user_avatar is None:
|
||||
async def get_avatar(user: User, scheme: Literal['Data URI', 'bytes'], default: str | None) -> str | bytes:
|
||||
if user.avatar is None:
|
||||
if default is None:
|
||||
msg = "Can't get avatar"
|
||||
raise TypeError(msg)
|
||||
return default
|
||||
bot_avatar = await user.user_avatar.get_image()
|
||||
avatar = await request.request(URL(user.avatar), is_json=False)
|
||||
if scheme == 'Data URI':
|
||||
avatar_format = Image.open(BytesIO(bot_avatar)).format
|
||||
avatar_format = Image.open(BytesIO(avatar)).format
|
||||
if avatar_format is None:
|
||||
msg = "Can't get avatar format"
|
||||
raise TypeError(msg)
|
||||
return f'data:{Image.MIME[avatar_format]};base64,{b64encode(bot_avatar).decode()}'
|
||||
return bot_avatar
|
||||
return f'data:{Image.MIME[avatar_format]};base64,{b64encode(avatar).decode()}'
|
||||
return avatar
|
||||
|
||||
|
||||
def img_to_png(image: bytes) -> bytes:
|
||||
|
||||
8
nonebot_plugin_tetris_stats/utils/lang.py
Normal file
8
nonebot_plugin_tetris_stats/utils/lang.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from typing import cast
|
||||
|
||||
from ..i18n.model import Lang
|
||||
from .typedefs import Lang as LangType
|
||||
|
||||
|
||||
def get_lang() -> LangType:
|
||||
return cast('LangType', Lang.template.template_language())
|
||||
@@ -23,7 +23,9 @@ def limit(limit: timedelta) -> Callable[[Callable[P, Coroutine[Any, Any, T]]], C
|
||||
nonlocal last_call
|
||||
async with lock:
|
||||
if (diff := (time() - last_call)) < limit_seconds:
|
||||
logger.debug(f'func: {func.__name__} trigger limit, wait {(limit_time:=limit_seconds-diff):.3f}s')
|
||||
logger.debug(
|
||||
f'func: {func.__name__} trigger limit, wait {(limit_time := limit_seconds - diff):.3f}s'
|
||||
)
|
||||
await sleep(limit_time)
|
||||
last_call = time()
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from typing import overload
|
||||
|
||||
from .typing import Number
|
||||
from .typedefs import Number
|
||||
|
||||
|
||||
class TetrisMetricsBaseWithPPS:
|
||||
|
||||
@@ -4,20 +4,26 @@ from jinja2 import Environment, FileSystemLoader
|
||||
from nonebot.compat import PYDANTIC_V2
|
||||
|
||||
from ..templates import TEMPLATES_DIR
|
||||
from .schemas.base import Base
|
||||
from .schemas.bind import Bind
|
||||
from .schemas.tetrio.rank.detail import Data as TETRIORankDetailData
|
||||
from .schemas.tetrio.rank.v1 import Data as TETRIORankDataV1
|
||||
from .schemas.tetrio.rank.v2 import Data as TETRIORankDataV2
|
||||
from .schemas.tetrio.record.blitz import Record as TETRIORecordBlitz
|
||||
from .schemas.tetrio.record.sprint import Record as TETRIORecordSprint
|
||||
from .schemas.tetrio.user.info_v1 import Info as TETRIOUserInfoV1
|
||||
from .schemas.tetrio.user.info_v2 import Info as TETRIOUserInfoV2
|
||||
from .schemas.tetrio.user.list_v2 import List as TETRIOUserListV2
|
||||
from .schemas.top_info import Info as TOPInfo
|
||||
from .schemas.tos_info import Info as TOSInfo
|
||||
from .schemas.v1.tetrio.rank import Data as TETRIORankDataV1
|
||||
from .schemas.v1.tetrio.user.info import Info as TETRIOUserInfoV1
|
||||
from .schemas.v1.top.info import Info as TOPInfoV1
|
||||
from .schemas.v1.tos.info import Info as TOSInfoV1
|
||||
from .schemas.v2.tetrio.rank import Data as TETRIORankDataV2
|
||||
from .schemas.v2.tetrio.rank.detail import Data as TETRIORankDetailDataV2
|
||||
from .schemas.v2.tetrio.record.blitz import Record as TETRIORecordBlitzV2
|
||||
from .schemas.v2.tetrio.record.sprint import Record as TETRIORecordSprintV2
|
||||
from .schemas.v2.tetrio.tetra_league import Data as TETRIOTetraLeagueDataV2
|
||||
from .schemas.v2.tetrio.user.info import Info as TETRIOUserInfoV2
|
||||
from .schemas.v2.tetrio.user.list import List as TETRIOUserListV2
|
||||
|
||||
env = Environment(
|
||||
loader=FileSystemLoader(TEMPLATES_DIR), autoescape=True, trim_blocks=True, lstrip_blocks=True, enable_async=True
|
||||
loader=FileSystemLoader(TEMPLATES_DIR),
|
||||
autoescape=False, # noqa: S701
|
||||
trim_blocks=True,
|
||||
lstrip_blocks=True,
|
||||
enable_async=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -28,48 +34,26 @@ async def render(render_type: Literal['v1/tetrio/info'], data: TETRIOUserInfoV1)
|
||||
@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: ...
|
||||
async def render(render_type: Literal['v1/top/info'], data: TOPInfoV1) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v1/tos/info'], data: TOSInfo) -> str: ...
|
||||
async def render(render_type: Literal['v1/tos/info'], data: TOSInfoV1) -> 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: TETRIORankDetailDataV2) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/record/blitz'], data: TETRIORecordBlitzV2) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/record/sprint'], data: TETRIORecordSprintV2) -> str: ...
|
||||
@overload
|
||||
async def render(render_type: Literal['v2/tetrio/tetra-league'], data: TETRIOTetraLeagueDataV2) -> 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[
|
||||
'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
|
||||
| TETRIOUserInfoV1
|
||||
| TETRIORankDataV1
|
||||
| TOPInfo
|
||||
| TOSInfo
|
||||
| TETRIOUserInfoV2
|
||||
| TETRIOUserListV2
|
||||
| TETRIORecordSprint
|
||||
| TETRIORecordBlitz
|
||||
| TETRIORankDataV2
|
||||
| TETRIORankDetailData,
|
||||
render_type: str,
|
||||
data: Base,
|
||||
) -> str:
|
||||
if PYDANTIC_V2:
|
||||
return await env.get_template('index.html').render_async(
|
||||
|
||||
@@ -43,8 +43,8 @@ class Piece(Enum):
|
||||
)
|
||||
|
||||
I5 = (
|
||||
(True, True, True, True, True), # fmt: skip
|
||||
)
|
||||
(True, True, True, True, True),
|
||||
) # fmt: skip
|
||||
|
||||
V = (
|
||||
(True, False, False),
|
||||
@@ -156,7 +156,7 @@ class SkinManager:
|
||||
|
||||
|
||||
class Skin(ABC):
|
||||
def __new__(cls, *args: Any, **kwargs: Any) -> Self: # noqa: ANN401, ARG003
|
||||
def __new__(cls, *args: Any, **kwargs: Any) -> Self: # noqa: ANN401, ARG004
|
||||
instance = super().__new__(cls)
|
||||
SkinManager.register(instance)
|
||||
return instance
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
from strenum import StrEnum
|
||||
|
||||
from ...typing import Number
|
||||
from ...typedefs import Lang, Number
|
||||
|
||||
|
||||
class Base(BaseModel):
|
||||
lang: Lang
|
||||
|
||||
|
||||
class Avatar(BaseModel):
|
||||
@@ -18,3 +24,14 @@ class People(BaseModel):
|
||||
class Ranking(BaseModel):
|
||||
rating: Number
|
||||
rd: Number
|
||||
|
||||
|
||||
class HistoryData(BaseModel):
|
||||
score: Number
|
||||
record_at: datetime
|
||||
|
||||
|
||||
class Trending(StrEnum):
|
||||
UP = 'up'
|
||||
KEEP = 'keep'
|
||||
DOWN = 'down'
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user