mirror of
https://github.com/A-Minos/nonebot-plugin-tetris-stats.git
synced 2026-03-05 05:36:54 +08:00
Compare commits
210 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6f3f6bda1d | |||
|
|
367ead2ff5 | ||
|
|
7cfe6593f2 | ||
| 67058a1492 | |||
| c4ab6badbc | |||
|
|
52bfd30ec5 | ||
|
|
7eaf551dd0 | ||
| 99e475b75b | |||
|
|
ba0d1677cf | ||
|
|
14f3e6960e | ||
|
|
61c798de1a | ||
|
|
d63976b881 | ||
|
|
72042220d8 | ||
|
|
15d3a33cb8 | ||
|
|
f8fde51009 | ||
|
|
6256053a82 | ||
|
|
689a2c72b8 | ||
|
|
cdea262335 | ||
|
|
28a02aec0f | ||
|
|
95aa00e2cd | ||
|
|
73bdf93d88 | ||
|
|
397047162e | ||
|
|
653bccf48a | ||
|
|
bce73489dd | ||
|
|
f4e1e8b1a2 | ||
|
|
b3bb425c44 | ||
|
|
59a1c80ce5 | ||
|
|
fcecf5a01f | ||
|
|
a4ffb6bbc6 | ||
|
|
81150a36be | ||
|
|
2ddf1dc336 | ||
|
|
3615a87926 | ||
|
|
0228e1a480 | ||
|
|
d920c90936 | ||
|
|
024418f032 | ||
|
|
3945da6655 | ||
|
|
bc59e287d8 | ||
|
|
f8382150c7 | ||
|
|
4fd17204c4 | ||
|
|
9d4333812d | ||
|
|
2c07a1e337 | ||
|
|
2f95650282 | ||
|
|
0b4d49ee6a | ||
|
|
9392fefdf7 | ||
| a57811b0d3 | |||
|
|
7a5170936b | ||
|
|
068c508f57 | ||
|
|
0648ca021b | ||
|
|
65e7fed32b | ||
|
|
fdbb2f3f6e | ||
| 144c223fe9 | |||
|
|
52a6d95434 | ||
| d8255756ca | |||
|
|
13c6d53b6a | ||
| 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 | ||
| 08a1a427b4 | |||
|
|
d4e91c8521 | ||
| dbde1181ce | |||
|
|
86fe4f0766 | ||
|
|
381f2505d6 | ||
| b3a77f5296 | |||
| 274f30f82a | |||
| efb1ddb260 | |||
| 7e3f49bc9e | |||
| 665772ed66 | |||
|
|
44fda8a19e | ||
|
|
6921bf4e37 | ||
|
|
c3c97c1c8b | ||
|
|
1d33872c9b | ||
|
|
b2d5a1e729 | ||
|
|
a0fd9eaed3 | ||
|
|
593723aa76 | ||
|
|
73d97d8458 | ||
|
|
d6f11655c1 | ||
|
|
376e85e36e | ||
|
|
45116a1418 | ||
|
|
a42d3e3837 | ||
|
|
b333c54c7d | ||
|
|
8840402d2f | ||
|
|
e8b64b23f5 | ||
|
|
40762a3180 | ||
|
|
a2c6ad8328 | ||
|
|
c7d93069ef | ||
| 4b514df2db | |||
| 47c83be1b5 | |||
| 6c0e092f51 | |||
| 04b9cd9eae | |||
|
|
61b5fcb137 | ||
| c0540769c8 | |||
|
|
0e19943046 | ||
|
|
7e1d2e8cb0 | ||
|
|
8931cfb5a7 | ||
|
|
ea8a18c1b1 | ||
| ef1acb0f16 | |||
|
|
f7bb667254 | ||
|
|
fa94c1beeb | ||
|
|
4e1e91a977 | ||
|
|
0f6a00819b | ||
|
|
b56385b412 | ||
|
|
7eea235f52 | ||
|
|
8a06b572ed | ||
| 6867245be3 | |||
|
|
eebff0a8ad | ||
| 74eef41506 | |||
| 5eb4771259 | |||
| 7a3a4d936d | |||
|
|
03ca7c4486 | ||
|
|
b043d1da59 | ||
|
|
c9659201b1 | ||
|
|
617d3ec658 | ||
|
|
57a1992675 | ||
|
|
8d1d2f329e | ||
|
|
fa6cbd5c6d | ||
|
|
9f0f0b87f4 | ||
|
|
96c298b1b8 | ||
|
|
df5ced235d | ||
|
|
af83c7a2d9 | ||
|
|
bc41a91034 | ||
|
|
d97291d1bc | ||
| 5b56de9de1 | |||
| 0898a81331 | |||
|
|
d464059c0a | ||
|
|
6ea8b9328c | ||
|
|
773ff5545c | ||
|
|
94710b938b | ||
| ec09bb734d | |||
|
|
9e9a642847 | ||
|
|
04e0b14e72 | ||
|
|
20ce9c64be | ||
|
|
8af07bf031 | ||
|
|
3a904f67ad | ||
|
|
fc9b751ac4 | ||
| cb4c6b96f0 | |||
|
|
25c3777c0f | ||
|
|
193fd1da2a | ||
|
|
2cd609dd40 | ||
| a206098805 | |||
|
|
d493ba5f0d | ||
|
|
581d1f9674 | ||
|
|
01c99e8a8c | ||
|
|
eb3f4bea04 | ||
|
|
ebbbd68b05 | ||
|
|
10e0eb815e | ||
|
|
a57b04e181 | ||
|
|
cc2e71f1a5 | ||
|
|
3384263bb2 | ||
|
|
68f210dc4f | ||
|
|
00a85fe3e9 | ||
|
|
a10a7584ae | ||
|
|
95aac5e321 | ||
| 89d8c938e2 | |||
| 84db42f1ce | |||
|
|
0a660922bb | ||
|
|
56bc98cc79 | ||
|
|
be61683b51 | ||
| ccd5706a95 | |||
| b69240caa5 | |||
| 49d00f4d0e | |||
| 389a850025 |
12
.github/dependabot.yml
vendored
12
.github/dependabot.yml
vendored
@@ -1,12 +0,0 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "pip" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
target-branch: "main"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
27
.github/workflows/Release.yml
vendored
27
.github/workflows/Release.yml
vendored
@@ -3,7 +3,7 @@ name: Release CI
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "*"
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
@@ -12,24 +12,25 @@ jobs:
|
||||
id-token: write
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install poetry
|
||||
run: pipx install poetry
|
||||
shell: bash
|
||||
|
||||
- uses: actions/setup-python@v4
|
||||
- uses: astral-sh/setup-uv@v7
|
||||
name: Setup UV
|
||||
with:
|
||||
python-version: '3.11'
|
||||
cache: "poetry"
|
||||
enable-cache: true
|
||||
|
||||
- run: poetry install
|
||||
- name: 'Set up Python'
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version-file: '.python-version'
|
||||
|
||||
- run: uv sync
|
||||
shell: bash
|
||||
|
||||
- name: Get Version
|
||||
id: version
|
||||
run: |
|
||||
echo "VERSION=$(poetry version -s)" >> $GITHUB_OUTPUT
|
||||
echo "VERSION=$(uvx pdm show --version)" >> $GITHUB_OUTPUT
|
||||
echo "TAG_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
|
||||
echo "TAG_NAME=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
|
||||
|
||||
@@ -38,10 +39,10 @@ jobs:
|
||||
run: exit 1
|
||||
|
||||
- name: Build Package
|
||||
run: poetry build
|
||||
run: uv build
|
||||
|
||||
- name: Publish Package to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
run: uv publish
|
||||
|
||||
- name: Publish Package to GitHub Release
|
||||
run: gh release create ${{ steps.version.outputs.TAG_NAME }} dist/*.tar.gz dist/*.whl -t "🔖 ${{ steps.version.outputs.TAG_NAME }}" --generate-notes
|
||||
|
||||
57
.github/workflows/Test.yml
vendored
Normal file
57
.github/workflows/Test.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
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", "3.14"]
|
||||
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@v6
|
||||
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
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@a638d6464689bbb24c325bb3fe9404d63a913030
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
42
.github/workflows/TypeCheck.yml
vendored
42
.github/workflows/TypeCheck.yml
vendored
@@ -1,27 +1,33 @@
|
||||
name: TypeCheck
|
||||
|
||||
on:
|
||||
push:
|
||||
push:
|
||||
|
||||
jobs:
|
||||
Mypy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
TypeCheck:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install poetry
|
||||
run: pipx install poetry
|
||||
shell: bash
|
||||
- uses: astral-sh/setup-uv@v7
|
||||
name: Setup UV
|
||||
with:
|
||||
enable-cache: true
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.10'
|
||||
cache: 'poetry'
|
||||
- name: 'Set up Python'
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version-file: '.python-version'
|
||||
|
||||
- run: poetry install
|
||||
shell: bash
|
||||
- run: uv sync
|
||||
shell: bash
|
||||
|
||||
- name: Run Mypy
|
||||
shell: bash
|
||||
run: |
|
||||
poetry run mypy ./nonebot_plugin_tetris_stats
|
||||
- name: Run Mypy
|
||||
shell: bash
|
||||
run: |
|
||||
uv run mypy ./nonebot_plugin_tetris_stats
|
||||
|
||||
- name: Run BasedPyright
|
||||
shell: bash
|
||||
run: |
|
||||
uv run basedpyright ./nonebot_plugin_tetris_stats/
|
||||
|
||||
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@v3
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v2
|
||||
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@v4
|
||||
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@v2
|
||||
# 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@v4
|
||||
|
||||
# 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@v2
|
||||
# - run: |
|
||||
# echo "Run, Build Application using script"
|
||||
# ./location_of_script_within_repo/buildscript.sh
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
|
||||
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.6.1
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: [--fix, --exit-non-zero-on-fix]
|
||||
stages: [commit]
|
||||
- id: ruff-format
|
||||
stages: [commit]
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.15.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]
|
||||
|
||||
1
.python-version
Normal file
1
.python-version
Normal file
@@ -0,0 +1 @@
|
||||
3.10
|
||||
58
CONTRIBUTING.en-US.md
Normal file
58
CONTRIBUTING.en-US.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# How to Contribute?
|
||||
|
||||
## Setting Up the Environment
|
||||
|
||||
### For Developers with Basic Python Knowledge
|
||||
|
||||
First, you need install [uv](https://docs.astral.sh/uv/).
|
||||
Then:
|
||||
|
||||
```bash
|
||||
# Set up the basic Python environment
|
||||
uv python install 3.10
|
||||
|
||||
# Clone the repository
|
||||
git clone https://github.com/A-Minos/nonebot-plugin-tetris-stats.git
|
||||
cd nonebot-plugin-tetris-stats
|
||||
|
||||
# Install dependencies
|
||||
uv sync
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
### Code Development
|
||||
|
||||
1. For static code analysis, use [ruff](https://docs.astral.sh/ruff/). You can install the corresponding plugin for your IDE or use the command line with `ruff check ./nonebot_plugin_tetris_stats/` to check the code.
|
||||
2. For code formatting, use [ruff](https://docs.astral.sh/ruff/). You can install the corresponding plugin for your IDE or use the command line with `ruff format ./nonebot_plugin_tetris_stats/` to format the code.
|
||||
3. For type checking, use both [basedpyright](https://docs.basedpyright.com/latest/) and [mypy](https://www.mypy-lang.org/). You can install the corresponding plugins for your IDE or use the following commands in the terminal to check the code:
|
||||
|
||||
```bash
|
||||
# basedpyright
|
||||
basedpyright ./nonebot_plugin_tetris_stats/
|
||||
|
||||
# mypy
|
||||
mypy ./nonebot_plugin_tetris_stats/
|
||||
```
|
||||
|
||||
### Internationalization
|
||||
|
||||
This project uses [Tarina](https://github.com/ArcletProject/Tarina) for internationalization support.
|
||||
|
||||
#### 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.
|
||||
3. Edit the generated `./nonebot_plugin_tetris_stats/i18n/{language_code}.json` file.
|
||||
|
||||
#### Updating an Existing Language
|
||||
|
||||
1. Navigate to the `./nonebot_plugin_tetris_stats/i18n/` directory.
|
||||
2. Edit the corresponding `./nonebot_plugin_tetris_stats/i18n/{language_code}.json` file.
|
||||
|
||||
#### Adding New Entries
|
||||
|
||||
1. Navigate to the `./nonebot_plugin_tetris_stats/i18n/` directory.
|
||||
2. Edit the `.template.json` file.
|
||||
3. Run `tarina-lang schema && tarina-lang model`.
|
||||
4. Modify the language files, adding new entries at least to `en-US.json`.
|
||||
57
CONTRIBUTING.md
Normal file
57
CONTRIBUTING.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# 我该如何参与开发?
|
||||
|
||||
## 配置环境
|
||||
|
||||
首先你需要安装 [uv](https://docs.astral.sh/uv/)。
|
||||
然后:
|
||||
|
||||
```bash
|
||||
# 配置基础 Python 环境
|
||||
uv python install 3.10
|
||||
|
||||
# 克隆仓库
|
||||
git clone https://github.com/A-Minos/nonebot-plugin-tetris-stats.git
|
||||
cd nonebot-plugin-tetris-stats
|
||||
|
||||
# 安装依赖
|
||||
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
|
||||
basedpyright ./nonebot_plugin_tetris_stats/
|
||||
|
||||
# mypy
|
||||
mypy ./nonebot_plugin_tetris_stats/
|
||||
```
|
||||
|
||||
### 国际化
|
||||
|
||||
本项目使用 [Tarina](https://github.com/ArcletProject/Tarina) 提供国际化支持。
|
||||
|
||||
#### 添加新的语言
|
||||
|
||||
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) 的规范。
|
||||
3. 编辑生成的 `./nonebot_plugin_tetris_stats/i18n/{语言代码}.json` 文件。
|
||||
|
||||
#### 更新已有语言
|
||||
|
||||
1. 进入 `./nonebot_plugin_tetris_stats/i18n/` 目录。
|
||||
2. 编辑对应的 `./nonebot_plugin_tetris_stats/i18n/{语言代码}.json` 文件。
|
||||
|
||||
#### 添加新的条目
|
||||
|
||||
1. 进入 `./nonebot_plugin_tetris_stats/i18n/` 目录。
|
||||
2. 编辑 `.template.json` 文件。
|
||||
3. 运行 `tarina-lang schema && tarina-lang model`。
|
||||
4. 修改语言文件,至少为`en-US.json`添加新的条目。
|
||||
@@ -41,10 +41,10 @@
|
||||
alt="Gitmoji"
|
||||
/>
|
||||
</a>
|
||||
<a href="https://wakatime.com/badge/user/138b2226-8e02-42be-b99d-35c05198836f/project/65f5bdf7-45ec-479a-8dd2-18c498c910ca">
|
||||
<img
|
||||
src="https://wakatime.com/badge/user/138b2226-8e02-42be-b99d-35c05198836f/project/65f5bdf7-45ec-479a-8dd2-18c498c910ca.svg"
|
||||
alt="wakatime"
|
||||
<a href="https://wakatime.com/badge/user/138b2226-8e02-42be-b99d-35c05198836f/project/e26c7985-a236-4e76-90a6-a72f71d305ef">
|
||||
<img
|
||||
src="https://wakatime.com/badge/user/138b2226-8e02-42be-b99d-35c05198836f/project/e26c7985-a236-4e76-90a6-a72f71d305ef.svg"
|
||||
alt="wakatime"
|
||||
/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -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,6 @@
|
||||
from nonebot import get_plugin_config
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
|
||||
@@ -14,10 +16,17 @@ class Proxy(BaseModel):
|
||||
top: str | None = None
|
||||
|
||||
|
||||
class Dev(BaseModel):
|
||||
enabled: bool = False
|
||||
template_path: Path | None = None
|
||||
enable_template_check: bool = True
|
||||
|
||||
|
||||
class ScopedConfig(BaseModel):
|
||||
request_timeout: float = 30.0
|
||||
screenshot_quality: float = 2
|
||||
proxy: Proxy = Field(default_factory=Proxy)
|
||||
dev: Dev = Field(default_factory=Dev)
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
@@ -25,3 +34,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'))
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""fix json storage
|
||||
|
||||
迁移 ID: 1c5346b657d4
|
||||
父迁移: 2ff388a8c486
|
||||
创建时间: 2026-01-30 03:35:00
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import msgspec
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
from sqlalchemy.engine import Connection
|
||||
|
||||
_LOG_INTERVAL = 10000
|
||||
_BATCH_SIZE = 1000
|
||||
_PG_CHUNK_SIZE = 50000
|
||||
_SQLITE_FETCH_SIZE = 500
|
||||
|
||||
revision: str = '1c5346b657d4'
|
||||
down_revision: str | Sequence[str] | None = '2ff388a8c486'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
tables: dict[str, list[str]] = {
|
||||
'nb_t_io_tl_stats_field': [
|
||||
'low_pps',
|
||||
'low_apm',
|
||||
'low_vs',
|
||||
'high_pps',
|
||||
'high_apm',
|
||||
'high_vs',
|
||||
],
|
||||
'nb_t_io_hist_data': ['data'],
|
||||
'nb_t_top_hist_data': ['data'],
|
||||
'nb_t_tos_hist_data': ['data'],
|
||||
'nb_t_io_tl_hist': ['data'],
|
||||
}
|
||||
|
||||
|
||||
def _pg_convert_column(conn: Connection, table: str, column: str) -> None:
|
||||
tbl = sa.table(table, sa.column('id'), sa.column(column))
|
||||
col = getattr(tbl.c, column)
|
||||
path = sa.cast(sa.literal('{}'), ARRAY(sa.Text))
|
||||
payload = sa.cast(sa.cast(col, JSONB).op('#>>')(path), sa.JSON)
|
||||
base = sa.func.json_typeof(col) == 'string'
|
||||
min_max_stmt = sa.select(sa.func.min(tbl.c.id), sa.func.max(tbl.c.id)).where(base)
|
||||
result = conn.execute(min_max_stmt).one()
|
||||
if result[0] is None or result[1] is None:
|
||||
return
|
||||
start_id, end_id = result
|
||||
total = end_id - start_id + 1
|
||||
processed = 0
|
||||
context = op.get_context()
|
||||
with context.autocommit_block():
|
||||
for chunk_start in range(start_id, end_id + 1, _PG_CHUNK_SIZE):
|
||||
chunk_end = min(chunk_start + _PG_CHUNK_SIZE - 1, end_id)
|
||||
stmt = (
|
||||
sa.update(tbl).values({column: payload}).where(base).where(sa.between(tbl.c.id, chunk_start, chunk_end))
|
||||
)
|
||||
conn.execute(stmt)
|
||||
processed += chunk_end - chunk_start + 1
|
||||
logger.warning(
|
||||
f'tetris_stats: converting {table}.{column} chunk {chunk_start}-{chunk_end} '
|
||||
f'processed={processed}/{total}'
|
||||
)
|
||||
remaining_stmt = sa.select(sa.func.count()).select_from(tbl).where(base)
|
||||
remaining = conn.execute(remaining_stmt).scalar()
|
||||
if remaining:
|
||||
msg = f'json storage fix failed: {table}.{column} still has string rows'
|
||||
raise ValueError(msg)
|
||||
|
||||
|
||||
def _pg_convert(conn: Connection) -> None:
|
||||
for table, columns in tables.items():
|
||||
for column in columns:
|
||||
logger.warning(f'tetris_stats: converting {table}.{column} from json string to object')
|
||||
_pg_convert_column(conn, table, column)
|
||||
|
||||
|
||||
def _convert_table_python(conn: Connection, table_name: str, columns: list[str]) -> None: # noqa: C901
|
||||
meta = sa.MetaData()
|
||||
table = sa.Table(table_name, meta, autoload_with=conn)
|
||||
update_stmt = (
|
||||
table.update().where(table.c.id == sa.bindparam('b_id')).values(**{col: sa.bindparam(col) for col in columns})
|
||||
)
|
||||
batch: list[dict[str, object]] = []
|
||||
last_id = 0
|
||||
processed = 0
|
||||
while True:
|
||||
rows = (
|
||||
conn.execute(
|
||||
sa.select(table.c.id, *[table.c[col] for col in columns])
|
||||
.where(table.c.id > last_id)
|
||||
.order_by(table.c.id)
|
||||
.limit(_SQLITE_FETCH_SIZE)
|
||||
)
|
||||
.mappings()
|
||||
.all()
|
||||
)
|
||||
if not rows:
|
||||
break
|
||||
for row in rows:
|
||||
last_id = row['id']
|
||||
processed += 1
|
||||
update_values: dict[str, object] = {'b_id': row['id']}
|
||||
changed = False
|
||||
for column in columns:
|
||||
value = row[column]
|
||||
if isinstance(value, str | bytes):
|
||||
parsed = msgspec.json.decode(value)
|
||||
if not isinstance(parsed, dict | list):
|
||||
msg = f'json storage fix failed: {table_name}.{column} value is not object'
|
||||
raise TypeError(msg)
|
||||
update_values[column] = parsed
|
||||
changed = True
|
||||
elif isinstance(value, dict | list):
|
||||
update_values[column] = value
|
||||
else:
|
||||
msg = f'json storage fix failed: {table_name}.{column} invalid type {type(value)}'
|
||||
raise TypeError(msg)
|
||||
if changed:
|
||||
batch.append(update_values)
|
||||
if processed % _LOG_INTERVAL == 0:
|
||||
logger.warning(f'tetris_stats: converting {table_name} processed={processed}')
|
||||
if len(batch) >= _BATCH_SIZE:
|
||||
conn.execute(update_stmt, batch)
|
||||
batch.clear()
|
||||
if batch:
|
||||
conn.execute(update_stmt, batch)
|
||||
|
||||
|
||||
def _generic_convert(conn: Connection) -> None:
|
||||
for table, columns in tables.items():
|
||||
logger.warning(f'tetris_stats: converting {table} via python')
|
||||
_convert_table_python(conn, table, columns)
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
conn = op.get_bind()
|
||||
if conn.dialect.name == 'postgresql':
|
||||
_pg_convert(conn)
|
||||
else:
|
||||
_generic_convert(conn)
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
@@ -0,0 +1,42 @@
|
||||
"""add verify field
|
||||
|
||||
迁移 ID: 2ff388a8c486
|
||||
父迁移: 3588702dd3a4
|
||||
创建时间: 2025-07-22 18:09:09.734164
|
||||
|
||||
"""
|
||||
|
||||
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 = '2ff388a8c486'
|
||||
down_revision: str | Sequence[str] | None = '3588702dd3a4'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nb_t_bind', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('verify', sa.Boolean(), nullable=False, server_default='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_bind', schema=None) as batch_op:
|
||||
batch_op.drop_column('verify')
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,52 @@
|
||||
"""modify field length
|
||||
|
||||
迁移 ID: 3588702dd3a4
|
||||
父迁移: bc6abd57928f
|
||||
创建时间: 2025-07-19 17:21:17.927162
|
||||
|
||||
"""
|
||||
|
||||
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 = '3588702dd3a4'
|
||||
down_revision: str | Sequence[str] | None = 'bc6abd57928f'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('nb_t_tos_hist_data', schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
'user_unique_identifier',
|
||||
existing_type=sa.VARCHAR(length=24),
|
||||
type_=sa.String(length=256),
|
||||
existing_nullable=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_tos_hist_data', schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
'user_unique_identifier',
|
||||
existing_type=sa.String(length=256),
|
||||
type_=sa.VARCHAR(length=24),
|
||||
existing_nullable=False,
|
||||
)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,353 @@
|
||||
"""add io tl map
|
||||
|
||||
迁移 ID: 3a294ff14610
|
||||
父迁移: 6ecf383d646a
|
||||
创建时间: 2026-01-28 03:25:40.714853
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from nonebot.log import logger
|
||||
from rich.progress import (
|
||||
BarColumn,
|
||||
MofNCompleteColumn,
|
||||
Progress,
|
||||
ProgressColumn,
|
||||
Task,
|
||||
TaskProgressColumn,
|
||||
TextColumn,
|
||||
TimeRemainingColumn,
|
||||
filesize,
|
||||
)
|
||||
from rich.text import Text
|
||||
from sqlalchemy import Connection, text
|
||||
from sqlalchemy.ext.automap import automap_base
|
||||
from sqlalchemy.orm import Session
|
||||
from typing_extensions import override
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Sequence
|
||||
|
||||
revision: str = '3a294ff14610'
|
||||
down_revision: str | Sequence[str] | None = '6ecf383d646a'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
class RateColumn(ProgressColumn):
|
||||
"""Renders human readable processing rate."""
|
||||
|
||||
@override
|
||||
def render(self, task: Task) -> Text:
|
||||
"""Render the speed in iterations per second."""
|
||||
|
||||
def calculate_speed() -> float | None:
|
||||
now = time.monotonic()
|
||||
|
||||
if task.start_time is not None:
|
||||
elapsed = (task.finished_time or now) - task.start_time
|
||||
if elapsed > 0:
|
||||
return task.completed / elapsed
|
||||
return None
|
||||
|
||||
speed = task.finished_speed or task.speed or calculate_speed()
|
||||
|
||||
if speed is None:
|
||||
return Text('', style='progress.percentage')
|
||||
unit, suffix = filesize.pick_unit_and_suffix(
|
||||
int(speed),
|
||||
['', '×10³', '×10⁶', '×10⁹', '×10¹²'], # noqa: RUF001
|
||||
1000,
|
||||
)
|
||||
data_speed = speed / unit
|
||||
return Text(f'{data_speed:.1f}{suffix} it/s', style='progress.percentage')
|
||||
|
||||
|
||||
def _backfill_postgresql(conn: Connection, chunk_size: int = 20000) -> None:
|
||||
result = conn.execute(text('SELECT min(id), max(id) FROM nb_t_io_tl_hist')).one()
|
||||
if result[0] is None or result[1] is None:
|
||||
return
|
||||
min_id, max_id = result
|
||||
total = max_id - min_id + 1
|
||||
|
||||
logger.warning('PG backfill: Disabling foreign key constraints...')
|
||||
|
||||
work_mem = os.getenv('TETRIS_STATS_MIGRATION_WORK_MEM', '256MB')
|
||||
if not re.fullmatch(r'\d+(kB|MB|GB)', work_mem):
|
||||
work_mem = '256MB'
|
||||
conn.execute(
|
||||
text("SELECT set_config('work_mem', :work_mem, true)"),
|
||||
{'work_mem': work_mem},
|
||||
)
|
||||
temp_buffers = os.getenv('TETRIS_STATS_MIGRATION_TEMP_BUFFERS', '128MB')
|
||||
if not re.fullmatch(r'\d+(kB|MB|GB)', temp_buffers):
|
||||
temp_buffers = '128MB'
|
||||
conn.execute(
|
||||
text("SELECT set_config('temp_buffers', :temp_buffers, true)"),
|
||||
{'temp_buffers': temp_buffers},
|
||||
)
|
||||
conn.execute(text('SET LOCAL synchronous_commit = off'))
|
||||
|
||||
logger.warning('tetris_stats: PG backfill synchronous_commit=off')
|
||||
logger.warning(f'tetris_stats: PG backfill work_mem={work_mem}')
|
||||
logger.warning(f'tetris_stats: PG backfill temp_buffers={temp_buffers}')
|
||||
|
||||
conn.execute(text('SET LOCAL max_parallel_workers_per_gather = 8'))
|
||||
conn.execute(text('SET LOCAL parallel_setup_cost = 10'))
|
||||
conn.execute(text('SET LOCAL parallel_tuple_cost = 0.01'))
|
||||
|
||||
logger.warning('tetris_stats: PG backfill max_parallel_workers_per_gather=8')
|
||||
logger.warning('tetris_stats: PG backfill parallel_setup_cost=10')
|
||||
logger.warning('tetris_stats: PG backfill parallel_tuple_cost=0.01')
|
||||
|
||||
with Progress(
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
MofNCompleteColumn(),
|
||||
TaskProgressColumn(),
|
||||
RateColumn(),
|
||||
TimeRemainingColumn(),
|
||||
) as progress:
|
||||
task = progress.add_task('生成索引...', total=total)
|
||||
for start_id in range(min_id, max_id + 1, chunk_size):
|
||||
end_id = min(start_id + chunk_size - 1, max_id)
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
WITH entries AS (
|
||||
SELECT
|
||||
h.stats_id,
|
||||
h.id AS hist_id,
|
||||
e.ordinality - 1 AS entry_index,
|
||||
COALESCE(e.entry->>'_id', e.entry->>'id') AS uid_str
|
||||
FROM nb_t_io_tl_hist h
|
||||
CROSS JOIN LATERAL jsonb_array_elements(h.data::jsonb->'data'->'entries')
|
||||
WITH ORDINALITY AS e(entry, ordinality)
|
||||
WHERE h.id BETWEEN :start_id AND :end_id
|
||||
AND COALESCE(e.entry->>'_id', e.entry->>'id') IS NOT NULL
|
||||
),
|
||||
upserted_uids AS (
|
||||
INSERT INTO nb_t_io_uid (user_unique_identifier)
|
||||
SELECT DISTINCT uid_str FROM entries
|
||||
ON CONFLICT (user_unique_identifier)
|
||||
DO UPDATE SET user_unique_identifier = EXCLUDED.user_unique_identifier
|
||||
RETURNING id, user_unique_identifier
|
||||
)
|
||||
INSERT INTO nb_t_io_tl_map (stats_id, uid_id, hist_id, entry_index)
|
||||
SELECT e.stats_id, u.id, e.hist_id, e.entry_index
|
||||
FROM entries e
|
||||
JOIN upserted_uids u ON u.user_unique_identifier = e.uid_str
|
||||
"""
|
||||
),
|
||||
{'start_id': start_id, 'end_id': end_id},
|
||||
)
|
||||
progress.update(task, advance=end_id - start_id + 1)
|
||||
|
||||
|
||||
def _add_foreign_keys_postgresql(conn: Connection) -> None:
|
||||
logger.warning('PG backfill: Re-adding foreign key constraints (validating)...')
|
||||
|
||||
conn.execute(
|
||||
text("""
|
||||
ALTER TABLE nb_t_io_tl_map
|
||||
ADD CONSTRAINT fk_nb_t_io_tl_map_hist_id_nb_t_io_tl_hist
|
||||
FOREIGN KEY (hist_id) REFERENCES nb_t_io_tl_hist(id)
|
||||
NOT VALID
|
||||
""")
|
||||
)
|
||||
conn.execute(
|
||||
text("""
|
||||
ALTER TABLE nb_t_io_tl_map
|
||||
VALIDATE CONSTRAINT fk_nb_t_io_tl_map_hist_id_nb_t_io_tl_hist
|
||||
""")
|
||||
)
|
||||
|
||||
conn.execute(
|
||||
text("""
|
||||
ALTER TABLE nb_t_io_tl_map
|
||||
ADD CONSTRAINT fk_nb_t_io_tl_map_stats_id_nb_t_io_tl_stats
|
||||
FOREIGN KEY (stats_id) REFERENCES nb_t_io_tl_stats(id)
|
||||
NOT VALID
|
||||
""")
|
||||
)
|
||||
conn.execute(
|
||||
text("""
|
||||
ALTER TABLE nb_t_io_tl_map
|
||||
VALIDATE CONSTRAINT fk_nb_t_io_tl_map_stats_id_nb_t_io_tl_stats
|
||||
""")
|
||||
)
|
||||
|
||||
conn.execute(
|
||||
text("""
|
||||
ALTER TABLE nb_t_io_tl_map
|
||||
ADD CONSTRAINT fk_nb_t_io_tl_map_uid_id_nb_t_io_uid
|
||||
FOREIGN KEY (uid_id) REFERENCES nb_t_io_uid(id)
|
||||
NOT VALID
|
||||
""")
|
||||
)
|
||||
conn.execute(
|
||||
text("""
|
||||
ALTER TABLE nb_t_io_tl_map
|
||||
VALIDATE CONSTRAINT fk_nb_t_io_tl_map_uid_id_nb_t_io_uid
|
||||
""")
|
||||
)
|
||||
|
||||
logger.success('PG backfill: Foreign keys validated successfully')
|
||||
|
||||
|
||||
def _backfill_generic(conn: Connection) -> None:
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=conn)
|
||||
Hist = Base.classes.nb_t_io_tl_hist # noqa: N806
|
||||
Uid = Base.classes.nb_t_io_uid # noqa: N806
|
||||
Map = Base.classes.nb_t_io_tl_map # noqa: N806
|
||||
|
||||
with Session(conn) as session:
|
||||
count = session.query(Hist).count()
|
||||
if count == 0:
|
||||
return
|
||||
|
||||
logger.warning('tetris_stats: 正在生成 TETR.IO 玩家分页索引, 请不要关闭程序...')
|
||||
uid_map: dict[str, int] = {}
|
||||
|
||||
def refresh_uid_map() -> None:
|
||||
uids = session.query(Uid).all()
|
||||
uid_map.clear()
|
||||
uid_map.update({uid.user_unique_identifier: uid.id for uid in uids})
|
||||
|
||||
with Progress(
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
MofNCompleteColumn(),
|
||||
TaskProgressColumn(),
|
||||
RateColumn(),
|
||||
TimeRemainingColumn(),
|
||||
) as progress:
|
||||
total = progress.add_task('生成索引...', total=count)
|
||||
for hist in session.query(Hist).yield_per(1):
|
||||
data = hist.data
|
||||
if isinstance(data, str | bytes):
|
||||
msg = 'io tl map migration requires json object data'
|
||||
raise TypeError(msg)
|
||||
entries = data.get('data', {}).get('entries', []) if isinstance(data, dict) else []
|
||||
entry_info: list[tuple[str, int]] = []
|
||||
for index, entry in enumerate(entries):
|
||||
if isinstance(entry, dict):
|
||||
uid = entry.get('_id')
|
||||
if isinstance(uid, str):
|
||||
entry_info.append((uid, index))
|
||||
if not entry_info:
|
||||
progress.update(total, advance=1)
|
||||
continue
|
||||
|
||||
session.add_all([Uid(user_unique_identifier=uid) for uid, _ in entry_info if uid not in uid_map])
|
||||
session.flush()
|
||||
refresh_uid_map()
|
||||
session.add_all(
|
||||
[
|
||||
Map(
|
||||
stats_id=hist.stats_id,
|
||||
uid_id=uid_map[uid],
|
||||
hist_id=hist.id,
|
||||
entry_index=index,
|
||||
)
|
||||
for uid, index in entry_info
|
||||
]
|
||||
)
|
||||
session.flush()
|
||||
progress.update(total, advance=1)
|
||||
|
||||
|
||||
def backfill_mapping(conn: Connection) -> None:
|
||||
if conn.dialect.name == 'postgresql':
|
||||
logger.warning('tetris_stats: 检测到 PostgreSQL, 使用快速索引回填...')
|
||||
_backfill_postgresql(conn)
|
||||
_add_foreign_keys_postgresql(conn)
|
||||
return
|
||||
_backfill_generic(conn)
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
conn = op.get_bind()
|
||||
op.create_table(
|
||||
'nb_t_io_uid',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('user_unique_identifier', sa.String(length=24), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_uid')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_io_uid', schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
batch_op.f('ix_nb_t_io_uid_user_unique_identifier'),
|
||||
['user_unique_identifier'],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
if conn.dialect.name == 'postgresql':
|
||||
op.create_table(
|
||||
'nb_t_io_tl_map',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('stats_id', sa.Integer(), nullable=False),
|
||||
sa.Column('uid_id', sa.Integer(), nullable=False),
|
||||
sa.Column('hist_id', sa.Integer(), nullable=False),
|
||||
sa.Column('entry_index', sa.Integer(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_tl_map')),
|
||||
sa.UniqueConstraint('uid_id', 'hist_id', name='uq_nb_t_io_tl_map_uid_hist'),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
else:
|
||||
op.create_table(
|
||||
'nb_t_io_tl_map',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('stats_id', sa.Integer(), nullable=False),
|
||||
sa.Column('uid_id', sa.Integer(), nullable=False),
|
||||
sa.Column('hist_id', sa.Integer(), nullable=False),
|
||||
sa.Column('entry_index', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
['stats_id'],
|
||||
['nb_t_io_tl_stats.id'],
|
||||
name=op.f('fk_nb_t_io_tl_map_stats_id_nb_t_io_tl_stats'),
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
['uid_id'],
|
||||
['nb_t_io_uid.id'],
|
||||
name=op.f('fk_nb_t_io_tl_map_uid_id_nb_t_io_uid'),
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
['hist_id'],
|
||||
['nb_t_io_tl_hist.id'],
|
||||
name=op.f('fk_nb_t_io_tl_map_hist_id_nb_t_io_tl_hist'),
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_io_tl_map')),
|
||||
sa.UniqueConstraint('uid_id', 'hist_id', name='uq_nb_t_io_tl_map_uid_hist'),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
backfill_mapping(conn)
|
||||
|
||||
with op.batch_alter_table('nb_t_io_tl_map', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_tl_map_stats_id'), ['stats_id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_nb_t_io_tl_map_uid_id'), ['uid_id'], unique=False)
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
with op.batch_alter_table('nb_t_io_tl_map', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_tl_map_uid_id'))
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_tl_map_stats_id'))
|
||||
|
||||
op.drop_table('nb_t_io_tl_map')
|
||||
with op.batch_alter_table('nb_t_io_uid', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nb_t_io_uid_user_unique_identifier'))
|
||||
|
||||
op.drop_table('nb_t_io_uid')
|
||||
@@ -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
|
||||
|
||||
@@ -29,8 +28,8 @@ branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def migrate_old_data() -> None:
|
||||
from json import dumps, loads
|
||||
def migrate_old_data() -> None: # noqa: C901
|
||||
from json import dumps, loads # noqa: PLC0415
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=op.get_bind())
|
||||
@@ -47,6 +46,9 @@ def migrate_old_data() -> None:
|
||||
TimeRemainingColumn(),
|
||||
) as progress,
|
||||
):
|
||||
if session.query(OldHistoricalData).count() == 0:
|
||||
logger.info('空表, 跳过')
|
||||
return
|
||||
task_id = progress.add_task('[cyan]Migrating:', total=session.query(OldHistoricalData).count())
|
||||
pointer = 0
|
||||
while pointer < session.query(OldHistoricalData).order_by(desc(OldHistoricalData.id)).limit(1).one().id:
|
||||
@@ -106,6 +108,8 @@ def migrate_old_data() -> 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_tetriohistoricaldata',
|
||||
@@ -216,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,53 @@
|
||||
"""add compare delta config
|
||||
|
||||
迁移 ID: 6ecf383d646a
|
||||
父迁移: 1c5346b657d4
|
||||
创建时间: 2026-01-27 06:05:04.481654
|
||||
|
||||
"""
|
||||
|
||||
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 = '6ecf383d646a'
|
||||
down_revision: str | Sequence[str] | None = '1c5346b657d4'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
op.create_table(
|
||||
'nb_t_top_u_cfg',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('compare_delta', sa.Interval(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_top_u_cfg')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
op.create_table(
|
||||
'nb_t_tos_u_cfg',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('compare_delta', sa.Interval(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_nb_t_tos_u_cfg')),
|
||||
info={'bind_key': 'nonebot_plugin_tetris_stats'},
|
||||
)
|
||||
with op.batch_alter_table('nb_t_io_u_cfg', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('compare_delta', sa.Interval(), nullable=True))
|
||||
|
||||
|
||||
def downgrade(name: str = '') -> None:
|
||||
if name:
|
||||
return
|
||||
with op.batch_alter_table('nb_t_io_u_cfg', schema=None) as batch_op:
|
||||
batch_op.drop_column('compare_delta')
|
||||
|
||||
op.drop_table('nb_t_tos_u_cfg')
|
||||
op.drop_table('nb_t_top_u_cfg')
|
||||
@@ -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,16 +28,12 @@ depends_on: str | Sequence[str] | None = None
|
||||
def upgrade(name: str = '') -> None: # noqa: C901
|
||||
if name:
|
||||
return
|
||||
from nonebot_plugin_tetris_stats.version import __version__
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
if __version__ != '1.0.3':
|
||||
msg = '本迁移需要1.0.3版本, 请先锁定版本至1.0.3版本再执行本迁移'
|
||||
logger.critical(msg)
|
||||
raise RuntimeError(msg)
|
||||
|
||||
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,
|
||||
@@ -46,10 +42,6 @@ def upgrade(name: str = '') -> None: # noqa: C901
|
||||
TimeRemainingColumn,
|
||||
)
|
||||
|
||||
from nonebot_plugin_tetris_stats.game_data_processor.schemas import ( # type: ignore[import-untyped]
|
||||
BaseProcessedData,
|
||||
)
|
||||
|
||||
Base = automap_base() # noqa: N806
|
||||
Base.prepare(autoload_with=op.get_bind())
|
||||
HistoricalData = Base.classes.nonebot_plugin_tetris_stats_historicaldata # noqa: N806
|
||||
@@ -62,18 +54,33 @@ def upgrade(name: str = '') -> None: # noqa: C901
|
||||
def model_to_json(value: BaseModel) -> str:
|
||||
return value.json(by_alias=True)
|
||||
|
||||
models = BaseProcessedData.__subclasses__()
|
||||
|
||||
def json_to_model(value: str) -> BaseModel:
|
||||
for i in models:
|
||||
try:
|
||||
return type_validate_json(i, value)
|
||||
except ValidationError: # noqa: PERF203
|
||||
...
|
||||
raise ValueError
|
||||
|
||||
with Session(op.get_bind()) as session:
|
||||
count = session.query(HistoricalData).count()
|
||||
if count == 0:
|
||||
logger.info('空表, 跳过')
|
||||
return
|
||||
|
||||
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] # pyright: ignore[reportMissingImports] # noqa: PLC0415
|
||||
BaseProcessedData,
|
||||
)
|
||||
|
||||
models = BaseProcessedData.__subclasses__()
|
||||
|
||||
def json_to_model(value: str) -> BaseModel:
|
||||
for i in models:
|
||||
try:
|
||||
return type_validate_json(i, value)
|
||||
except ValidationError: # noqa: PERF203
|
||||
...
|
||||
raise ValueError
|
||||
|
||||
with Progress(
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
@@ -96,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,18 +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
|
||||
from nonebot_plugin_tetris_stats.version import __version__
|
||||
if op.get_bind().dialect.name == 'postgresql':
|
||||
return
|
||||
|
||||
if __version__ != '1.0.4':
|
||||
msg = '本迁移需要1.0.4版本, 请先锁定版本至1.0.4版本再执行本迁移'
|
||||
logger.critical(msg)
|
||||
raise RuntimeError(msg)
|
||||
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,
|
||||
@@ -42,11 +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 nonebot_plugin_tetris_stats.game_data_processor.schemas import BaseUser # type: ignore[import-untyped]
|
||||
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))
|
||||
@@ -60,37 +55,50 @@ def upgrade(name: str = '') -> None:
|
||||
Base.prepare(autoload_with=connection)
|
||||
HistoricalData = Base.classes.nonebot_plugin_tetris_stats_historicaldata # noqa: N806
|
||||
|
||||
models: list[type[BaseUser]] = BaseUser.__subclasses__()
|
||||
|
||||
def json_to_model(value: str) -> BaseUser:
|
||||
for i in models:
|
||||
try:
|
||||
return type_validate_json(i, value)
|
||||
except ValidationError: # noqa: PERF203
|
||||
...
|
||||
raise ValueError
|
||||
|
||||
with Session(op.get_bind()) as session:
|
||||
count = session.query(HistoricalData).count()
|
||||
with Progress(
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
MofNCompleteColumn(),
|
||||
TaskProgressColumn(),
|
||||
TimeRemainingColumn(),
|
||||
) as progress:
|
||||
task_id = progress.add_task('[cyan]Updateing:', total=count)
|
||||
for i in range(0, count, 100):
|
||||
for j in session.scalars(
|
||||
select(HistoricalData).where(HistoricalData.id > i).order_by(HistoricalData.id).limit(100)
|
||||
):
|
||||
model = json_to_model(j.game_user)
|
||||
if count == 0:
|
||||
logger.info('空表, 跳过')
|
||||
else:
|
||||
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 ( # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] # noqa: PLC0415
|
||||
BaseUser,
|
||||
)
|
||||
|
||||
models: list[type[BaseUser]] = BaseUser.__subclasses__()
|
||||
|
||||
def json_to_model(value: str) -> BaseUser:
|
||||
for i in models:
|
||||
try:
|
||||
j.user_unique_identifier = model.unique_identifier
|
||||
except ValueError:
|
||||
session.delete(j)
|
||||
progress.update(task_id, advance=1)
|
||||
session.commit()
|
||||
return type_validate_json(i, value)
|
||||
except ValidationError: # noqa: PERF203
|
||||
...
|
||||
raise ValueError
|
||||
|
||||
with Progress(
|
||||
TextColumn('[progress.description]{task.description}'),
|
||||
BarColumn(),
|
||||
MofNCompleteColumn(),
|
||||
TaskProgressColumn(),
|
||||
TimeRemainingColumn(),
|
||||
) as progress:
|
||||
task_id = progress.add_task('[cyan]Updateing:', total=count)
|
||||
for i in range(0, count, 100):
|
||||
for j in session.scalars(
|
||||
select(HistoricalData).where(HistoricalData.id > i).order_by(HistoricalData.id).limit(100)
|
||||
):
|
||||
model = json_to_model(j.game_user)
|
||||
try:
|
||||
j.user_unique_identifier = model.unique_identifier
|
||||
except ValueError:
|
||||
session.delete(j)
|
||||
progress.update(task_id, advance=1)
|
||||
session.commit()
|
||||
with op.batch_alter_table('nonebot_plugin_tetris_stats_historicaldata', schema=None) as batch_op:
|
||||
batch_op.alter_column('user_unique_identifier', existing_type=sa.VARCHAR(length=32), nullable=False)
|
||||
logger.success('database upgrade success')
|
||||
@@ -99,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:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from asyncio import Lock
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from enum import Enum, auto
|
||||
from typing import TYPE_CHECKING, Literal, TypeVar, overload
|
||||
|
||||
@@ -11,15 +11,19 @@ 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.duration import DEFAULT_COMPARE_DELTA
|
||||
from ..utils.typedefs import AllCommandType, BaseCommandType, GameType, TETRIOCommandType
|
||||
from .models import Bind, TriggerHistoricalDataV2
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..games.tetrio.api.models import TETRIOHistoricalData
|
||||
from ..games.tetrio.models import TETRIOUserConfig
|
||||
from ..games.top.api.models import TOPHistoricalData
|
||||
from ..games.top.models import TOPUserConfig
|
||||
from ..games.tos.api.models import TOSHistoricalData
|
||||
from ..games.tos.models import TOSUserConfig
|
||||
|
||||
|
||||
class BindStatus(Enum):
|
||||
@@ -42,6 +46,8 @@ async def create_or_update_bind(
|
||||
user: User,
|
||||
game_platform: GameType,
|
||||
game_account: str,
|
||||
*,
|
||||
verify: bool = False,
|
||||
) -> BindStatus:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
@@ -53,22 +59,41 @@ async def create_or_update_bind(
|
||||
user_id=user.id,
|
||||
game_platform=game_platform,
|
||||
game_account=game_account,
|
||||
verify=verify,
|
||||
)
|
||||
session.add(bind)
|
||||
message = BindStatus.SUCCESS
|
||||
status = BindStatus.SUCCESS
|
||||
else:
|
||||
bind.game_account = game_account
|
||||
message = BindStatus.UPDATE
|
||||
bind.verify = verify
|
||||
status = BindStatus.UPDATE
|
||||
await session.commit()
|
||||
return message
|
||||
return status
|
||||
|
||||
|
||||
T = TypeVar('T', 'TETRIOHistoricalData', 'TOPHistoricalData', 'TOSHistoricalData')
|
||||
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_HistoricalData = TypeVar('T_HistoricalData', 'TETRIOHistoricalData', 'TOPHistoricalData', 'TOSHistoricalData')
|
||||
|
||||
lock = Lock()
|
||||
|
||||
|
||||
async def anti_duplicate_add(model: T) -> None:
|
||||
async def anti_duplicate_add(model: T_HistoricalData) -> None:
|
||||
async with lock, get_session() as session:
|
||||
result = (
|
||||
await session.scalars(
|
||||
@@ -87,6 +112,19 @@ async def anti_duplicate_add(model: T) -> None:
|
||||
await session.commit()
|
||||
|
||||
|
||||
T_CONFIG = TypeVar('T_CONFIG', 'TETRIOUserConfig', 'TOPUserConfig', 'TOSUserConfig')
|
||||
|
||||
|
||||
async def resolve_compare_delta(
|
||||
config: type[T_CONFIG], session: AsyncSession, user_id: int, compare: timedelta | None
|
||||
) -> timedelta:
|
||||
return (
|
||||
compare
|
||||
or await session.scalar(select(config.compare_delta).where(config.id == user_id))
|
||||
or DEFAULT_COMPARE_DELTA
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@overload
|
||||
async def trigger(
|
||||
@@ -122,7 +160,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,
|
||||
|
||||
@@ -2,14 +2,14 @@ from collections.abc import Callable, Sequence
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from nonebot.compat import PYDANTIC_V2, type_validate_json
|
||||
from nonebot.compat import PYDANTIC_V2, type_validate_python
|
||||
from nonebot_plugin_orm import Model
|
||||
from pydantic import BaseModel, ValidationError
|
||||
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):
|
||||
@@ -30,27 +30,27 @@ class PydanticType(TypeDecorator):
|
||||
if PYDANTIC_V2:
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: Any | None, dialect: Dialect) -> str:
|
||||
def process_bind_param(self, value: Any | None, dialect: Dialect) -> dict | list:
|
||||
# 将 Pydantic 模型实例转换为 JSON
|
||||
if isinstance(value, tuple(self.models)):
|
||||
return value.model_dump_json(by_alias=True) # type: ignore[union-attr]
|
||||
return value.model_dump(mode='json', by_alias=True) # type: ignore[union-attr]
|
||||
raise TypeError
|
||||
else:
|
||||
|
||||
@override
|
||||
def process_bind_param(self, value: Any | None, dialect: Dialect) -> str:
|
||||
def process_bind_param(self, value: Any | None, dialect: Dialect) -> dict | list:
|
||||
# 将 Pydantic 模型实例转换为 JSON
|
||||
if isinstance(value, tuple(self.models)):
|
||||
return value.json(by_alias=True) # type: ignore[union-attr]
|
||||
return value.dict(by_alias=True) # type: ignore[union-attr]
|
||||
raise TypeError
|
||||
|
||||
@override
|
||||
def process_result_value(self, value: Any | None, dialect: Dialect) -> BaseModel:
|
||||
# 将 JSON 转换回 Pydantic 模型实例
|
||||
if isinstance(value, str | bytes):
|
||||
if isinstance(value, dict | list):
|
||||
for i in self.models:
|
||||
try:
|
||||
return type_validate_json(i, value)
|
||||
return type_validate_python(i, value)
|
||||
except ValidationError: # noqa: PERF203
|
||||
...
|
||||
raise ValueError
|
||||
@@ -65,13 +65,18 @@ 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]
|
||||
verify: Mapped[bool]
|
||||
|
||||
|
||||
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]
|
||||
|
||||
@@ -7,6 +7,7 @@ from nonebot.typing import T_Handler
|
||||
from nonebot_plugin_alconna import AlcMatches, Alconna, At, CommandMeta, on_alconna
|
||||
|
||||
from .. import ns
|
||||
from ..i18n import Lang
|
||||
from ..utils.exception import MessageFormatError, NeedCatchError
|
||||
|
||||
command: Alconna = Alconna(
|
||||
@@ -30,7 +31,7 @@ def add_block_handlers(handler: Callable[[T_Handler], T_Handler]) -> None:
|
||||
@handler
|
||||
async def _(bot: Bot, matcher: Matcher, target: At):
|
||||
if isinstance(target, At) and target.target == bot.self_id:
|
||||
await matcher.finish('不能查询bot的信息')
|
||||
await matcher.finish(Lang.interaction.wrong.query_bot())
|
||||
|
||||
|
||||
from . import tetrio, top, tos # noqa: F401, E402
|
||||
@@ -43,10 +44,10 @@ 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"查看帮助'
|
||||
+ Lang.help.usage(command=matches.header_result)
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
CANT_VERIFY_MESSAGE = '* 由于无法验证绑定信息, 不能保证查询到的用户为本人\n'
|
||||
@@ -2,8 +2,9 @@ from abc import ABC, abstractmethod
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
from typing_extensions import override
|
||||
|
||||
from ..utils.typing import GameType
|
||||
from ..utils.typedefs import GameType
|
||||
|
||||
T = TypeVar('T', bound=GameType)
|
||||
|
||||
@@ -13,6 +14,7 @@ class BaseUser(BaseModel, ABC, Generic[T]):
|
||||
|
||||
platform: T
|
||||
|
||||
@override
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if isinstance(other, BaseUser):
|
||||
return self.unique_identifier == other.unique_identifier
|
||||
@@ -22,3 +24,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, verify # noqa: A004, E402
|
||||
|
||||
main_command.add(command)
|
||||
|
||||
@@ -35,4 +35,6 @@ __all__ = [
|
||||
'query',
|
||||
'rank',
|
||||
'record',
|
||||
'unbind',
|
||||
'verify',
|
||||
]
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from asyncio import Lock
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import ClassVar
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
@@ -9,12 +9,15 @@ from nonebot.log import logger
|
||||
from yarl import URL
|
||||
|
||||
from ....config.config import config
|
||||
from ....utils.limit import limit
|
||||
from ....utils.request import Request
|
||||
from .schemas.base import FailedModel, SuccessModel
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
|
||||
request = Request(config.tetris.proxy.tetrio or config.tetris.proxy.main)
|
||||
request.request = limit(timedelta(seconds=1))(request.request) # type: ignore[method-assign] # pyright: ignore[reportAttributeAccessIssue]
|
||||
|
||||
|
||||
class Cache:
|
||||
@@ -29,7 +32,7 @@ class Cache:
|
||||
logger.debug(f'{url}: Cache hit!')
|
||||
return cached_data
|
||||
response_data = await request.request(url, extra_headers, enable_anti_cloudflare=True)
|
||||
parsed_data: SuccessModel | FailedModel = type_validate_json(SuccessModel | FailedModel, response_data) # type: ignore[arg-type]
|
||||
parsed_data: SuccessModel | FailedModel = type_validate_json(SuccessModel | FailedModel, response_data) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
if isinstance(parsed_data, SuccessModel):
|
||||
await cls.cache.add(
|
||||
url,
|
||||
|
||||
@@ -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
|
||||
@@ -18,11 +20,16 @@ async def by(
|
||||
by_type: Literal['league', 'xp', 'ar'], parameter: Parameter, x_session_id: UUID | None = None
|
||||
) -> BySuccessModel:
|
||||
model: By = type_validate_json(
|
||||
By, # type: ignore[arg-type]
|
||||
By, # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
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):
|
||||
@@ -62,7 +69,7 @@ async def records(
|
||||
match records_type:
|
||||
case '40l' | 'blitz':
|
||||
model = type_validate_json(
|
||||
Solo, # type: ignore[arg-type]
|
||||
Solo, # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
await get(
|
||||
BASE_URL / 'records' / f'{records_type}{scope}{revolution_id if revolution_id is not None else ""}',
|
||||
parameter,
|
||||
@@ -70,17 +77,14 @@ async def records(
|
||||
)
|
||||
case 'zenith' | 'zenithex':
|
||||
model = type_validate_json(
|
||||
Zenith, # type: ignore[arg-type]
|
||||
Zenith, # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
await get(
|
||||
BASE_URL / 'records' / f'{records_type}{scope}{revolution_id if revolution_id is not None else ""}',
|
||||
parameter,
|
||||
),
|
||||
)
|
||||
case _:
|
||||
msg = f'records_type: {records_type} is not supported'
|
||||
raise ValueError(msg)
|
||||
if isinstance(model, FailedModel):
|
||||
msg = f'排行榜信息请求错误:\n{model.error}' # type: ignore[attr-defined]
|
||||
msg = f'排行榜信息请求错误:\n{model.error}'
|
||||
raise RequestError(msg)
|
||||
return model
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -11,6 +11,7 @@ from ..constant import BASE_URL, USER_ID, USER_NAME
|
||||
from .cache import Cache
|
||||
from .models import TETRIOHistoricalData
|
||||
from .schemas.base import FailedModel
|
||||
from .schemas.labs.leagueflow import LeagueFlow, LeagueFlowSuccess
|
||||
from .schemas.records.solo import Solo as SoloRecord
|
||||
from .schemas.records.solo import SoloSuccessModel as RecordsSoloSuccessModel
|
||||
from .schemas.summaries import (
|
||||
@@ -26,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):
|
||||
@@ -45,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:
|
||||
@@ -84,10 +85,11 @@ class Player:
|
||||
self._user_info: UserInfoSuccess | None = None
|
||||
self._summaries: dict[Summaries, SummariesModel] = {}
|
||||
self._records: dict[RecordKey, RecordsSoloSuccessModel] = {}
|
||||
self._leagueflow: LeagueFlowSuccess | None = None
|
||||
|
||||
@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:
|
||||
@@ -112,7 +114,7 @@ class Player:
|
||||
"""Get User Info"""
|
||||
if self._user_info is None:
|
||||
raw_user_info = await Cache.get(BASE_URL / 'users' / self._request_user_parameter)
|
||||
user_info: UserInfo = type_validate_json(UserInfo, raw_user_info) # type: ignore[arg-type]
|
||||
user_info: UserInfo = type_validate_json(UserInfo, raw_user_info) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
if isinstance(user_info, FailedModel):
|
||||
msg = f'用户信息请求错误:\n{user_info.error}'
|
||||
raise RequestError(msg)
|
||||
@@ -144,7 +146,7 @@ class Player:
|
||||
BASE_URL / 'users' / self._request_user_parameter / 'summaries' / summaries_type
|
||||
)
|
||||
summaries: SummariesModel | FailedModel = type_validate_json(
|
||||
self.__SUMMARIES_MAPPING[summaries_type] | FailedModel, # type: ignore[arg-type]
|
||||
self.__SUMMARIES_MAPPING[summaries_type] | FailedModel, # type: ignore[assignment, arg-type] # pyright: ignore[reportArgumentType] #! waiting for [PEP 747](https://peps.python.org/pep-0747/)
|
||||
raw_summaries,
|
||||
)
|
||||
if isinstance(summaries, FailedModel):
|
||||
@@ -161,6 +163,18 @@ class Player:
|
||||
)
|
||||
return self._summaries[summaries_type]
|
||||
|
||||
async def get_leagueflow(self) -> LeagueFlowSuccess:
|
||||
if self._leagueflow is None:
|
||||
leagueflow: LeagueFlow = type_validate_json(
|
||||
LeagueFlow, # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
await Cache.get(BASE_URL / 'labs/leagueflow' / self._request_user_parameter),
|
||||
)
|
||||
if isinstance(leagueflow, FailedModel):
|
||||
msg = f'League 历史记录请求错误:\n{leagueflow.error}'
|
||||
raise RequestError(msg)
|
||||
self._leagueflow = leagueflow
|
||||
return self._leagueflow
|
||||
|
||||
@property
|
||||
async def sprint(self) -> SummariesSoloSuccessModel:
|
||||
return await self.get_summaries('40l')
|
||||
@@ -213,7 +227,7 @@ class Player:
|
||||
raw_records = await Cache.get(
|
||||
BASE_URL / 'users' / self._request_user_parameter / 'records' / mode_type / records_type,
|
||||
)
|
||||
records: RecordsSoloSuccessModel | FailedModel = type_validate_json(SoloRecord, raw_records) # type: ignore[arg-type]
|
||||
records: RecordsSoloSuccessModel | FailedModel = type_validate_json(SoloRecord, raw_records) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
if isinstance(records, FailedModel):
|
||||
msg = f'用户Summaries数据请求错误:\n{records.error}'
|
||||
raise RequestError(msg)
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ...typing import Prisecter
|
||||
from ...typedefs import Prisecter
|
||||
|
||||
|
||||
class AggregateStats(BaseModel):
|
||||
@@ -50,19 +50,21 @@ class P(BaseModel):
|
||||
return Prisecter(f'{self.pri}:{self.sec}:{self.ter}')
|
||||
|
||||
|
||||
# fmt: off
|
||||
class ArCounts(BaseModel):
|
||||
bronze: int | None = Field(default=None, alias='1')
|
||||
silver: int | None = Field(default=None, alias='2')
|
||||
gold: int | None = Field(default=None, alias='3')
|
||||
bronze: int | None = Field(default=None, alias='1')
|
||||
silver: int | None = Field(default=None, alias='2')
|
||||
gold: int | None = Field(default=None, alias='3')
|
||||
platinum: int | None = Field(default=None, alias='4')
|
||||
diamond: int | None = Field(default=None, alias='5')
|
||||
issued: int | None = Field(default=None, alias='100')
|
||||
top3: int | None = Field(default=None, alias='t3')
|
||||
top5: int | None = Field(default=None, alias='t5')
|
||||
top10: int | None = Field(default=None, alias='t10')
|
||||
top25: int | None = Field(default=None, alias='t25')
|
||||
top50: int | None = Field(default=None, alias='t50')
|
||||
top100: int | None = Field(default=None, alias='t100')
|
||||
diamond: int | None = Field(default=None, alias='5')
|
||||
issued: int | None = Field(default=None, alias='100')
|
||||
top3: int | None = Field(default=None, alias='t3')
|
||||
top5: int | None = Field(default=None, alias='t5')
|
||||
top10: int | None = Field(default=None, alias='t10')
|
||||
top25: int | None = Field(default=None, alias='t25')
|
||||
top50: int | None = Field(default=None, alias='t50')
|
||||
top100: int | None = Field(default=None, alias='t100')
|
||||
# fmt: on
|
||||
|
||||
|
||||
class Cache(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
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
from datetime import datetime
|
||||
from enum import IntEnum
|
||||
from typing import Literal, NamedTuple
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..base import FailedModel
|
||||
from ..base import SuccessModel as BaseSuccessModel
|
||||
|
||||
|
||||
class Result(IntEnum):
|
||||
VICTORY = 1
|
||||
DEFEAT = 2
|
||||
VICTORY_BY_DISQUALIFICATION = 3
|
||||
DEFEAT_BY_DISQUALIFICATION = 4
|
||||
TIE = 5
|
||||
NO_CONTEST = 6
|
||||
MATCH_NULLIFIED = 7
|
||||
|
||||
|
||||
class Point(NamedTuple):
|
||||
timestamp_offset: int
|
||||
result: Result
|
||||
post_match_tr: int
|
||||
opponent_pre_match_tr: int
|
||||
"""If the opponent was unranked, same as post_match_tr."""
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
start_time: datetime = Field(..., alias='startTime')
|
||||
points: list[Point] = Field(..., min_length=1)
|
||||
|
||||
|
||||
class Empty(BaseModel):
|
||||
start_time: Literal[9007199254740991] = Field(..., alias='startTime')
|
||||
points: list = Field(..., max_length=0)
|
||||
|
||||
|
||||
class LeagueFlowSuccess(BaseSuccessModel):
|
||||
data: Data | Empty
|
||||
|
||||
|
||||
LeagueFlow = LeagueFlowSuccess | FailedModel
|
||||
@@ -1,8 +1,9 @@
|
||||
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):
|
||||
@@ -12,4 +13,6 @@ class Parameter(BaseModel):
|
||||
country: str | None = None
|
||||
|
||||
def to_params(self) -> dict[str, Any]:
|
||||
return self.model_dump(exclude_defaults=True)
|
||||
if PYDANTIC_V2:
|
||||
return self.model_dump(exclude_defaults=True)
|
||||
return self.dict(exclude_defaults=True)
|
||||
|
||||
@@ -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,94 @@
|
||||
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
|
||||
PERCENTILEINVARIANT = 7
|
||||
|
||||
|
||||
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):
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
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:
|
||||
from pydantic import field_validator
|
||||
else:
|
||||
from pydantic import validator
|
||||
|
||||
|
||||
class PastInner(BaseModel):
|
||||
season: str
|
||||
@@ -75,6 +81,24 @@ class NeverRatedData(BaseData):
|
||||
percentile: Literal[-1]
|
||||
percentile_rank: Literal['z']
|
||||
|
||||
if PYDANTIC_V2:
|
||||
|
||||
@field_validator('apm', 'pps', 'vs', mode='before')
|
||||
@classmethod
|
||||
def _(cls, value: float | None) -> float:
|
||||
if value is None:
|
||||
return 0
|
||||
return value
|
||||
|
||||
else:
|
||||
|
||||
@validator('apm', 'pps', 'vs', pre=True, always=True)
|
||||
@classmethod
|
||||
def _(cls, value: float | None) -> float:
|
||||
if value is None:
|
||||
return 0
|
||||
return value
|
||||
|
||||
|
||||
class RatedData(BaseData):
|
||||
gamesplayed: int
|
||||
@@ -98,5 +122,9 @@ class RatedData(BaseData):
|
||||
percentile_rank: str
|
||||
|
||||
|
||||
class InvalidData(BaseModel):
|
||||
"""I don't know what osk is doing, but the return value is an empty dictionary"""
|
||||
|
||||
|
||||
class LeagueSuccessModel(SuccessModel):
|
||||
data: NeverPlayedData | NeverRatedData | RatedData
|
||||
data: NeverPlayedData | NeverRatedData | RatedData | InvalidData
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -33,6 +33,11 @@ class Distinguishment(BaseModel):
|
||||
type: str
|
||||
|
||||
|
||||
class OldUsernames(BaseModel):
|
||||
username: str
|
||||
ts: datetime
|
||||
|
||||
|
||||
class Data(BaseModel):
|
||||
id: str = Field(default=..., alias='_id')
|
||||
username: str
|
||||
@@ -65,6 +70,7 @@ class Data(BaseModel):
|
||||
achievements: list[int]
|
||||
ar: int
|
||||
ar_counts: ArCounts
|
||||
oldusernames: list[OldUsernames]
|
||||
|
||||
|
||||
class UserInfoSuccess(BaseSuccessModel):
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Literal, NewType
|
||||
|
||||
S1ValidRank = Literal[
|
||||
'x+',
|
||||
'x',
|
||||
'u',
|
||||
'ss',
|
||||
@@ -1,21 +1,26 @@
|
||||
from asyncio import gather
|
||||
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 ...i18n import Lang
|
||||
from ...utils.host import get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.base import Avatar, People
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.render.schemas.bind import Bind
|
||||
from . import alc, command, get_player
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
@@ -41,9 +46,45 @@ alc.shortcut(
|
||||
humanized='io绑定',
|
||||
)
|
||||
|
||||
try:
|
||||
from nonebot.adapters.discord import MessageCreateEvent
|
||||
|
||||
@alc.assign('TETRIO.bind')
|
||||
async def _(_: MessageCreateEvent, 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,
|
||||
command_type='bind',
|
||||
command_args=[],
|
||||
):
|
||||
user, user_info = await gather(account.user, account.get_info())
|
||||
verify = (
|
||||
user_info.data.connections.discord is not None
|
||||
and user_info.data.connections.discord.id == event_session.user.id
|
||||
)
|
||||
async with get_session() as session:
|
||||
bind_status = await create_or_update_bind(
|
||||
session=session,
|
||||
user=nb_user,
|
||||
game_platform=GAME_TYPE,
|
||||
game_account=user.unique_identifier,
|
||||
verify=verify,
|
||||
)
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
await UniMessage.image(
|
||||
raw=await make_bind_image(
|
||||
player=account,
|
||||
event_session=event_session,
|
||||
interface=interface,
|
||||
verify=verify,
|
||||
)
|
||||
).finish()
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
@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,
|
||||
@@ -59,28 +100,45 @@ async def _(nb_user: User, account: Player, event_session: EventSession, bot_inf
|
||||
game_account=user.unique_identifier,
|
||||
)
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/binding',
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
status='unknown',
|
||||
user=People(
|
||||
avatar=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}')
|
||||
% {'revision': avatar_revision}
|
||||
)
|
||||
if (avatar_revision := (await account.avatar_revision)) is not None and avatar_revision != 0
|
||||
else Avatar(type='identicon', hash=md5(user.ID.encode()).hexdigest()), # noqa: S324
|
||||
name=user.name.upper(),
|
||||
),
|
||||
bot=People(
|
||||
avatar=await get_avatar(bot_info, 'Data URI', '../../static/logo/logo.svg'),
|
||||
name=bot_info.user_name,
|
||||
),
|
||||
command='io查我',
|
||||
),
|
||||
await UniMessage.image(
|
||||
raw=await make_bind_image(
|
||||
player=account,
|
||||
event_session=event_session,
|
||||
interface=interface,
|
||||
verify=None,
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(raw=await screenshot(f'http://{netloc}/host/{page_hash}.html')).finish()
|
||||
).finish()
|
||||
|
||||
|
||||
async def make_bind_image(
|
||||
player: Player, event_session: Uninfo, interface: QryItrface, *, verify: bool | None = None
|
||||
) -> bytes:
|
||||
(user, avatar_revision) = await gather(player.user, player.avatar_revision)
|
||||
return await render_image(
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
type='unknown' if verify is None else 'success' if verify else 'unverified',
|
||||
user=People(
|
||||
avatar=str(
|
||||
URL(f'http://{get_self_netloc()}/host/resource/tetrio/avatars/{user.ID}')
|
||||
% {'revision': avatar_revision}
|
||||
)
|
||||
if 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=Lang.prompt.io_check(),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
from datetime import timedelta
|
||||
|
||||
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
|
||||
|
||||
from ...db import trigger
|
||||
from ...i18n import Lang
|
||||
from ...utils.duration import parse_duration
|
||||
from . import alc, command
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TETRIOUserConfig
|
||||
from .typing import Template
|
||||
from .typedefs import Template
|
||||
|
||||
command.add(
|
||||
Subcommand(
|
||||
@@ -22,6 +26,12 @@ command.add(
|
||||
alias=['-DT', 'DefaultTemplate'],
|
||||
help_text='设置默认查询模板',
|
||||
),
|
||||
Option(
|
||||
'--default-compare',
|
||||
Arg('compare', parse_duration, notice='对比时间距离'),
|
||||
alias=['-DC', 'DefaultCompare'],
|
||||
help_text='设置默认对比时间距离',
|
||||
),
|
||||
help_text='TETR.IO 查询个性化配置',
|
||||
),
|
||||
)
|
||||
@@ -34,18 +44,28 @@ 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 | None = None,
|
||||
compare: timedelta | None = None,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='config',
|
||||
command_args=[f'--default-template {template}'],
|
||||
command_args=([f'--default-template {template}'] if template is not None else [])
|
||||
+ ([f'--default-compare {compare}'] if compare is not None else []),
|
||||
):
|
||||
config = (await session.scalars(select(TETRIOUserConfig).where(TETRIOUserConfig.id == user.id))).one_or_none()
|
||||
if config is None:
|
||||
config = TETRIOUserConfig(id=user.id, query_template=template)
|
||||
config = TETRIOUserConfig(id=user.id, query_template=template or 'v1', compare_delta=compare)
|
||||
session.add(config)
|
||||
else:
|
||||
config.query_template = template
|
||||
if template is not None:
|
||||
config.query_template = template
|
||||
if compare is not None:
|
||||
config.compare_delta = compare
|
||||
await session.commit()
|
||||
await UniMessage('配置成功').finish()
|
||||
await UniMessage(Lang.bind.config_success()).finish()
|
||||
|
||||
@@ -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,19 @@
|
||||
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.screenshot import screenshot
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.v2.tetrio.user.list import Data, List, TetraLeague, User
|
||||
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,12 +30,13 @@ 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,
|
||||
country: str | None = None,
|
||||
):
|
||||
country = country.upper() if country is not None else None
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
@@ -56,17 +57,19 @@ async def _(
|
||||
country=country,
|
||||
)
|
||||
league = await by('league', parameter)
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v2/tetrio/user/list',
|
||||
await UniMessage.image(
|
||||
raw=await render_image(
|
||||
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),
|
||||
@@ -79,12 +82,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:
|
||||
await UniMessage.image(raw=await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')).finish()
|
||||
).finish()
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from nonebot_plugin_orm import Model
|
||||
from sqlalchemy import DateTime, ForeignKey, String
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, Interval, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column, relationship
|
||||
|
||||
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))
|
||||
compare_delta: Mapped[timedelta | None] = mapped_column(Interval(native=True), nullable=True)
|
||||
|
||||
|
||||
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 +29,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 +43,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 +58,23 @@ 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')
|
||||
|
||||
|
||||
class TETRIOUserUniqueIdentifier(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_uid'
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
user_unique_identifier: Mapped[str] = mapped_column(String(24), unique=True, index=True)
|
||||
|
||||
|
||||
class TETRIOLeagueUserMap(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_io_tl_map'
|
||||
__table_args__ = (UniqueConstraint('uid_id', 'hist_id', name='uq_nb_t_io_tl_map_uid_hist'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(init=False, primary_key=True)
|
||||
stats_id: Mapped[int] = mapped_column(ForeignKey('nb_t_io_tl_stats.id'), index=True)
|
||||
uid_id: Mapped[int] = mapped_column(ForeignKey('nb_t_io_uid.id'), index=True)
|
||||
hist_id: Mapped[int] = mapped_column(ForeignKey('nb_t_io_tl_hist.id'))
|
||||
entry_index: Mapped[int] = mapped_column(Integer)
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
from asyncio import gather
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import md5
|
||||
from typing import TypeVar
|
||||
|
||||
from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot import get_driver
|
||||
from nonebot.adapters import Event
|
||||
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_user import User as NBUser
|
||||
from nonebot_plugin_user import get_user
|
||||
from sqlalchemy import select
|
||||
from yarl import URL
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...utils.host import HostPage, get_self_netloc
|
||||
from ...utils.metrics import get_metrics
|
||||
from ...utils.render import render
|
||||
from ...utils.render.schemas.base import Avatar
|
||||
from ...utils.render.schemas.tetrio.user.info_v2 import (
|
||||
Badge,
|
||||
Blitz,
|
||||
Sprint,
|
||||
Statistic,
|
||||
TetraLeague,
|
||||
TetraLeagueStatistic,
|
||||
Zen,
|
||||
)
|
||||
from ...utils.render.schemas.tetrio.user.info_v2 import Info as V2TemplateInfo
|
||||
from ...utils.render.schemas.tetrio.user.info_v2 import User as V2TemplateUser
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.typing import Me
|
||||
from .. import add_block_handlers, alc
|
||||
from ..constant import CANT_VERIFY_MESSAGE
|
||||
from . import command, get_player
|
||||
from .api import Player
|
||||
from .api.schemas.summaries.league import NeverPlayedData, NeverRatedData
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TETRIOUserConfig
|
||||
from .typing import Template
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
command.add(
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
Arg(
|
||||
'target',
|
||||
At | Me,
|
||||
notice='@想要查询的人 / 自己',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='TETR.IO 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
Option(
|
||||
'--template',
|
||||
Arg('template', Template),
|
||||
alias=['-T'],
|
||||
help_text='要使用的查询模板',
|
||||
),
|
||||
help_text='查询 TETR.IO 游戏信息',
|
||||
),
|
||||
)
|
||||
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:查询|查|query|stats)',
|
||||
command='tstats TETR.IO query',
|
||||
humanized='io查',
|
||||
)
|
||||
alc.shortcut(
|
||||
'fkosk',
|
||||
command='tstats TETR.IO query',
|
||||
arguments=['我'],
|
||||
fuzzy=False,
|
||||
humanized='An Easter egg!',
|
||||
)
|
||||
|
||||
add_block_handlers(alc.assign('TETRIO.query'))
|
||||
|
||||
|
||||
@alc.assign('TETRIO.query')
|
||||
async def _( # noqa: PLR0913
|
||||
user: NBUser,
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: EventSession,
|
||||
template: Template | None = None,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[f'--default-template {template}'] if template is not None else [],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=await get_user(
|
||||
event_session.platform, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if template is None:
|
||||
template = await session.scalar(
|
||||
select(TETRIOUserConfig.query_template).where(TETRIOUserConfig.id == user.id)
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = UniMessage(CANT_VERIFY_MESSAGE)
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
await (message + UniMessage.image(raw=await make_query_image_v2(player))).finish()
|
||||
|
||||
|
||||
@alc.assign('TETRIO.query')
|
||||
async def _(user: NBUser, account: Player, event_session: EventSession, template: Template | None = None):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[f'--default-template {template}'] if template is not None else [],
|
||||
):
|
||||
async with get_session() as session:
|
||||
if template is None:
|
||||
template = await session.scalar(
|
||||
select(TETRIOUserConfig.query_template).where(TETRIOUserConfig.id == user.id)
|
||||
)
|
||||
await (UniMessage.image(raw=await make_query_image_v2(account))).finish()
|
||||
|
||||
|
||||
N = TypeVar('N', int, float)
|
||||
|
||||
|
||||
def handling_special_value(value: N) -> N | None:
|
||||
return value if value != -1 else None
|
||||
|
||||
|
||||
async def make_query_image_v2(player: Player) -> bytes:
|
||||
(
|
||||
(user, user_info, league, sprint, blitz, zen),
|
||||
(avatar_revision, banner_revision),
|
||||
) = await gather(
|
||||
gather(player.user, player.get_info(), player.league, player.sprint, player.blitz, player.zen),
|
||||
gather(player.avatar_revision, player.banner_revision),
|
||||
)
|
||||
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
|
||||
else:
|
||||
sprint_value = 'N/A'
|
||||
|
||||
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'
|
||||
elif game_time // 60 > 0:
|
||||
play_time = f'{game_time//60:.0f}m {game_time % 60:.0f}s'
|
||||
else:
|
||||
play_time = f'{game_time:.0f}s'
|
||||
else:
|
||||
play_time = game_time
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v2/tetrio/user/info',
|
||||
V2TemplateInfo(
|
||||
user=V2TemplateUser(
|
||||
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,
|
||||
avatar=str(
|
||||
URL(f'http://{netloc}/host/resource/tetrio/avatars/{user.ID}') % {'revision': avatar_revision}
|
||||
)
|
||||
if avatar_revision is not None and avatar_revision != 0
|
||||
else Avatar(
|
||||
type='identicon',
|
||||
hash=md5(user.ID.encode()).hexdigest(), # noqa: S324
|
||||
),
|
||||
badges=[
|
||||
Badge(
|
||||
id=i.id,
|
||||
description=i.label,
|
||||
group=i.group,
|
||||
receive_at=i.ts if isinstance(i.ts, datetime) else None,
|
||||
)
|
||||
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,
|
||||
playtime=play_time,
|
||||
join_at=user_info.data.ts,
|
||||
),
|
||||
tetra_league=TetraLeague(
|
||||
rank=league.data.rank,
|
||||
highest_rank='z' if isinstance(league.data, NeverRatedData) else league.data.bestrank,
|
||||
tr=round(league.data.tr, 2),
|
||||
glicko=round(league.data.glicko, 2),
|
||||
rd=round(league.data.rd, 2),
|
||||
global_rank=league.data.standing,
|
||||
country_rank=league.data.standing_local,
|
||||
pps=(metrics := get_metrics(pps=league.data.pps, apm=league.data.apm, vs=league.data.vs)).pps,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
statistic=TetraLeagueStatistic(total=league.data.gamesplayed, wins=league.data.gameswon),
|
||||
decaying=league.data.decaying,
|
||||
history=None,
|
||||
)
|
||||
if not isinstance(league.data, NeverPlayedData)
|
||||
else None,
|
||||
statistic=Statistic(
|
||||
total=handling_special_value(user_info.data.gamesplayed),
|
||||
wins=handling_special_value(user_info.data.gameswon),
|
||||
),
|
||||
sprint=Sprint(
|
||||
time=sprint_value,
|
||||
global_rank=sprint.data.rank,
|
||||
play_at=sprint.data.record.ts,
|
||||
)
|
||||
if sprint.data.record is not None
|
||||
else None,
|
||||
blitz=Blitz(
|
||||
score=blitz.data.record.results.stats.score,
|
||||
global_rank=blitz.data.rank,
|
||||
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),
|
||||
),
|
||||
),
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{netloc}/host/{page_hash}.html')
|
||||
167
nonebot_plugin_tetris_stats/games/tetrio/query/__init__.py
Normal file
167
nonebot_plugin_tetris_stats/games/tetrio/query/__init__.py
Normal file
@@ -0,0 +1,167 @@
|
||||
from datetime import timedelta, timezone
|
||||
|
||||
from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot import get_driver
|
||||
from nonebot.adapters import Event
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot_plugin_alconna import Args, At, Option, Subcommand
|
||||
from nonebot_plugin_alconna.uniseg import Image, UniMessage
|
||||
from nonebot_plugin_orm import get_session
|
||||
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
|
||||
|
||||
from ....db import query_bind_info, resolve_compare_delta, trigger
|
||||
from ....i18n import Lang
|
||||
from ....utils.duration import parse_duration
|
||||
from ....utils.exception import FallbackError
|
||||
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 ..typedefs import Template
|
||||
from .v1 import make_query_image_v1
|
||||
from .v2 import make_query_image_v2
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
driver = get_driver()
|
||||
|
||||
command.add(
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
Arg(
|
||||
'target',
|
||||
At | Me,
|
||||
notice='@想要查询的人 / 自己',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
Arg(
|
||||
'account',
|
||||
get_player,
|
||||
notice='TETR.IO 用户名 / ID',
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
Option(
|
||||
'--template',
|
||||
Arg('template', Template),
|
||||
alias=['-T'],
|
||||
help_text='要使用的查询模板',
|
||||
),
|
||||
Option(
|
||||
'--compare',
|
||||
Arg('compare', parse_duration),
|
||||
alias=['-C'],
|
||||
help_text='指定对比时间距离',
|
||||
),
|
||||
help_text='查询 TETR.IO 游戏信息',
|
||||
),
|
||||
)
|
||||
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:查询|查|query|stats)',
|
||||
command='tstats TETR.IO query',
|
||||
humanized='io查',
|
||||
)
|
||||
alc.shortcut(
|
||||
'fkosk',
|
||||
command='tstats TETR.IO query',
|
||||
arguments=['我'],
|
||||
fuzzy=False,
|
||||
humanized='An Easter egg!',
|
||||
)
|
||||
|
||||
add_block_handlers(alc.assign('TETRIO.query'))
|
||||
|
||||
|
||||
async def make_query_result(player: Player, template: Template, compare_delta: timedelta) -> UniMessage:
|
||||
if template == 'v1':
|
||||
try:
|
||||
return UniMessage.image(raw=await make_query_image_v1(player, compare_delta))
|
||||
except FallbackError:
|
||||
template = 'v2'
|
||||
if template == 'v2':
|
||||
return UniMessage.image(raw=await make_query_image_v2(player))
|
||||
return None
|
||||
|
||||
|
||||
@alc.assign('TETRIO.query')
|
||||
async def _( # noqa: PLR0913
|
||||
user: NBUser,
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: Uninfo,
|
||||
template: Template | None = None,
|
||||
compare: timedelta | None = None,
|
||||
):
|
||||
command_args: list[str] = []
|
||||
if template is not None:
|
||||
command_args.append(f'--template {template}')
|
||||
if compare is not None:
|
||||
command_args.append(f'--compare {compare}')
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=command_args,
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=await get_user(
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if template is None:
|
||||
template = await session.scalar(
|
||||
select(TETRIOUserConfig.query_template).where(TETRIOUserConfig.id == user.id)
|
||||
)
|
||||
compare_delta = await resolve_compare_delta(TETRIOUserConfig, session, user.id, compare)
|
||||
if bind is None:
|
||||
await matcher.finish(Lang.bind.not_found())
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
await (
|
||||
UniMessage.i18n(Lang.interaction.warning.unverified)
|
||||
+ (
|
||||
UniMessage('\n')
|
||||
if not (result := await make_query_result(player, template or 'v1', compare_delta)).has(Image)
|
||||
else UniMessage()
|
||||
)
|
||||
+ result
|
||||
).finish()
|
||||
|
||||
|
||||
@alc.assign('TETRIO.query')
|
||||
async def _(
|
||||
user: NBUser,
|
||||
account: Player,
|
||||
event_session: Uninfo,
|
||||
template: Template | None = None,
|
||||
compare: timedelta | None = None,
|
||||
):
|
||||
command_args: list[str] = []
|
||||
if template is not None:
|
||||
command_args.append(f'--template {template}')
|
||||
if compare is not None:
|
||||
command_args.append(f'--compare {compare}')
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=command_args,
|
||||
):
|
||||
async with get_session() as session:
|
||||
if template is None:
|
||||
template = await session.scalar(
|
||||
select(TETRIOUserConfig.query_template).where(TETRIOUserConfig.id == user.id)
|
||||
)
|
||||
compare_delta = await resolve_compare_delta(TETRIOUserConfig, session, user.id, compare)
|
||||
await (await make_query_result(account, template or 'v1', compare_delta)).finish()
|
||||
56
nonebot_plugin_tetris_stats/games/tetrio/query/tools.py
Normal file
56
nonebot_plugin_tetris_stats/games/tetrio/query/tools.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from collections.abc import Callable
|
||||
from datetime import timedelta
|
||||
from typing import TypeVar, overload
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from ....utils.exception import FallbackError
|
||||
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[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 = [
|
||||
HistoryData(
|
||||
record_at=start_time + timedelta(milliseconds=i.timestamp_offset),
|
||||
score=i.post_match_tr,
|
||||
)
|
||||
for i in leagueflow.data.points
|
||||
if start_time + timedelta(milliseconds=i.timestamp_offset)
|
||||
]
|
||||
return ret if handle is None else handle(ret)
|
||||
|
||||
|
||||
N = TypeVar('N', int, float)
|
||||
|
||||
|
||||
def handling_special_value(value: N) -> N | None:
|
||||
return value if value != -1 else None
|
||||
|
||||
|
||||
L = TypeVar('L', NeverPlayedData, NeverRatedData, RatedData)
|
||||
|
||||
|
||||
@overload
|
||||
def get_league_data(user_info: LeagueSuccessModel, league_type: type[L]) -> L: ...
|
||||
@overload
|
||||
def get_league_data(
|
||||
user_info: LeagueSuccessModel, league_type: None = None
|
||||
) -> NeverPlayedData | NeverRatedData | RatedData: ...
|
||||
def get_league_data(
|
||||
user_info: LeagueSuccessModel, league_type: type[L] | None = None
|
||||
) -> L | NeverPlayedData | NeverRatedData | RatedData:
|
||||
league = user_info.data
|
||||
if isinstance(league, InvalidData):
|
||||
raise FallbackError
|
||||
if league_type is None:
|
||||
return league
|
||||
if isinstance(league, league_type):
|
||||
return league
|
||||
raise FallbackError
|
||||
291
nonebot_plugin_tetris_stats/games/tetrio/query/v1.py
Normal file
291
nonebot_plugin_tetris_stats/games/tetrio/query/v1.py
Normal file
@@ -0,0 +1,291 @@
|
||||
from asyncio import gather
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from hashlib import md5
|
||||
from typing import Literal, NamedTuple
|
||||
|
||||
from nonebot_plugin_orm import AsyncSession, get_session
|
||||
from sqlalchemy import func, select
|
||||
from yarl import URL
|
||||
|
||||
from ....utils.chart import get_split, get_value_bounds, handle_history_data
|
||||
from ....utils.host import get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import TetrisMetricsProWithPPSVS, get_metrics
|
||||
from ....utils.render import render_image
|
||||
from ....utils.render.schemas.base import Avatar, Trending
|
||||
from ....utils.render.schemas.v1.base import History
|
||||
from ....utils.render.schemas.v1.tetrio.info import Info, Multiplayer, Singleplayer, User
|
||||
from ..api import Player
|
||||
from ..api.models import TETRIOHistoricalData
|
||||
from ..api.schemas.leaderboards.by import Entry, InvalidEntry
|
||||
from ..api.schemas.summaries.league import LeagueSuccessModel, NeverRatedData, RatedData
|
||||
from ..constant import TR_MAX, TR_MIN
|
||||
from ..models import TETRIOLeagueHistorical, TETRIOLeagueUserMap, TETRIOUserUniqueIdentifier
|
||||
from .tools import flow_to_history, get_league_data
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
|
||||
class Trends(NamedTuple):
|
||||
pps: Trending = Trending.KEEP
|
||||
apm: Trending = Trending.KEEP
|
||||
adpm: Trending = Trending.KEEP
|
||||
|
||||
|
||||
class HistoricalSnapshot(NamedTuple):
|
||||
metrics: TetrisMetricsProWithPPSVS
|
||||
delta: timedelta
|
||||
|
||||
|
||||
async def get_nearest_historical(
|
||||
session: AsyncSession,
|
||||
unique_identifier: str,
|
||||
target_time: datetime,
|
||||
) -> HistoricalSnapshot | None:
|
||||
before = await session.scalar(
|
||||
select(TETRIOHistoricalData)
|
||||
.where(
|
||||
TETRIOHistoricalData.user_unique_identifier == unique_identifier,
|
||||
TETRIOHistoricalData.api_type == 'league',
|
||||
TETRIOHistoricalData.update_time <= target_time,
|
||||
)
|
||||
.order_by(TETRIOHistoricalData.update_time.desc())
|
||||
.limit(1)
|
||||
)
|
||||
after = await session.scalar(
|
||||
select(TETRIOHistoricalData)
|
||||
.where(
|
||||
TETRIOHistoricalData.user_unique_identifier == unique_identifier,
|
||||
TETRIOHistoricalData.api_type == 'league',
|
||||
TETRIOHistoricalData.update_time >= target_time,
|
||||
)
|
||||
.order_by(TETRIOHistoricalData.update_time.asc())
|
||||
.limit(1)
|
||||
)
|
||||
candidates = [i for i in (before, after) if i is not None]
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
delta_seconds, selected = min(
|
||||
(
|
||||
abs((target_time - i.update_time.astimezone(UTC)).total_seconds()),
|
||||
i,
|
||||
)
|
||||
for i in candidates
|
||||
)
|
||||
delta = timedelta(seconds=delta_seconds)
|
||||
|
||||
if not isinstance(selected.data, LeagueSuccessModel) or not isinstance(
|
||||
selected.data.data, RatedData | NeverRatedData
|
||||
):
|
||||
return None
|
||||
|
||||
data = selected.data.data
|
||||
return HistoricalSnapshot(get_metrics(pps=data.pps, apm=data.apm, vs=data.vs), delta)
|
||||
|
||||
|
||||
async def _get_boundary_league_historical(
|
||||
session: AsyncSession,
|
||||
uid_id: int,
|
||||
target_time: datetime,
|
||||
*,
|
||||
time_direction: Literal['before', 'after'],
|
||||
) -> tuple[TETRIOLeagueUserMap, datetime] | None:
|
||||
boundary_time = await session.scalar(
|
||||
select((func.max if time_direction == 'before' else func.min)(TETRIOLeagueHistorical.update_time))
|
||||
.select_from(TETRIOLeagueUserMap)
|
||||
.join(TETRIOLeagueHistorical, TETRIOLeagueUserMap.hist_id == TETRIOLeagueHistorical.id)
|
||||
.where(
|
||||
TETRIOLeagueUserMap.uid_id == uid_id,
|
||||
TETRIOLeagueHistorical.update_time <= target_time
|
||||
if time_direction == 'before'
|
||||
else TETRIOLeagueHistorical.update_time >= target_time,
|
||||
)
|
||||
)
|
||||
if boundary_time is None:
|
||||
return None
|
||||
|
||||
return (
|
||||
(
|
||||
await session.execute(
|
||||
select(TETRIOLeagueUserMap, TETRIOLeagueHistorical.update_time)
|
||||
.join(TETRIOLeagueHistorical, TETRIOLeagueUserMap.hist_id == TETRIOLeagueHistorical.id)
|
||||
.where(
|
||||
TETRIOLeagueUserMap.uid_id == uid_id,
|
||||
TETRIOLeagueHistorical.update_time == boundary_time,
|
||||
)
|
||||
.order_by(TETRIOLeagueHistorical.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
)
|
||||
.tuples()
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
async def get_nearest_league_historical(
|
||||
session: AsyncSession,
|
||||
unique_identifier: str,
|
||||
target_time: datetime,
|
||||
) -> HistoricalSnapshot | None:
|
||||
uid_id = await session.scalar(
|
||||
select(TETRIOUserUniqueIdentifier.id).where(
|
||||
TETRIOUserUniqueIdentifier.user_unique_identifier == unique_identifier
|
||||
)
|
||||
)
|
||||
if uid_id is None:
|
||||
return None
|
||||
|
||||
before = await _get_boundary_league_historical(
|
||||
session,
|
||||
uid_id,
|
||||
target_time,
|
||||
time_direction='before',
|
||||
)
|
||||
after = await _get_boundary_league_historical(
|
||||
session,
|
||||
uid_id,
|
||||
target_time,
|
||||
time_direction='after',
|
||||
)
|
||||
|
||||
candidates = [i for i in (before, after) if i is not None]
|
||||
if not candidates:
|
||||
return None
|
||||
delta_seconds, selected = min(
|
||||
(
|
||||
abs((target_time - i[1].astimezone(UTC)).total_seconds()),
|
||||
i[0],
|
||||
)
|
||||
for i in candidates
|
||||
)
|
||||
delta = timedelta(seconds=delta_seconds)
|
||||
|
||||
historical = await session.get(TETRIOLeagueHistorical, selected.hist_id)
|
||||
if historical is None or not isinstance(
|
||||
(entry := find_entry(historical.data.data.entries, selected.entry_index, unique_identifier)), Entry
|
||||
):
|
||||
return None
|
||||
return HistoricalSnapshot(get_metrics(pps=entry.league.pps, apm=entry.league.apm, vs=entry.league.vs), delta)
|
||||
|
||||
|
||||
def find_entry(
|
||||
entries: list[Entry | InvalidEntry],
|
||||
entry_index: int,
|
||||
unique_identifier: str | None = None,
|
||||
) -> Entry | InvalidEntry | None:
|
||||
if 0 <= entry_index < len(entries):
|
||||
entry = entries[entry_index]
|
||||
if unique_identifier is None or entry.id == unique_identifier:
|
||||
return entry
|
||||
if unique_identifier is None:
|
||||
return None
|
||||
for entry in entries:
|
||||
if entry.id == unique_identifier:
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
async def get_trends(player: Player, compare_delta: timedelta) -> Trends:
|
||||
league = await player.league
|
||||
if not isinstance(league.data, RatedData | NeverRatedData):
|
||||
return Trends()
|
||||
user = await player.user
|
||||
|
||||
async with get_session() as session:
|
||||
target_time = (league.cache.cached_at - compare_delta).astimezone(UTC)
|
||||
historical, league_historical = await gather(
|
||||
get_nearest_historical(
|
||||
session,
|
||||
user.unique_identifier,
|
||||
target_time,
|
||||
),
|
||||
get_nearest_league_historical(
|
||||
session,
|
||||
user.unique_identifier,
|
||||
target_time,
|
||||
),
|
||||
)
|
||||
selected = min((historical, league_historical), key=lambda x: x.delta if x is not None else timedelta.max)
|
||||
if selected is None:
|
||||
return Trends()
|
||||
metrics = get_metrics(pps=league.data.pps, apm=league.data.apm, vs=league.data.vs)
|
||||
return Trends(
|
||||
pps=Trending.compare(selected.metrics.pps, metrics.pps),
|
||||
apm=Trending.compare(selected.metrics.apm, metrics.apm),
|
||||
adpm=Trending.compare(selected.metrics.adpm, metrics.adpm),
|
||||
)
|
||||
|
||||
|
||||
async def make_query_image_v1(player: Player, compare_delta: timedelta) -> bytes:
|
||||
(
|
||||
(user, user_info, league, sprint, blitz, leagueflow),
|
||||
(avatar_revision,),
|
||||
) = await gather(
|
||||
gather(player.user, player.get_info(), player.league, player.sprint, player.blitz, player.get_leagueflow()),
|
||||
gather(player.avatar_revision),
|
||||
)
|
||||
league_data = get_league_data(league, RatedData)
|
||||
histories = flow_to_history(leagueflow, handle_history_data)
|
||||
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
|
||||
else:
|
||||
sprint_value = 'N/A'
|
||||
blitz_value = f'{blitz.data.record.results.stats.score:,}' if blitz.data.record is not None else 'N/A'
|
||||
dsps: float
|
||||
dspp: float
|
||||
# make mypy happy
|
||||
return await render_image(
|
||||
Info(
|
||||
user=User(
|
||||
avatar=str(
|
||||
URL(f'http://{get_self_netloc()}/host/resource/tetrio/avatars/{user.ID}')
|
||||
% {'revision': avatar_revision}
|
||||
)
|
||||
if 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(),
|
||||
bio=user_info.data.bio,
|
||||
),
|
||||
multiplayer=Multiplayer(
|
||||
glicko=f'{round(league_data.glicko, 2):,}',
|
||||
rd=round(league_data.rd, 2),
|
||||
rank=league_data.rank,
|
||||
tr=f'{round(league_data.tr, 2):,}',
|
||||
global_rank=league_data.standing,
|
||||
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=(trends := (await get_trends(player, compare_delta))).pps,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
apm_trending=trends.apm,
|
||||
adpm=metrics.adpm,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
adpm_trending=trends.adpm,
|
||||
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),
|
||||
),
|
||||
singleplayer=Singleplayer(
|
||||
sprint=sprint_value,
|
||||
blitz=blitz_value,
|
||||
),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
205
nonebot_plugin_tetris_stats/games/tetrio/query/v2.py
Normal file
205
nonebot_plugin_tetris_stats/games/tetrio/query/v2.py
Normal file
@@ -0,0 +1,205 @@
|
||||
from asyncio import gather
|
||||
from datetime import datetime, timedelta
|
||||
from hashlib import md5
|
||||
|
||||
from yarl import URL
|
||||
|
||||
from ....utils.exception import FallbackError
|
||||
from ....utils.host import get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render_image
|
||||
from ....utils.render.schemas.base import Avatar
|
||||
from ....utils.render.schemas.v2.tetrio.user.info import (
|
||||
Achievement,
|
||||
Badge,
|
||||
Best,
|
||||
Blitz,
|
||||
Info,
|
||||
Sprint,
|
||||
Statistic,
|
||||
TetraLeague,
|
||||
TetraLeagueStatistic,
|
||||
User,
|
||||
Week,
|
||||
Zen,
|
||||
Zenith,
|
||||
)
|
||||
from ..api import Player
|
||||
from ..api.schemas.summaries.league import InvalidData, NeverPlayedData, NeverRatedData
|
||||
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, 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(),
|
||||
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()
|
||||
sprint_value = f'{duration:.3f}s' if duration < 60 else f'{duration // 60:.0f}m {duration % 60:.3f}s' # noqa: PLR2004
|
||||
else:
|
||||
sprint_value = 'N/A'
|
||||
|
||||
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'
|
||||
elif game_time // 60 > 0:
|
||||
play_time = f'{game_time // 60:.0f}m {game_time % 60:.0f}s'
|
||||
else:
|
||||
play_time = f'{game_time:.0f}s'
|
||||
else:
|
||||
play_time = game_time
|
||||
try:
|
||||
history = flow_to_history(leagueflow, lambda x: x[-100:])
|
||||
except FallbackError:
|
||||
history = None
|
||||
netloc = get_self_netloc()
|
||||
return await render_image(
|
||||
Info(
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
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}
|
||||
)
|
||||
if avatar_revision is not None and avatar_revision != 0
|
||||
else Avatar(
|
||||
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,
|
||||
description=i.label,
|
||||
group=i.group,
|
||||
receive_at=i.ts if isinstance(i.ts, datetime) else None,
|
||||
)
|
||||
for i in user_info.data.badges
|
||||
],
|
||||
xp=user_info.data.xp,
|
||||
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,
|
||||
),
|
||||
tetra_league=TetraLeague(
|
||||
rank=league.data.rank,
|
||||
highest_rank='z' if isinstance(league.data, NeverRatedData) else league.data.bestrank,
|
||||
tr=round(league.data.tr, 2),
|
||||
glicko=round(league.data.glicko, 2),
|
||||
rd=round(league.data.rd, 2),
|
||||
global_rank=league.data.standing,
|
||||
country_rank=league.data.standing_local,
|
||||
pps=(metrics := get_metrics(pps=league.data.pps, apm=league.data.apm, vs=league.data.vs)).pps,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
statistic=TetraLeagueStatistic(total=league.data.gamesplayed, wins=league.data.gameswon),
|
||||
decaying=league.data.decaying,
|
||||
history=history,
|
||||
)
|
||||
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),
|
||||
),
|
||||
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
|
||||
else None,
|
||||
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(),
|
||||
),
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable, Sequence
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from math import floor
|
||||
from statistics import mean
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, TypeVar
|
||||
from uuid import uuid4
|
||||
|
||||
from nonebot import get_driver
|
||||
@@ -12,8 +12,8 @@ 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.limit import limit
|
||||
from ....utils.retry import retry
|
||||
from .. import alc
|
||||
from .. import command as base_command
|
||||
@@ -22,11 +22,17 @@ from ..api.schemas.base import P
|
||||
from ..api.schemas.leaderboards import Parameter
|
||||
from ..api.schemas.leaderboards.by import Entry
|
||||
from ..constant import RANK_PERCENTILE
|
||||
from ..models import TETRIOLeagueHistorical, TETRIOLeagueStats, TETRIOLeagueStatsField
|
||||
from ..models import (
|
||||
TETRIOLeagueHistorical,
|
||||
TETRIOLeagueStats,
|
||||
TETRIOLeagueStatsField,
|
||||
TETRIOLeagueUserMap,
|
||||
TETRIOUserUniqueIdentifier,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..api.schemas.leaderboards.by import BySuccessModel
|
||||
from ..api.typing import Rank
|
||||
from ..api.typedefs import Rank
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
@@ -81,22 +87,28 @@ def find_special_player(
|
||||
return sort(users, field)
|
||||
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
|
||||
def _chunked(values: list[T], size: int) -> Iterator[list[T]]:
|
||||
for i in range(0, len(values), size):
|
||||
yield values[i : i + size]
|
||||
|
||||
|
||||
@scheduler.scheduled_job('cron', hour='0,6,12,18', minute=0)
|
||||
async def get_tetra_league_data() -> None:
|
||||
x_session_id = uuid4()
|
||||
limit_by = retry(max_attempts=10, exception_type=RequestError)(limit(timedelta(seconds=1))(by))
|
||||
retry_by = retry(max_attempts=10, exception_type=RequestError)(by)
|
||||
prisecter = P(pri=9007199254740991, sec=9007199254740991, ter=9007199254740991) # * from ch.tetr.io
|
||||
results: list[BySuccessModel] = []
|
||||
while True:
|
||||
model = await limit_by('league', Parameter(after=prisecter.to_prisecter(), limit=100), x_session_id)
|
||||
model = await retry_by('league', Parameter(after=prisecter.to_prisecter(), limit=100), x_session_id)
|
||||
prisecter = model.data.entries[-1].p
|
||||
results.append(model)
|
||||
if len(model.data.entries) < 100: # 分页值 # noqa: PLR2004
|
||||
break
|
||||
|
||||
players: list[Entry] = []
|
||||
for result in results:
|
||||
players.extend(result.data.entries)
|
||||
players = [i for result in results 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)
|
||||
@@ -132,22 +144,53 @@ async def get_tetra_league_data() -> None:
|
||||
]
|
||||
stats.raw = historicals
|
||||
stats.fields = fields
|
||||
player_ids = {i.id for result in results for i in result.data.entries}
|
||||
async with get_session() as session:
|
||||
session.add(stats)
|
||||
existing_ids: list[TETRIOUserUniqueIdentifier] = []
|
||||
for chunk in _chunked(list(player_ids), 500):
|
||||
existing_ids.extend(
|
||||
(
|
||||
await session.scalars(
|
||||
select(TETRIOUserUniqueIdentifier).filter(
|
||||
TETRIOUserUniqueIdentifier.user_unique_identifier.in_(chunk)
|
||||
)
|
||||
)
|
||||
).all()
|
||||
)
|
||||
new_ids = [
|
||||
TETRIOUserUniqueIdentifier(user_unique_identifier=i)
|
||||
for i in player_ids - {i.user_unique_identifier for i in existing_ids}
|
||||
]
|
||||
session.add_all(new_ids)
|
||||
await session.flush()
|
||||
uid_mapping = {i.user_unique_identifier: i.id for i in list(existing_ids) + new_ids}
|
||||
maps: list[TETRIOLeagueUserMap] = []
|
||||
for i in stats.raw:
|
||||
for index, entry in enumerate(i.data.data.entries):
|
||||
maps.append(
|
||||
TETRIOLeagueUserMap(
|
||||
stats_id=stats.id, uid_id=uid_mapping[entry.id], hist_id=i.id, entry_index=index
|
||||
)
|
||||
)
|
||||
session.add_all(maps)
|
||||
maps.clear()
|
||||
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.dev.enabled:
|
||||
|
||||
@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,24 @@ 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 sqlalchemy import func, select
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from sqlalchemy import 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.screenshot import screenshot
|
||||
from ....utils.render import render_image
|
||||
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 .. 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,14 +31,15 @@ command.add(
|
||||
|
||||
|
||||
@alc.assign('TETRIO.rank.all')
|
||||
async def _(event_session: EventSession, template: Template = 'v1'):
|
||||
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,
|
||||
command_type='rank',
|
||||
command_args=['--all'],
|
||||
command_args=['--all'] + ([f'--template {template}'] if template is not None else []),
|
||||
):
|
||||
async with get_session() as session:
|
||||
# 获取最新记录
|
||||
latest_data = (
|
||||
await session.scalars(
|
||||
select(TETRIOLeagueStats)
|
||||
@@ -48,68 +48,109 @@ async def _(event_session: EventSession, template: Template = 'v1'):
|
||||
.options(selectinload(TETRIOLeagueStats.fields))
|
||||
)
|
||||
).one()
|
||||
compare_data = (
|
||||
await session.scalars(
|
||||
|
||||
# 计算目标时间点 (24小时前)
|
||||
target_time = latest_data.update_time - timedelta(hours=24)
|
||||
|
||||
# 查询目标时间点之前的最近记录
|
||||
before = (
|
||||
await session.scalar(
|
||||
select(TETRIOLeagueStats)
|
||||
.order_by(
|
||||
func.abs(
|
||||
func.julianday(TETRIOLeagueStats.update_time)
|
||||
- func.julianday(latest_data.update_time - timedelta(hours=24))
|
||||
)
|
||||
)
|
||||
.where(TETRIOLeagueStats.update_time <= target_time)
|
||||
.order_by(TETRIOLeagueStats.update_time.desc())
|
||||
.limit(1)
|
||||
.options(selectinload(TETRIOLeagueStats.fields))
|
||||
)
|
||||
).one()
|
||||
or latest_data
|
||||
)
|
||||
|
||||
# 查询目标时间点之后的最近记录
|
||||
after = (
|
||||
await session.scalar(
|
||||
select(TETRIOLeagueStats)
|
||||
.where(TETRIOLeagueStats.update_time >= target_time) # 使用 >= 避免间隙
|
||||
.order_by(TETRIOLeagueStats.update_time.asc())
|
||||
.limit(1)
|
||||
.options(selectinload(TETRIOLeagueStats.fields))
|
||||
)
|
||||
or latest_data
|
||||
)
|
||||
|
||||
# 确定最接近的记录
|
||||
compare_data = (
|
||||
before
|
||||
if abs((target_time - before.update_time).total_seconds())
|
||||
< abs((target_time - after.update_time).total_seconds())
|
||||
else after
|
||||
)
|
||||
|
||||
match template:
|
||||
case 'v1':
|
||||
case 'v1' | None:
|
||||
await UniMessage.image(raw=await make_image_v1(latest_data, compare_data)).finish()
|
||||
case 'v2':
|
||||
await UniMessage.image(raw=await make_image_v2(latest_data, compare_data)).finish()
|
||||
|
||||
|
||||
_RANK_ORDER_INDEX = {
|
||||
v: i
|
||||
for i, v in enumerate(
|
||||
('x+', 'x', 'u', 'ss', 's+', 's', 's-', 'a+', 'a', 'a-', 'b+', 'b', 'b-', 'c+', 'c', 'c-', 'd+', 'd', 'z')
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _rank_sort_key(rank: str) -> int:
|
||||
try:
|
||||
return _RANK_ORDER_INDEX[rank]
|
||||
except KeyError as e:
|
||||
msg = f'未知段位: {rank!r}'
|
||||
raise ValueError(msg) from e
|
||||
|
||||
|
||||
async def make_image_v1(latest_data: TETRIOLeagueStats, compare_data: TETRIOLeagueStats) -> bytes:
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/tetrio/rank',
|
||||
DataV1(
|
||||
items={
|
||||
i[0].rank: ItemDataV1(
|
||||
trending=round(i[0].tr_line - i[1].tr_line, 2),
|
||||
require_tr=round(i[0].tr_line, 2),
|
||||
players=i[0].player_count,
|
||||
)
|
||||
for i in zip(latest_data.fields, compare_data.fields, strict=True)
|
||||
},
|
||||
updated_at=latest_data.update_time,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
return await render_image(
|
||||
DataV1(
|
||||
items={
|
||||
i[0].rank: ItemDataV1(
|
||||
trending=round(i[0].tr_line - i[1].tr_line, 2),
|
||||
require_tr=round(i[0].tr_line, 2),
|
||||
players=i[0].player_count,
|
||||
)
|
||||
for i in zip(
|
||||
sorted(latest_data.fields, key=lambda x: _rank_sort_key(x.rank)),
|
||||
sorted(compare_data.fields, key=lambda x: _rank_sort_key(x.rank)),
|
||||
strict=True,
|
||||
)
|
||||
},
|
||||
updated_at=latest_data.update_time,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def make_image_v2(latest_data: TETRIOLeagueStats, compare_data: TETRIOLeagueStats) -> bytes:
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v2/tetrio/rank',
|
||||
DataV2(
|
||||
items={
|
||||
i[0].rank: ItemDataV2(
|
||||
require_tr=round(i[0].tr_line, 2),
|
||||
trending=round(i[0].tr_line - i[1].tr_line, 2),
|
||||
average_data=AverageDataV2(
|
||||
pps=(metrics := get_metrics(pps=i[0].avg_pps, apm=i[0].avg_apm, vs=i[0].avg_vs)).pps,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
),
|
||||
players=i[0].player_count,
|
||||
)
|
||||
for i in zip(latest_data.fields, compare_data.fields, strict=True)
|
||||
},
|
||||
updated_at=latest_data.update_time,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
return await render_image(
|
||||
DataV2(
|
||||
items={
|
||||
i[0].rank: ItemDataV2(
|
||||
require_tr=round(i[0].tr_line, 2),
|
||||
trending=round(i[0].tr_line - i[1].tr_line, 2),
|
||||
average_data=AverageDataV2(
|
||||
pps=(metrics := get_metrics(pps=i[0].avg_pps, apm=i[0].avg_apm, vs=i[0].avg_vs)).pps,
|
||||
apm=metrics.apm,
|
||||
apl=metrics.apl,
|
||||
vs=metrics.vs,
|
||||
adpl=metrics.adpl,
|
||||
),
|
||||
players=i[0].player_count,
|
||||
)
|
||||
for i in zip(
|
||||
sorted(latest_data.fields, key=lambda x: _rank_sort_key(x.rank)),
|
||||
sorted(compare_data.fields, key=lambda x: _rank_sort_key(x.rank)),
|
||||
strict=True,
|
||||
)
|
||||
},
|
||||
updated_at=latest_data.update_time,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -5,19 +5,18 @@ 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 sqlalchemy import func, select
|
||||
from nonebot_plugin_uninfo import Uninfo
|
||||
from nonebot_plugin_uninfo.orm import get_session_persist_id
|
||||
from sqlalchemy import 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.screenshot import screenshot
|
||||
from ....utils.render import render_image
|
||||
from ....utils.render.schemas.v2.tetrio.rank.detail import Data, SpecialData
|
||||
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 +29,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,
|
||||
@@ -38,6 +37,7 @@ async def _(rank: ValidRank, event_session: EventSession):
|
||||
command_args=[f'--detail {rank}'],
|
||||
):
|
||||
async with get_session() as session:
|
||||
# 获取最新记录
|
||||
latest_data = (
|
||||
await session.scalars(
|
||||
select(TETRIOLeagueStats)
|
||||
@@ -46,19 +46,41 @@ async def _(rank: ValidRank, event_session: EventSession):
|
||||
.options(selectinload(TETRIOLeagueStats.fields))
|
||||
)
|
||||
).one()
|
||||
compare_data = (
|
||||
await session.scalars(
|
||||
|
||||
# 计算目标时间点 (24小时前)
|
||||
target_time = latest_data.update_time - timedelta(hours=24)
|
||||
|
||||
# 查询目标时间点之前的最近记录
|
||||
before = (
|
||||
await session.scalar(
|
||||
select(TETRIOLeagueStats)
|
||||
.order_by(
|
||||
func.abs(
|
||||
func.julianday(TETRIOLeagueStats.update_time)
|
||||
- func.julianday(latest_data.update_time - timedelta(hours=24))
|
||||
)
|
||||
)
|
||||
.where(TETRIOLeagueStats.update_time <= target_time)
|
||||
.order_by(TETRIOLeagueStats.update_time.desc())
|
||||
.limit(1)
|
||||
.options(selectinload(TETRIOLeagueStats.fields))
|
||||
)
|
||||
).one()
|
||||
or latest_data # 回退到最新记录
|
||||
)
|
||||
|
||||
# 查询目标时间点之后的最近记录
|
||||
after = (
|
||||
await session.scalar(
|
||||
select(TETRIOLeagueStats)
|
||||
.where(TETRIOLeagueStats.update_time >= target_time)
|
||||
.order_by(TETRIOLeagueStats.update_time.asc())
|
||||
.limit(1)
|
||||
.options(selectinload(TETRIOLeagueStats.fields))
|
||||
)
|
||||
or latest_data # 回退到最新记录
|
||||
)
|
||||
|
||||
# 确定最接近的记录
|
||||
compare_data = (
|
||||
before
|
||||
if abs((target_time - before.update_time).total_seconds())
|
||||
< abs((target_time - after.update_time).total_seconds())
|
||||
else after
|
||||
)
|
||||
await UniMessage.image(
|
||||
raw=await make_image(
|
||||
rank,
|
||||
@@ -90,39 +112,36 @@ async def make_image(rank: ValidRank, latest: TETRIOLeagueStats, compare: TETRIO
|
||||
max_vs = get_metrics(
|
||||
pps=latest_data.high_vs.league.pps, apm=latest_data.high_vs.league.apm, vs=latest_data.high_vs.league.vs
|
||||
)
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v2/tetrio/rank/detail',
|
||||
Data(
|
||||
name=latest_data.rank,
|
||||
trending=round(latest_data.tr_line - compare_data.tr_line, 2),
|
||||
require_tr=round(latest_data.tr_line, 2),
|
||||
players=latest_data.player_count,
|
||||
minimum_data=SpecialData(
|
||||
apm=low_apm.apm,
|
||||
pps=low_pps.pps,
|
||||
lpm=low_pps.lpm,
|
||||
vs=low_vs.vs,
|
||||
adpm=low_vs.adpm,
|
||||
apm_holder=latest_data.low_apm.username.upper(),
|
||||
pps_holder=latest_data.low_pps.username.upper(),
|
||||
vs_holder=latest_data.low_vs.username.upper(),
|
||||
),
|
||||
average_data=SpecialData(
|
||||
apm=avg.apm, pps=avg.pps, lpm=avg.lpm, vs=avg.vs, adpm=avg.adpm, apl=avg.apl, adpl=avg.adpl
|
||||
),
|
||||
maximum_data=SpecialData(
|
||||
apm=max_apm.apm,
|
||||
pps=max_pps.pps,
|
||||
lpm=max_pps.lpm,
|
||||
vs=max_vs.vs,
|
||||
adpm=max_vs.adpm,
|
||||
apm_holder=latest_data.high_apm.username.upper(),
|
||||
pps_holder=latest_data.high_pps.username.upper(),
|
||||
vs_holder=latest_data.high_vs.username.upper(),
|
||||
),
|
||||
updated_at=latest.update_time.replace(tzinfo=UTC).astimezone(ZoneInfo('Asia/Shanghai')),
|
||||
return await render_image(
|
||||
Data(
|
||||
name=latest_data.rank,
|
||||
trending=round(latest_data.tr_line - compare_data.tr_line, 2),
|
||||
require_tr=round(latest_data.tr_line, 2),
|
||||
players=latest_data.player_count,
|
||||
minimum_data=SpecialData(
|
||||
apm=low_apm.apm,
|
||||
pps=low_pps.pps,
|
||||
lpm=low_pps.lpm,
|
||||
vs=low_vs.vs,
|
||||
adpm=low_vs.adpm,
|
||||
apm_holder=latest_data.low_apm.username.upper(),
|
||||
pps_holder=latest_data.low_pps.username.upper(),
|
||||
vs_holder=latest_data.low_vs.username.upper(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
average_data=SpecialData(
|
||||
apm=avg.apm, pps=avg.pps, lpm=avg.lpm, vs=avg.vs, adpm=avg.adpm, apl=avg.apl, adpl=avg.adpl
|
||||
),
|
||||
maximum_data=SpecialData(
|
||||
apm=max_apm.apm,
|
||||
pps=max_pps.pps,
|
||||
lpm=max_pps.lpm,
|
||||
vs=max_vs.vs,
|
||||
adpm=max_vs.adpm,
|
||||
apm_holder=latest_data.high_apm.username.upper(),
|
||||
pps_holder=latest_data.high_pps.username.upper(),
|
||||
vs_holder=latest_data.high_vs.username.upper(),
|
||||
),
|
||||
updated_at=latest.update_time.replace(tzinfo=UTC).astimezone(ZoneInfo('Asia/Shanghai')),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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,22 +7,22 @@ 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
|
||||
|
||||
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.host import get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render import render_image
|
||||
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.screenshot import screenshot
|
||||
from ....utils.typing import Me
|
||||
from ...constant import CANT_VERIFY_MESSAGE
|
||||
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.typedefs import Me
|
||||
from .. import alc
|
||||
from ..api.player import Player
|
||||
from ..constant import GAME_TYPE
|
||||
@@ -42,7 +42,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,19 +54,20 @@ 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,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = UniMessage(CANT_VERIFY_MESSAGE)
|
||||
await matcher.finish(Lang.bind.not_found())
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
await (message + UniMessage.image(raw=await make_blitz_image(player))).finish()
|
||||
await (
|
||||
UniMessage.i18n(Lang.interaction.warning.unverified) + UniMessage.image(raw=await make_blitz_image(player))
|
||||
).finish()
|
||||
|
||||
|
||||
@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,
|
||||
@@ -79,72 +80,69 @@ async def _(account: Player, event_session: EventSession):
|
||||
async def make_blitz_image(player: Player) -> bytes:
|
||||
user, blitz = await gather(player.user, player.blitz)
|
||||
if blitz.data.record is None:
|
||||
msg = f'未找到用户 {user.name.upper()} 的 Blitz 记录'
|
||||
msg = Lang.record.not_found(username=user.name.upper(), mode=Lang.record.blitz())
|
||||
raise RecordNotFoundError(msg)
|
||||
stats = blitz.data.record.results.stats
|
||||
clears = stats.clears
|
||||
duration = timedelta(milliseconds=stats.finaltime).total_seconds()
|
||||
metrics = get_metrics(pps=stats.piecesplaced / duration)
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
page=await render(
|
||||
'v2/tetrio/record/blitz',
|
||||
Record(
|
||||
type='best',
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
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
|
||||
),
|
||||
return await render_image(
|
||||
Record(
|
||||
type='best',
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
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
|
||||
),
|
||||
replay_id=blitz.data.record.replayid,
|
||||
rank=blitz.data.rank,
|
||||
personal_rank=1,
|
||||
statistic=Statistic(
|
||||
keys=stats.inputs,
|
||||
kpp=round(stats.inputs / stats.piecesplaced, 2),
|
||||
kps=round(stats.inputs / duration, 2),
|
||||
max=Max(
|
||||
combo=max((0, stats.topcombo - 1)),
|
||||
btb=max((0, stats.topbtb - 1)),
|
||||
),
|
||||
pieces=stats.piecesplaced,
|
||||
pps=metrics.pps,
|
||||
lines=stats.lines,
|
||||
lpm=metrics.lpm,
|
||||
holds=stats.holds,
|
||||
score=stats.score,
|
||||
spp=round(stats.score / stats.piecesplaced, 2),
|
||||
single=clears.singles,
|
||||
double=clears.doubles,
|
||||
triple=clears.triples,
|
||||
quad=clears.quads,
|
||||
tspins=Tspins(
|
||||
total=clears.realtspins,
|
||||
single=clears.tspinsingles,
|
||||
double=clears.tspindoubles,
|
||||
triple=clears.tspintriples,
|
||||
mini=Mini(
|
||||
total=clears.minitspins,
|
||||
single=clears.minitspinsingles,
|
||||
double=clears.minitspindoubles,
|
||||
),
|
||||
),
|
||||
all_clear=clears.allclear,
|
||||
finesse=Finesse(
|
||||
faults=stats.finesse.faults,
|
||||
accuracy=round(stats.finesse.perfectpieces / stats.piecesplaced * 100, 2),
|
||||
),
|
||||
level=stats.level,
|
||||
),
|
||||
play_at=blitz.data.record.ts,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{netloc}/host/{page_hash}.html')
|
||||
replay_id=blitz.data.record.replayid,
|
||||
rank=blitz.data.rank,
|
||||
personal_rank=1,
|
||||
statistic=Statistic(
|
||||
keys=stats.inputs,
|
||||
kpp=round(stats.inputs / stats.piecesplaced, 2),
|
||||
kps=round(stats.inputs / duration, 2),
|
||||
max=Max(
|
||||
combo=max((0, stats.topcombo - 1)),
|
||||
btb=max((0, stats.topbtb - 1)),
|
||||
),
|
||||
pieces=stats.piecesplaced,
|
||||
pps=metrics.pps,
|
||||
lines=stats.lines,
|
||||
lpm=metrics.lpm,
|
||||
holds=stats.holds,
|
||||
score=stats.score,
|
||||
spp=round(stats.score / stats.piecesplaced, 2),
|
||||
single=clears.singles,
|
||||
double=clears.doubles,
|
||||
triple=clears.triples,
|
||||
quad=clears.quads,
|
||||
tspins=Tspins(
|
||||
total=clears.realtspins,
|
||||
single=clears.tspinsingles,
|
||||
double=clears.tspindoubles,
|
||||
triple=clears.tspintriples,
|
||||
mini=Mini(
|
||||
total=clears.minitspins,
|
||||
single=clears.minitspinsingles,
|
||||
double=clears.minitspindoubles,
|
||||
),
|
||||
),
|
||||
all_clear=clears.allclear,
|
||||
finesse=Finesse(
|
||||
faults=stats.finesse.faults,
|
||||
accuracy=round(stats.finesse.perfectpieces / stats.piecesplaced * 100, 2),
|
||||
),
|
||||
level=stats.level,
|
||||
),
|
||||
play_at=blitz.data.record.ts,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -7,22 +7,22 @@ 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
|
||||
|
||||
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.host import get_self_netloc
|
||||
from ....utils.lang import get_lang
|
||||
from ....utils.metrics import get_metrics
|
||||
from ....utils.render import render
|
||||
from ....utils.render import render_image
|
||||
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.screenshot import screenshot
|
||||
from ....utils.typing import Me
|
||||
from ...constant import CANT_VERIFY_MESSAGE
|
||||
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.typedefs import Me
|
||||
from .. import alc
|
||||
from ..api.player import Player
|
||||
from ..constant import GAME_TYPE
|
||||
@@ -42,7 +42,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,19 +54,20 @@ 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,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
message = UniMessage(CANT_VERIFY_MESSAGE)
|
||||
await matcher.finish(Lang.bind.not_found())
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
await (message + UniMessage.image(raw=await make_sprint_image(player))).finish()
|
||||
await (
|
||||
UniMessage.i18n(Lang.interaction.warning.unverified) + UniMessage.image(raw=await make_sprint_image(player))
|
||||
).finish()
|
||||
|
||||
|
||||
@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,
|
||||
@@ -79,7 +80,7 @@ async def _(account: Player, event_session: EventSession):
|
||||
async def make_sprint_image(player: Player) -> bytes:
|
||||
user, sprint = await gather(player.user, player.sprint)
|
||||
if sprint.data.record is None:
|
||||
msg = f'未找到用户 {user.name.upper()} 的 40L 记录'
|
||||
msg = Lang.record.not_found(username=user.name.upper(), mode=Lang.record.sprint())
|
||||
raise RecordNotFoundError(msg)
|
||||
stats = sprint.data.record.results.stats
|
||||
clears = stats.clears
|
||||
@@ -87,64 +88,61 @@ async def make_sprint_image(player: Player) -> bytes:
|
||||
sprint_value = f'{duration:.3f}s' if duration < 60 else f'{duration // 60:.0f}m {duration % 60:.3f}s' # noqa: PLR2004
|
||||
metrics = get_metrics(pps=stats.piecesplaced / duration)
|
||||
netloc = get_self_netloc()
|
||||
async with HostPage(
|
||||
page=await render(
|
||||
'v2/tetrio/record/40l',
|
||||
Record(
|
||||
type='best',
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
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
|
||||
),
|
||||
return await render_image(
|
||||
Record(
|
||||
type='best',
|
||||
user=User(
|
||||
id=user.ID,
|
||||
name=user.name.upper(),
|
||||
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
|
||||
),
|
||||
time=sprint_value,
|
||||
replay_id=sprint.data.record.replayid,
|
||||
rank=sprint.data.rank,
|
||||
personal_rank=1,
|
||||
statistic=Statistic(
|
||||
keys=stats.inputs,
|
||||
kpp=round(stats.inputs / stats.piecesplaced, 2),
|
||||
kps=round(stats.inputs / duration, 2),
|
||||
max=Max(
|
||||
combo=max((0, stats.topcombo - 1)),
|
||||
btb=max((0, stats.topbtb - 1)),
|
||||
),
|
||||
pieces=stats.piecesplaced,
|
||||
pps=metrics.pps,
|
||||
lines=stats.lines,
|
||||
lpm=metrics.lpm,
|
||||
holds=stats.holds,
|
||||
score=stats.score,
|
||||
single=clears.singles,
|
||||
double=clears.doubles,
|
||||
triple=clears.triples,
|
||||
quad=clears.quads,
|
||||
tspins=Tspins(
|
||||
total=clears.realtspins,
|
||||
single=clears.tspinsingles,
|
||||
double=clears.tspindoubles,
|
||||
triple=clears.tspintriples,
|
||||
mini=Mini(
|
||||
total=clears.minitspins,
|
||||
single=clears.minitspinsingles,
|
||||
double=clears.minitspindoubles,
|
||||
),
|
||||
),
|
||||
all_clear=clears.allclear,
|
||||
finesse=Finesse(
|
||||
faults=stats.finesse.faults,
|
||||
accuracy=round(stats.finesse.perfectpieces / stats.piecesplaced * 100, 2),
|
||||
),
|
||||
),
|
||||
play_at=sprint.data.record.ts,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{netloc}/host/{page_hash}.html')
|
||||
time=sprint_value,
|
||||
replay_id=sprint.data.record.replayid,
|
||||
rank=sprint.data.rank,
|
||||
personal_rank=1,
|
||||
statistic=Statistic(
|
||||
keys=stats.inputs,
|
||||
kpp=round(stats.inputs / stats.piecesplaced, 2),
|
||||
kps=round(stats.inputs / duration, 2),
|
||||
max=Max(
|
||||
combo=max((0, stats.topcombo - 1)),
|
||||
btb=max((0, stats.topbtb - 1)),
|
||||
),
|
||||
pieces=stats.piecesplaced,
|
||||
pps=metrics.pps,
|
||||
lines=stats.lines,
|
||||
lpm=metrics.lpm,
|
||||
holds=stats.holds,
|
||||
score=stats.score,
|
||||
single=clears.singles,
|
||||
double=clears.doubles,
|
||||
triple=clears.triples,
|
||||
quad=clears.quads,
|
||||
tspins=Tspins(
|
||||
total=clears.realtspins,
|
||||
single=clears.tspinsingles,
|
||||
double=clears.tspindoubles,
|
||||
triple=clears.tspintriples,
|
||||
mini=Mini(
|
||||
total=clears.minitspins,
|
||||
single=clears.minitspinsingles,
|
||||
double=clears.minitspindoubles,
|
||||
),
|
||||
),
|
||||
all_clear=clears.allclear,
|
||||
finesse=Finesse(
|
||||
faults=stats.finesse.faults,
|
||||
accuracy=round(stats.finesse.perfectpieces / stats.piecesplaced * 100, 2),
|
||||
),
|
||||
),
|
||||
play_at=sprint.data.record.ts,
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
85
nonebot_plugin_tetris_stats/games/tetrio/unbind.py
Normal file
85
nonebot_plugin_tetris_stats/games/tetrio/unbind.py
Normal file
@@ -0,0 +1,85 @@
|
||||
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 ...i18n import Lang
|
||||
from ...utils.host import get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.base import Avatar, People
|
||||
from ...utils.render.schemas.bind import Bind
|
||||
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(Lang.bind.no_account(game='TETR.IO')).finish()
|
||||
resp = await suggest(Lang.bind.confirm_unbind(), ['是', '否'])
|
||||
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()
|
||||
await UniMessage.image(
|
||||
raw=await render_image(
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
type='unbind',
|
||||
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=Lang.prompt.io_bind(),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
).send()
|
||||
await remove_bind(session=session, user=nb_user, game_platform=GAME_TYPE)
|
||||
111
nonebot_plugin_tetris_stats/games/tetrio/verify.py
Normal file
111
nonebot_plugin_tetris_stats/games/tetrio/verify.py
Normal file
@@ -0,0 +1,111 @@
|
||||
from asyncio import gather
|
||||
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 yarl import URL
|
||||
|
||||
from ...config.config import global_config
|
||||
from ...db import create_or_update_bind, query_bind_info, trigger
|
||||
from ...i18n import Lang
|
||||
from ...utils.host import get_self_netloc
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.base import Avatar, People
|
||||
from ...utils.render.schemas.bind import Bind
|
||||
from . import alc, command
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
|
||||
command.add(Subcommand('verify', help_text='验证 TETR.IO 账号'))
|
||||
|
||||
alc.shortcut(
|
||||
'(?i:io)(?i:验证|verify)',
|
||||
command='tstats TETR.IO verify',
|
||||
humanized='io验证',
|
||||
)
|
||||
|
||||
try:
|
||||
from nonebot.adapters.discord import MessageCreateEvent
|
||||
|
||||
@alc.assign('TETRIO.verify')
|
||||
async def _(_: MessageCreateEvent, 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='verify',
|
||||
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(Lang.bind.no_account(game='TETR.IO')).finish()
|
||||
if bind.verify is True:
|
||||
await UniMessage(Lang.bind.verify_already()).finish()
|
||||
player = Player(user_id=bind.game_account, trust=True)
|
||||
user_info = await player.get_info()
|
||||
verify = (
|
||||
user_info.data.connections.discord is not None
|
||||
and user_info.data.connections.discord.id == event_session.user.id
|
||||
)
|
||||
if verify is False:
|
||||
await UniMessage(Lang.bind.verify_failed(game='TETR.IO')).finish()
|
||||
await create_or_update_bind(
|
||||
session=session,
|
||||
user=nb_user,
|
||||
game_platform=GAME_TYPE,
|
||||
game_account=bind.game_account,
|
||||
verify=verify,
|
||||
)
|
||||
user, avatar_revision = await gather(player.user, player.avatar_revision)
|
||||
await UniMessage.image(
|
||||
raw=await render_image(
|
||||
Bind(
|
||||
platform='TETR.IO',
|
||||
type='success',
|
||||
user=People(
|
||||
avatar=str(
|
||||
URL(f'http://{get_self_netloc()}/host/resource/tetrio/avatars/{user.ID}')
|
||||
% {'revision': avatar_revision}
|
||||
)
|
||||
if 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=Lang.prompt.io_check(),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
).finish()
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
@alc.assign('TETRIO.verify')
|
||||
async def _(event_session: Uninfo):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='verify',
|
||||
command_args=[],
|
||||
):
|
||||
await UniMessage(Lang.bind.only_discord()).finish()
|
||||
@@ -1,8 +1,9 @@
|
||||
from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot_plugin_alconna import Args, At, Subcommand
|
||||
from nonebot_plugin_alconna import Args, At, Option, Subcommand
|
||||
|
||||
from ...utils.duration import parse_duration
|
||||
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 +30,20 @@ command.add(
|
||||
),
|
||||
help_text='绑定 TOP 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'unbind',
|
||||
help_text='解除绑定 TOP 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'config',
|
||||
Option(
|
||||
'--default-compare',
|
||||
Arg('compare', parse_duration, notice='对比时间距离'),
|
||||
alias=['-DC', 'DefaultCompare'],
|
||||
help_text='设置默认对比时间距离',
|
||||
),
|
||||
help_text='TOP 查询个性化配置',
|
||||
),
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
@@ -45,15 +60,39 @@ command.add(
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
Option(
|
||||
'--compare',
|
||||
Arg('compare', parse_duration),
|
||||
alias=['-C'],
|
||||
help_text='指定对比时间距离',
|
||||
),
|
||||
help_text='查询 TOP 游戏信息',
|
||||
),
|
||||
help_text='TOP 游戏相关指令',
|
||||
)
|
||||
)
|
||||
|
||||
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查',
|
||||
)
|
||||
alc.shortcut(
|
||||
'(?i:top)(?i:配置|配|config)',
|
||||
command='tstats TOP config',
|
||||
humanized='top配置',
|
||||
)
|
||||
|
||||
add_block_handlers(alc.assign('TOP.query'))
|
||||
|
||||
from . import bind, query # noqa: E402, F401
|
||||
from . import bind, config, 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,29 +1,27 @@
|
||||
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 ...i18n import Lang
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.render.schemas.bind import Bind
|
||||
from . import alc
|
||||
from .api import Player
|
||||
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,
|
||||
@@ -39,24 +37,32 @@ async def _(
|
||||
game_account=user.unique_identifier,
|
||||
)
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/binding',
|
||||
await UniMessage.image(
|
||||
raw=await render_image(
|
||||
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=Lang.prompt.top_check(),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(
|
||||
raw=await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
).finish()
|
||||
).finish()
|
||||
|
||||
32
nonebot_plugin_tetris_stats/games/top/config.py
Normal file
32
nonebot_plugin_tetris_stats/games/top/config.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import async_scoped_session
|
||||
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
|
||||
|
||||
from ...db import trigger
|
||||
from ...i18n import Lang
|
||||
from . import alc
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TOPUserConfig
|
||||
|
||||
|
||||
@alc.assign('TOP.config')
|
||||
async def _(user: User, session: async_scoped_session, event_session: Uninfo, compare: timedelta):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='config',
|
||||
command_args=[f'--default-compare {compare}'],
|
||||
):
|
||||
config = (await session.scalars(select(TOPUserConfig).where(TOPUserConfig.id == user.id))).one_or_none()
|
||||
if config is None:
|
||||
config = TOPUserConfig(id=user.id, compare_delta=compare)
|
||||
session.add(config)
|
||||
else:
|
||||
config.compare_delta = compare
|
||||
await session.commit()
|
||||
await UniMessage(Lang.bind.config_success()).finish()
|
||||
@@ -1,4 +1,4 @@
|
||||
from re import compile
|
||||
from re import compile # noqa: A004
|
||||
from typing import Literal
|
||||
|
||||
from yarl import URL
|
||||
|
||||
12
nonebot_plugin_tetris_stats/games/top/models.py
Normal file
12
nonebot_plugin_tetris_stats/games/top/models.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from nonebot_plugin_orm import Model
|
||||
from sqlalchemy import Interval
|
||||
from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
|
||||
class TOPUserConfig(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_top_u_cfg'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
compare_delta: Mapped[timedelta | None] = mapped_column(Interval(native=True), nullable=True)
|
||||
@@ -1,63 +1,143 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
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_alconna.uniseg import Image, UniMessage
|
||||
from nonebot_plugin_orm import AsyncSession, get_session
|
||||
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
|
||||
|
||||
from ...db import query_bind_info, trigger
|
||||
from ...db import query_bind_info, resolve_compare_delta, 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 import render_image
|
||||
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.screenshot import screenshot
|
||||
from ...utils.typing import Me
|
||||
from ..constant import CANT_VERIFY_MESSAGE
|
||||
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.typedefs import Me
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .api.models import TOPHistoricalData
|
||||
from .api.schemas.user_profile import Data, UserProfile
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TOPUserConfig
|
||||
|
||||
UTC = timezone.utc
|
||||
|
||||
|
||||
async def get_compare_profile(session: AsyncSession, user_name: str, target_time: datetime) -> UserProfile | None:
|
||||
before = await session.scalar(
|
||||
select(TOPHistoricalData)
|
||||
.where(
|
||||
TOPHistoricalData.user_unique_identifier == user_name,
|
||||
TOPHistoricalData.api_type == 'User Profile',
|
||||
TOPHistoricalData.update_time <= target_time,
|
||||
)
|
||||
.order_by(TOPHistoricalData.update_time.desc())
|
||||
.limit(1)
|
||||
)
|
||||
after = await session.scalar(
|
||||
select(TOPHistoricalData)
|
||||
.where(
|
||||
TOPHistoricalData.user_unique_identifier == user_name,
|
||||
TOPHistoricalData.api_type == 'User Profile',
|
||||
TOPHistoricalData.update_time >= target_time,
|
||||
)
|
||||
.order_by(TOPHistoricalData.update_time.asc())
|
||||
.limit(1)
|
||||
)
|
||||
if before is None:
|
||||
selected = after
|
||||
elif after is None:
|
||||
selected = before
|
||||
else:
|
||||
selected = (
|
||||
before
|
||||
if abs((target_time - before.update_time).total_seconds())
|
||||
<= abs((target_time - after.update_time).total_seconds())
|
||||
else after
|
||||
)
|
||||
if selected is None or not isinstance(selected.data, UserProfile):
|
||||
return None
|
||||
return selected.data
|
||||
|
||||
|
||||
def compare_metrics(
|
||||
current: TetrisMetricsBasicWithLPM, compare: TetrisMetricsBasicWithLPM | None
|
||||
) -> tuple[Trending, Trending]:
|
||||
if compare is None:
|
||||
return Trending.KEEP, Trending.KEEP
|
||||
return Trending.compare(compare.lpm, current.lpm), Trending.compare(compare.apm, current.apm)
|
||||
|
||||
|
||||
@alc.assign('TOP.query')
|
||||
async def _(event: Event, matcher: Matcher, target: At | Me, event_session: EventSession):
|
||||
async def _( # noqa: PLR0913
|
||||
user: NBUser,
|
||||
event: Event,
|
||||
matcher: Matcher,
|
||||
target: At | Me,
|
||||
event_session: Uninfo,
|
||||
compare: timedelta | None = None,
|
||||
):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
command_args=[f'--compare {compare}'] if compare is not None else [],
|
||||
):
|
||||
async with get_session() as session:
|
||||
bind = await query_bind_info(
|
||||
session=session,
|
||||
user=await get_user(
|
||||
event_session.platform, target.target if isinstance(target, At) else event.get_user_id()
|
||||
event_session.scope, target.target if isinstance(target, At) else event.get_user_id()
|
||||
),
|
||||
game_platform=GAME_TYPE,
|
||||
)
|
||||
if bind is None:
|
||||
await matcher.finish('未查询到绑定信息')
|
||||
if bind is None:
|
||||
await matcher.finish(Lang.bind.not_found())
|
||||
compare_delta = await resolve_compare_delta(TOPUserConfig, session, user.id, compare)
|
||||
player = Player(user_name=bind.game_account, trust=True)
|
||||
profile = await player.get_profile()
|
||||
compare_profile = await get_compare_profile(
|
||||
session,
|
||||
profile.user_name,
|
||||
datetime.now(tz=UTC) - compare_delta,
|
||||
)
|
||||
await (
|
||||
UniMessage(CANT_VERIFY_MESSAGE)
|
||||
+ await make_query_result(await Player(user_name=bind.game_account, trust=True).get_profile())
|
||||
UniMessage.i18n(Lang.interaction.warning.unverified)
|
||||
+ (
|
||||
UniMessage('\n')
|
||||
if not (result := await make_query_result(profile, compare_profile)).has(Image)
|
||||
else UniMessage()
|
||||
)
|
||||
+ result
|
||||
).finish()
|
||||
|
||||
|
||||
@alc.assign('TOP.query')
|
||||
async def _(account: Player, event_session: EventSession):
|
||||
async def _(user: NBUser, account: Player, event_session: Uninfo, compare: timedelta | None = None):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='query',
|
||||
command_args=[],
|
||||
command_args=[f'--compare {compare}'] if compare is not None else [],
|
||||
):
|
||||
await (await make_query_result(await account.get_profile())).finish()
|
||||
async with get_session() as session:
|
||||
compare_delta = await resolve_compare_delta(TOPUserConfig, session, user.id, compare)
|
||||
profile = await account.get_profile()
|
||||
compare_profile = await get_compare_profile(
|
||||
session,
|
||||
profile.user_name,
|
||||
datetime.now(tz=UTC) - compare_delta,
|
||||
)
|
||||
await (await make_query_result(profile, compare_profile)).finish()
|
||||
|
||||
|
||||
def get_avg_metrics(data: list[Data]) -> TetrisMetricsBasicWithLPM:
|
||||
@@ -69,46 +149,61 @@ def get_avg_metrics(data: list[Data]) -> TetrisMetricsBasicWithLPM:
|
||||
return get_metrics(lpm=total_lpm / num, apm=total_apm / num)
|
||||
|
||||
|
||||
async def make_query_image(profile: UserProfile) -> bytes:
|
||||
async def make_query_image(profile: UserProfile, compare: UserProfile | None) -> bytes:
|
||||
if profile.today is None or profile.total is None:
|
||||
raise FallbackError
|
||||
today = get_metrics(lpm=profile.today.lpm, apm=profile.today.apm)
|
||||
history = get_avg_metrics(profile.total)
|
||||
async with HostPage(
|
||||
await render(
|
||||
'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),
|
||||
compare_today = get_metrics(lpm=compare.today.lpm, apm=compare.today.apm) if compare and compare.today else None
|
||||
compare_history = get_avg_metrics(compare.total) if compare is not None and compare.total is not None else None
|
||||
today_lpm_trending, today_apm_trending = compare_metrics(today, compare_today)
|
||||
history_lpm_trending, history_apm_trending = compare_metrics(history, compare_history)
|
||||
return await render_image(
|
||||
Info(
|
||||
user=People(avatar=get_avatar(profile.user_name), name=profile.user_name),
|
||||
today=InfoData(
|
||||
pps=today.pps,
|
||||
lpm=today.lpm,
|
||||
lpm_trending=today_lpm_trending,
|
||||
apm=today.apm,
|
||||
apl=today.apl,
|
||||
apm_trending=today_apm_trending,
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
return await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
historical=InfoData(
|
||||
pps=history.pps,
|
||||
lpm=history.lpm,
|
||||
lpm_trending=history_lpm_trending,
|
||||
apm=history.apm,
|
||||
apl=history.apl,
|
||||
apm_trending=history_apm_trending,
|
||||
),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def make_query_text(profile: UserProfile) -> UniMessage:
|
||||
message = ''
|
||||
if profile.today is not None:
|
||||
today = get_metrics(lpm=profile.today.lpm, apm=profile.today.apm)
|
||||
message += f'用户 {profile.user_name} 24小时内统计数据为: '
|
||||
message += f"\nL'PM: {today.lpm} ( {today.pps} pps )"
|
||||
message += f'\nAPM: {today.apm} ( x{today.apl} )'
|
||||
message += Lang.stats.daily_stats(name=profile.user_name)
|
||||
message += Lang.stats.lpm(lpm=today.lpm, pps=today.pps)
|
||||
message += Lang.stats.apm(apm=today.apm, apl=today.apl)
|
||||
else:
|
||||
message += f'用户 {profile.user_name} 暂无24小时内统计数据'
|
||||
message += Lang.stats.no_daily(name=profile.user_name)
|
||||
if profile.total is not None:
|
||||
total = get_avg_metrics(profile.total)
|
||||
message += '\n历史统计数据为: '
|
||||
message += f"\nL'PM: {total.lpm} ( {total.pps} pps )"
|
||||
message += f'\nAPM: {total.apm} ( x{total.apl} )'
|
||||
message += Lang.stats.history_stats()
|
||||
message += Lang.stats.lpm(lpm=total.lpm, pps=total.pps)
|
||||
message += Lang.stats.apm(apm=total.apm, apl=total.apl)
|
||||
else:
|
||||
message += '\n暂无历史统计数据'
|
||||
message += Lang.stats.no_history()
|
||||
return UniMessage(message)
|
||||
|
||||
|
||||
async def make_query_result(profile: UserProfile) -> UniMessage:
|
||||
async def make_query_result(profile: UserProfile, compare: UserProfile | None) -> UniMessage:
|
||||
try:
|
||||
return UniMessage.image(raw=await make_query_image(profile))
|
||||
return UniMessage.image(raw=await make_query_image(profile, compare))
|
||||
except FallbackError:
|
||||
...
|
||||
return make_query_text(profile)
|
||||
|
||||
75
nonebot_plugin_tetris_stats/games/top/unbind.py
Normal file
75
nonebot_plugin_tetris_stats/games/top/unbind.py
Normal file
@@ -0,0 +1,75 @@
|
||||
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 ...i18n import Lang
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.render.schemas.bind import Bind
|
||||
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(Lang.bind.no_account(game='TOP')).finish()
|
||||
resp = await suggest(Lang.bind.confirm_unbind(), ['是', '否'])
|
||||
if resp is None or resp.extract_plain_text() == '否':
|
||||
return
|
||||
player = Player(user_name=bind.game_account, trust=True)
|
||||
user = await player.user
|
||||
await UniMessage.image(
|
||||
raw=await render_image(
|
||||
Bind(
|
||||
platform='TOP',
|
||||
type='unbind',
|
||||
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=Lang.prompt.top_bind(),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
).send()
|
||||
await remove_bind(session=session, user=nb_user, game_platform=GAME_TYPE)
|
||||
@@ -1,8 +1,9 @@
|
||||
from arclet.alconna import Arg, ArgFlag
|
||||
from nonebot_plugin_alconna import Args, At, Subcommand
|
||||
from nonebot_plugin_alconna import Args, At, Option, Subcommand
|
||||
|
||||
from ...utils.duration import parse_duration
|
||||
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 +35,20 @@ command.add(
|
||||
),
|
||||
help_text='绑定 茶服 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'unbind',
|
||||
help_text='解除绑定 TOS 账号',
|
||||
),
|
||||
Subcommand(
|
||||
'config',
|
||||
Option(
|
||||
'--default-compare',
|
||||
Arg('compare', parse_duration, notice='对比时间距离'),
|
||||
alias=['-DC', 'DefaultCompare'],
|
||||
help_text='设置默认对比时间距离',
|
||||
),
|
||||
help_text='茶服 查询个性化配置',
|
||||
),
|
||||
Subcommand(
|
||||
'query',
|
||||
Args(
|
||||
@@ -50,15 +65,39 @@ command.add(
|
||||
flags=[ArgFlag.HIDDEN, ArgFlag.OPTIONAL],
|
||||
),
|
||||
),
|
||||
Option(
|
||||
'--compare',
|
||||
Arg('compare', parse_duration),
|
||||
alias=['-C'],
|
||||
help_text='指定对比时间距离',
|
||||
),
|
||||
help_text='查询 茶服 游戏信息',
|
||||
),
|
||||
help_text='茶服 游戏相关指令',
|
||||
)
|
||||
)
|
||||
|
||||
alc.shortcut('(?i:tos|茶服)(?i:绑定|绑|bind)', {'command': 'tstats TOS bind', 'humanized': '茶服绑定'})
|
||||
alc.shortcut('(?i:tos|茶服)(?i:查询|查|query|stats)', {'command': 'tstats TOS query', 'humanized': '茶服查'})
|
||||
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='茶服查',
|
||||
)
|
||||
alc.shortcut(
|
||||
'(?i:tos|茶服)(?i:配置|配|config)',
|
||||
command='tstats TOS config',
|
||||
humanized='茶服配置',
|
||||
)
|
||||
|
||||
add_block_handlers(alc.assign('TOS.query'))
|
||||
|
||||
from . import bind, query # noqa: E402, F401
|
||||
from . import bind, config, query, unbind # noqa: E402, F401
|
||||
|
||||
@@ -11,8 +11,10 @@ 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)
|
||||
user_unique_identifier: Mapped[str] = mapped_column(String(256), index=True)
|
||||
api_type: Mapped[Literal['User Info', 'User Profile']] = mapped_column(String(16), index=True)
|
||||
data: Mapped[UserInfoSuccess | UserProfile] = mapped_column(
|
||||
PydanticType(get_model=[], models={UserInfoSuccess, UserProfile})
|
||||
|
||||
@@ -59,15 +59,16 @@ class Player:
|
||||
async def get_info(self) -> UserInfoSuccess:
|
||||
"""获取用户信息"""
|
||||
if self._user_info is None:
|
||||
path = str(
|
||||
URL('getTeaIdInfo') % {'teaId': self.teaid}
|
||||
if self.teaid is not None
|
||||
else URL('getUsernameInfo') % {'username': cast(str, self.user_name)}
|
||||
)
|
||||
if self.teaid is not None:
|
||||
path = 'getTeaIdInfo'
|
||||
query = {'teaId': self.teaid}
|
||||
else:
|
||||
path = 'getUsernameInfo'
|
||||
query = {'username': cast('str', self.user_name)}
|
||||
raw_user_info = await request.failover_request(
|
||||
[i / path for i in BASE_URL], failover_code=[502], failover_exc=(TimeoutException,)
|
||||
[i / path % query for i in BASE_URL], failover_code=[502], failover_exc=(TimeoutException,)
|
||||
)
|
||||
user_info: UserInfo = type_validate_json(UserInfo, raw_user_info) # type: ignore[arg-type]
|
||||
user_info: UserInfo = type_validate_json(UserInfo, raw_user_info) # type: ignore[arg-type] # pyright: ignore[reportArgumentType]
|
||||
if not isinstance(user_info, UserInfoSuccess):
|
||||
msg = f'用户信息请求错误:\n{user_info.error}'
|
||||
raise RequestError(msg)
|
||||
@@ -90,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,16 +1,20 @@
|
||||
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 ...i18n import Lang
|
||||
from ...utils.image import get_avatar
|
||||
from ...utils.render import Bind, render
|
||||
from ...utils.lang import get_lang
|
||||
from ...utils.render import render_image
|
||||
from ...utils.render.schemas.base import People
|
||||
from ...utils.screenshot import screenshot
|
||||
from ...utils.render.schemas.bind import Bind
|
||||
from . import alc
|
||||
from .api import Player
|
||||
from .constant import GAME_TYPE
|
||||
@@ -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),
|
||||
@@ -40,23 +43,32 @@ async def _(
|
||||
)
|
||||
user_info = await account.get_info()
|
||||
if bind_status in (BindStatus.SUCCESS, BindStatus.UPDATE):
|
||||
async with HostPage(
|
||||
await render(
|
||||
'v1/binding',
|
||||
await UniMessage.image(
|
||||
raw=await render_image(
|
||||
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.prompt.tos_check(),
|
||||
lang=get_lang(),
|
||||
),
|
||||
)
|
||||
) as page_hash:
|
||||
await UniMessage.image(
|
||||
raw=await screenshot(f'http://{get_self_netloc()}/host/{page_hash}.html')
|
||||
).finish()
|
||||
).finish()
|
||||
|
||||
32
nonebot_plugin_tetris_stats/games/tos/config.py
Normal file
32
nonebot_plugin_tetris_stats/games/tos/config.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from nonebot_plugin_alconna.uniseg import UniMessage
|
||||
from nonebot_plugin_orm import async_scoped_session
|
||||
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
|
||||
|
||||
from ...db import trigger
|
||||
from ...i18n import Lang
|
||||
from . import alc
|
||||
from .constant import GAME_TYPE
|
||||
from .models import TOSUserConfig
|
||||
|
||||
|
||||
@alc.assign('TOS.config')
|
||||
async def _(user: User, session: async_scoped_session, event_session: Uninfo, compare: timedelta):
|
||||
async with trigger(
|
||||
session_persist_id=await get_session_persist_id(event_session),
|
||||
game_platform=GAME_TYPE,
|
||||
command_type='config',
|
||||
command_args=[f'--default-compare {compare}'],
|
||||
):
|
||||
config = (await session.scalars(select(TOSUserConfig).where(TOSUserConfig.id == user.id))).one_or_none()
|
||||
if config is None:
|
||||
config = TOSUserConfig(id=user.id, compare_delta=compare)
|
||||
session.add(config)
|
||||
else:
|
||||
config.compare_delta = compare
|
||||
await session.commit()
|
||||
await UniMessage(Lang.bind.config_success()).finish()
|
||||
@@ -1,4 +1,4 @@
|
||||
from re import compile
|
||||
from re import compile # noqa: A004
|
||||
from typing import Literal
|
||||
|
||||
from yarl import URL
|
||||
|
||||
12
nonebot_plugin_tetris_stats/games/tos/models.py
Normal file
12
nonebot_plugin_tetris_stats/games/tos/models.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from nonebot_plugin_orm import Model
|
||||
from sqlalchemy import Interval
|
||||
from sqlalchemy.orm import Mapped, MappedAsDataclass, mapped_column
|
||||
|
||||
|
||||
class TOSUserConfig(MappedAsDataclass, Model):
|
||||
__tablename__ = 'nb_t_tos_u_cfg'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
compare_delta: Mapped[timedelta | None] = mapped_column(Interval(native=True), nullable=True)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user