Remove bundled legacy plugin fixture

This commit is contained in:
whatevertogo
2026-03-13 15:04:54 +08:00
parent 91b5ed400e
commit ea8731b693
23 changed files with 0 additions and 19897 deletions

View File

@@ -1,207 +0,0 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$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.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
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
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.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
#poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
#pdm.lock
#pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
#pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# 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
.env
.envrc
.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/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Cursor
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
# refer to https://docs.cursor.com/context/ignore-files
.cursorignore
.cursorindexingignore
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/

View File

@@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2022-2099 AstrBot Plugin Authors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@@ -1,135 +0,0 @@
# 明日方舟猜猜乐Mrfzcclv1.1.9
AstrBot 插件:遮挡干员立绘猜名字;支持排行榜、名片、比赛模式。
## 命令
### 游戏
| 命令 | 说明 | 示例 |
|---|---|---|
| `/fc` | 开始一局(私聊=个人;群聊=群内同一题) | `/fc` |
| `/fcc 干员名` | 猜测干员名称 | `/fcc 能天使` |
| `/fct` | 下一条提示 | `/fct` |
| `/fcw` | 一次性三条提示 | `/fcw` |
| `/fce` | 强制结束并显示答案 | `/fce` |
### 统计(`/ccl`
| 命令 | 说明 |
|---|---|
| `/ccl 排行榜` | 正确量排行榜 |
| `/ccl 错误排行榜` | 错误量排行榜 |
| `/ccl 提示排行榜` | 提示使用排行榜 |
| `/ccl 名片 [用户ID]` | 用户名片(不填=自己) |
注:`require_admin=true` 时,排行榜仅管理员可用。
### 比赛(群聊,仅管理员)
| 命令 | 说明 | 示例 |
|---|---|---|
| `/ccl 比赛帮助` | 查看比赛命令 | `/ccl 比赛帮助` |
| `/ccl 比赛创建 [名称] [题目限制] [时间限制(分钟)]` | 创建比赛0=不限制) | `/ccl 比赛创建 春节赛 20 30` |
| `/ccl 比赛开始` | 开始比赛并发送第一题 | `/ccl 比赛开始` |
| `/ccl 比赛结束` | 结束比赛并结算荣誉/排行 | `/ccl 比赛结束` |
| `/ccl 比赛排行` | 查看当前比赛排行 | `/ccl 比赛排行` |
| `/ccl 清除数据 [user_id]` | 清除指定用户的比赛数据 | `/ccl 清除数据 123456` |
| `/ccl 清除荣誉 [user_id]` | 清除指定用户的比赛荣誉 | `/ccl 清除荣誉 123456` |
| `/ccl 清除所有数据` | 清除所有用户的比赛数据 | `/ccl 清除所有数据` |
| `/ccl 清除所有荣誉` | 清除所有用户的比赛荣誉 | `/ccl 清除所有荣誉` |
| `/ccl 授予荣誉 [user_id] [名次] [比赛名称] [答对数量]` | 授予用户比赛荣誉 | `/ccl 授予荣誉 123456 1 春节赛 20` |
## 比赛机制
- 自动出题:`/ccl 比赛开始` 后发送第一题;任意玩家答对后自动发送下一题。
- 自动结束:达到题目上限或时间上限会自动结束并发送排行榜,同时写入荣誉(名片可查)。
- 题目上限口径:按“累计答对题数(每题首次答对)”计。
- 计分:`score = correct_count - wrong_count / 3`
- 自动提示:每题超过 `match_hint_delay` 秒未答对,会按提示序列持续发送提示直到没有可提示为止。
## 提示规则
提示序列(每次提示推进 1 步):
1. 职业及分支
2. 星级
3. 阵营
4. 获取方式
5. 名称提示:每次增加显示 `ceil(len(name)/3)` 个字,直到全名
名称提示示例:名字长度 5 → 每次增加 2 个字 → 2/4/5。
## 配置(`_conf_schema.json`
- `mrfz_data_path`: 题库 JSON 路径(默认 `arknights_skins_dict.json`
- `target_size`: 输出图片参考大小
- `easy_probability` / `medium_probability` / `hard_probability`: 难度概率
- `similarity_threshold`: 相似度阈值SequenceMatcher
- `calculate_threshold`: 字符覆盖率阈值
- `enable_homophone`: 同音字识别
- `daily_game_limit`: 每日开局次数0=不限制)
- `match_question_limit`: 比赛题目上限0=不限制)
- `match_time_limit`: 比赛时间上限分钟0=不限制)
- `match_hint_delay`: 比赛超时自动提示0=关闭;默认 30
- `admin_ids`: 比赛/管理指令管理员列表
- `require_admin`: 排行榜/名片是否仅管理员可用
- `low_weight_characters`: 低权重干员关键词(逗号分隔)
- `low_weight_ratio`: 低权重干员出现比例
- `character_aliases`: 别名映射(`别名:正名,...`
- `renderer_theme`: 排行榜/名片主题
## 更新日志
### v1.1.9
- ✅ 修复判定题目数量限制的user_id使用错误
- ✅ 修复题目数量限制不过滤管理员的错误
- ✅ 修复当前多个人在共同使用时存在的竞态问题
### v1.1.8
- ✅ 修复比赛:到达题目/时间限制未自动结束
- ✅ 修复比赛:开始/答对后不自动出下一题
- ✅ 新增比赛:超时自动提示(循环到提示耗尽)
- ✅ 调整提示:名称提示按 1/3向上取整递进
- ✅ 修复比赛荣誉:重复写入导致名片重复显示
### v1.1.6
- ✅ 优化路径处理,使用可配置的相对路径
- ✅ 扩展干员别名库,支持更多常见昵称
- ✅ 移除冗余配置项,简化配置文件
- ✅ 修复依赖问题,确保插件正常运行
### v1.1.2
- 优化画图
### v1.1.0
- ✅ 新增排行榜系统(正确量、错误量、提示使用榜)
- ✅ 添加个人档案查询功能
- ✅ 实现图片可视化排行榜
- ✅ 完善SQLite数据持久化
- ✅ 优化错误处理和资源管理
### v1.0.0
- ✅ 基础猜谜游戏功能
- ✅ 模糊匹配算法
- ✅ 提示系统
- ✅ 多会话支持
## 📊 数据来源
- 感谢blibliwiki的立绘资源
- 干员数据基于公开的明日方舟游戏信息
## 📄 许可证
AGPL-3.0
## 👨‍💻 开发者
- **开发者**Lishining
- **版本**v1.1.9
- **标语**:你知道的,我一直是明日方舟高手
- **QQ群**: 1083090761
---
*感谢所有参与测试的明日方舟博士们!游戏愉快!🎮*
*欢迎iss和pr,我看见了会认真修改的!*

View File

@@ -1,110 +0,0 @@
{
"mrfz_data_path": {
"description": "明日方舟角色数据(插件自带,可以通过修改文件来修改随机池)",
"type": "string",
"default": "arknights_skins_dict.json",
"hint": "例如:/home/user/arknights_skins_dict.json"
},
"target_size": {
"description": "角色立绘最后输出的参考大小",
"type": "int",
"default": 512,
"hint": "例如512"
},
"similarity_threshold": {
"description": "判断是否正确的阈值,语义的相似度,越高判断的要求越高",
"type": "float",
"default": 0.4,
"hint": "(0.-1.) 推荐0.4-0.5"
},
"calculate_threshold": {
"description": "判断是否正确的阈值,字的准确率(与位置无关仅判断字是否正确),越高判断的要求越高",
"type": "float",
"default": 0.5,
"hint": "(0.-1.) 推荐0.5-0.6"
},
"enable_homophone": {
"description": "启用同音字识别,例如「银灰」和「银辉」都会被识别为正确",
"type": "bool",
"default": false,
"hint": "true开启,false关闭"
},
"easy_probability": {
"description": "简单难度概率(0-1)",
"type": "float",
"default": 0.6,
"hint": "60%概率出现简单难度(5个方块)"
},
"medium_probability": {
"description": "中等难度概率(0-1)",
"type": "float",
"default": 0.3,
"hint": "30%概率出现中等难度(3个方块)"
},
"hard_probability": {
"description": "困难难度概率(0-1)",
"type": "float",
"default": 0.1,
"hint": "10%概率出现困难难度(1个方块)"
},
"daily_game_limit": {
"description": "每个用户每日开启游戏次数限制",
"type": "int",
"default": 10,
"hint": "0表示无限制"
},
"match_question_limit": {
"description": "比赛答题数量限制(0表示不限制)",
"type": "int",
"default": 0,
"hint": "答完指定数量自动结束,在创建比赛时不填写默认使用该值"
},
"match_time_limit": {
"description": "比赛时间限制(分钟,0表示不限制)",
"type": "int",
"default": 0,
"hint": "超过指定时间自动结束,在创建比赛时不填写默认使用该值"
},
"match_hint_delay": {
"description": "比赛超时自动提示(秒,0表示关闭)",
"type": "int",
"default": 30,
"hint": "每题超过指定时间未答对,将自动发送 1 条提示"
},
"admin_ids": {
"description": "管理员QQ号列表",
"type": "list",
"default": [],
"hint": "例如: [123456789, 987654321]"
},
"low_weight_characters": {
"description": "低权重干员关键词(逗号分隔)",
"type": "string",
"default": "预备干员,机师,W,SideStory",
"hint": "这些干员出现频率会降低"
},
"low_weight_ratio": {
"description": "低权重干员出现概率(0-1)",
"type": "float",
"default": 0.2,
"hint": "0.2表示降低该干员出现概率为原本的0.2"
},
"require_admin": {
"description": "排行榜查看指令是否启动管理员限制",
"type": "bool",
"default": true,
"hint": "true开启,false关闭"
},
"character_aliases": {
"description": "干员别名映射(别名:正名,多组用逗号分隔)",
"type": "string",
"default": "小刻:刻俄柏,小羊:艾雅法拉,42:史尔特尔,42姐:史尔特尔,玫剑圣:玫兰莎,克天使:克洛丝,kokodayo:克洛丝,猛男:安塞尔,医疗小车:Lancet-2,近卫小车:Castle-3,太子爷:12F,桃:桃金娘,富婆:杰西卡,阿米驴:阿米娅,银老板:银灰,前夫哥:银灰,虎鲸:斯卡蒂,蒂蒂:斯卡蒂,大腿夹剑:斯卡蒂,老爷子:赫拉格,大公:赫拉格,肠粉龙:陈,煌猫:煌,寒哥:棘刺,傻狗:刻俄柏,忧郁蓝调:莫斯提马,企鹅:麦哲伦,瑕子姐:瑕光,闪剑圣:闪灵,喜羊羊:闪灵,塞爹:塞雷娅,塞妈:塞雷娅,莱茵拳皇:塞雷娅,鬼姐:星熊,星sir:星熊",
"hint": "格式: 别名1:正名1,别名2:正名2"
},
"renderer_theme": {
"description": "问答统计图片主题",
"type": "string",
"default": "light",
"hint": "可选light(浅色)、industrial(深色)、retro_win(复古Win)"
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +0,0 @@
name: astrbot_plugin_mrfzccl # 插件唯一识别名,以 astrbot_plugin_ 前缀开头
display_name: 明日方舟猜猜乐 # 用于展示的名字,可以是方便人类阅读的名字(需要版本 >= v4.5.0,低版本不会报错,请放心填写)
desc: 明日方舟干员立绘猜猜乐,支持排行榜/名片/比赛模式 # 插件简短描述
version: v1.1.9 # 插件版本号。格式v1.1.1 或者 v1.1
author: lishining # 作者
repo: https://github.com/Li-shi-ling/astrbot_plugin_mrfzccl # 插件的仓库地址
support_platforms:
- aiocqhttp

View File

@@ -1,4 +0,0 @@
html2image
aiohttp
pypinyin
numpy

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +0,0 @@
from .QnAStatsRenderer import QnAStatsRenderer
class QnAStatsRendererIndustrial(QnAStatsRenderer):
"""
工业(深色)主题渲染器。
用法:
- 白天浅色QnAStatsRenderer(...)
- 工业深色QnAStatsRendererIndustrial(...)
"""
def __init__(self, output_dir: str = "data/quiz_images"):
super().__init__(output_dir=output_dir, theme="industrial")

View File

@@ -1,14 +0,0 @@
from .QnAStatsRenderer import QnAStatsRenderer
class QnAStatsRendererRetroWin(QnAStatsRenderer):
"""
复古 Win / 像素风主题渲染器。
用法:
- 默认浅色QnAStatsRenderer(...)
- 工业深色QnAStatsRendererIndustrial(...)
- 复古WinQnAStatsRendererRetroWin(...)
"""
def __init__(self, output_dir: str = "data/quiz_images"):
super().__init__(output_dir=output_dir, theme="retro_win")

View File

@@ -1,110 +0,0 @@
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlmodel import SQLModel
from sqlalchemy.exc import OperationalError
import os
class DBManager:
"""数据库管理器,负责异步连接和会话管理"""
def __init__(self, db_path: str):
os.makedirs(os.path.dirname(os.path.abspath(db_path)), exist_ok=True)
self.db_url = f"sqlite+aiosqlite:///{db_path}"
# 创建异步引擎
self.engine = create_async_engine(
self.db_url,
echo=False,
pool_pre_ping=True,
pool_recycle=3600,
# pool_size=5,
# max_overflow=5,
)
# 创建会话工厂
self.async_session = async_sessionmaker(
self.engine,
class_=AsyncSession,
expire_on_commit=False,
)
self.async_session_factory = self.async_session
async def init_db(self):
"""初始化数据库,创建所有定义的表"""
async with self.engine.begin() as conn:
try:
await conn.run_sync(SQLModel.metadata.create_all)
except OperationalError as e:
if "already exists" not in str(e):
raise
async with self.engine.begin() as conn:
try:
await conn.execute(text(
"ALTER TABLE match ADD COLUMN question_limit INTEGER DEFAULT 0"
))
except OperationalError:
pass
try:
await conn.execute(text(
"ALTER TABLE match ADD COLUMN time_limit INTEGER DEFAULT 0"
))
except OperationalError:
pass
try:
await conn.execute(text(
"ALTER TABLE match ADD COLUMN started_at TIMESTAMP"
))
except OperationalError:
pass
try:
await conn.execute(text(
"ALTER TABLE match_participant ADD COLUMN wrong_count INTEGER DEFAULT 0"
))
except OperationalError:
pass
try:
await conn.execute(text(
"ALTER TABLE match_participant ADD COLUMN score REAL DEFAULT 0.0"
))
except OperationalError:
pass
try:
await conn.execute(text(
"ALTER TABLE match_honor ADD COLUMN wrong_count INTEGER DEFAULT 0"
))
except OperationalError:
pass
try:
await conn.execute(text(
"ALTER TABLE match_honor ADD COLUMN score REAL DEFAULT 0.0"
))
except OperationalError:
pass
# SQLite 优化 PRAGMA
async with self.engine.connect() as conn:
await conn.execute(text("PRAGMA journal_mode=WAL"))
await conn.execute(text("PRAGMA synchronous=NORMAL"))
await conn.execute(text("PRAGMA cache_size=-20000"))
await conn.execute(text("PRAGMA temp_store=MEMORY"))
await conn.execute(text("PRAGMA mmap_size=134217728"))
await conn.execute(text("PRAGMA optimize"))
await conn.commit()
@asynccontextmanager
async def get_session(self) -> AsyncGenerator[AsyncSession, None]:
"""异步获取数据库会话的上下文管理器"""
session = self.async_session_factory()
try:
async with session.begin():
yield session
finally:
await session.close()

File diff suppressed because it is too large Load Diff

View File

@@ -1,67 +0,0 @@
from datetime import datetime
from typing import Optional
from sqlmodel import Field, SQLModel
class UserQnAStats(SQLModel, table=True):
"""用户问答统计表 - 记录用户的答题统计数据"""
__tablename__ = "user_qna_stats"
__table_args__ = {"extend_existing": True}
id: Optional[int] = Field(default=None, primary_key=True, description="主键ID自增唯一标识")
user_id: str = Field(index=True, description="用户ID")
user_name: str = Field(index=True, description="用户名称")
correct_count: int = Field(default=0, description="答对次数")
wrong_count: int = Field(default=0, description="答错次数")
tip_count: int = Field(default=0, description="提示次数")
created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
updated_at: datetime = Field(default_factory=datetime.now, description="更新时间")
class Match(SQLModel, table=True):
"""比赛表"""
__tablename__ = "match"
__table_args__ = {"extend_existing": True}
match_id: Optional[int] = Field(default=None, primary_key=True)
group_id: str = Field(index=True, description="群ID")
match_name: str = Field(description="比赛名称")
is_active: bool = Field(default=True, description="是否进行中")
question_limit: int = Field(default=0, description="答题数量限制(0不限制)")
time_limit: int = Field(default=0, description="时间限制分钟(0不限制)")
created_at: datetime = Field(default_factory=datetime.now)
started_at: Optional[datetime] = Field(default=None, description="开始时间")
ended_at: Optional[datetime] = Field(default=None, description="结束时间")
class MatchParticipant(SQLModel, table=True):
"""比赛参与者表"""
__tablename__ = "match_participant"
__table_args__ = {"extend_existing": True}
id: Optional[int] = Field(default=None, primary_key=True)
match_id: int = Field(index=True, description="比赛ID")
user_id: str = Field(index=True, description="用户ID")
user_name: str = Field(description="用户名称")
correct_count: int = Field(default=0, description="答对数")
wrong_count: int = Field(default=0, description="答错数")
score: float = Field(default=0.0, description="得分(正确数-错误数*1/3)")
joined_at: datetime = Field(default_factory=datetime.now)
class MatchHonor(SQLModel, table=True):
"""比赛荣誉表"""
__tablename__ = "match_honor"
__table_args__ = {"extend_existing": True}
id: Optional[int] = Field(default=None, primary_key=True)
user_id: str = Field(index=True, description="用户ID")
match_id: int = Field(description="比赛ID")
match_name: str = Field(description="比赛名称")
rank: int = Field(description="名次")
correct_count: int = Field(default=0, description="答对数")
wrong_count: int = Field(default=0, description="答错数")
score: float = Field(default=0.0, description="得分(正确数-错误数*1/3)")
medal: str = Field(description="奖牌")
created_at: datetime = Field(default_factory=datetime.now)

View File

@@ -1,2 +0,0 @@
"""Command handler modules for Mrfzccl plugin (stage-1 split)."""

View File

@@ -1,123 +0,0 @@
from __future__ import annotations
from typing import Any, AsyncIterator
from astrbot.api.event import AstrMessageEvent
async def handle_reset_user_data(
self,
event: AstrMessageEvent,
target_user_id: str = "",
) -> AsyncIterator[Any]:
"""清除用户答题数据(仅管理员)/ccl 清除数据 [user_id]"""
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以清除数据")
return
if target_user_id:
await self.user_qna_repo.reset_user_stats(target_user_id)
yield event.plain_result(f"✅ 用户 {target_user_id} 的答题数据已清除")
else:
await self.user_qna_repo.reset_user_stats(sender_id)
yield event.plain_result("✅ 您的答题数据已清除")
async def handle_reset_user_honors_cmd(
self,
event: AstrMessageEvent,
target_user_id: str = "",
) -> AsyncIterator[Any]:
"""清除用户荣誉数据(仅管理员)/ccl 清除荣誉 [user_id]"""
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以清除荣誉")
return
if target_user_id:
await self.match_repo.reset_user_honors(target_user_id)
yield event.plain_result(f"✅ 用户 {target_user_id} 的荣誉数据已清除")
else:
await self.match_repo.reset_user_honors(sender_id)
yield event.plain_result("✅ 您的荣誉数据已清除")
async def handle_reset_all_data_cmd(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""清除所有用户的答题数据(仅管理员)/ccl 清除所有数据"""
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以清除所有数据")
return
await self.user_qna_repo.reset_all_stats()
yield event.plain_result("✅ 所有用户的答题数据已清除")
async def handle_reset_all_honors_cmd(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""清除所有用户的荣誉数据(仅管理员)/ccl 清除所有荣誉"""
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以清除所有荣誉")
return
await self.match_repo.reset_all_honors()
yield event.plain_result("✅ 所有用户的荣誉数据已清除")
async def handle_grant_honor_cmd(
self,
event: AstrMessageEvent,
target_user_id: str = "",
rank: int = 1,
match_name: str = "",
correct_count: int = 0,
) -> AsyncIterator[Any]:
"""授予用户特定荣誉(仅管理员)/ccl 授予荣誉 [user_id] [名次] [比赛名称] [答对数量]"""
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以授予荣誉")
return
# 检查参数完整性
if not target_user_id or not match_name:
yield event.plain_result("❌ 请提供完整参数: /ccl 授予荣誉 [user_id] [名次] [比赛名称] [答对数量]")
return
# 根据名次生成奖牌表情
if rank == 1:
medal = "🥇"
elif rank == 2:
medal = "🥈"
elif rank == 3:
medal = "🥉"
else:
medal = f"{rank}"
# 计算得分错误数默认为0
score = correct_count - 0
# 保存荣誉
await self.match_repo.save_honor(
user_id=target_user_id,
match_id=0, # 虚拟比赛ID
match_name=match_name,
rank=rank,
correct_count=correct_count,
wrong_count=0,
score=score,
)
yield event.plain_result(
f"✅ 已授予用户 {target_user_id} 荣誉: {medal} {match_name}{rank}名, 答对{correct_count}"
)

View File

@@ -1,137 +0,0 @@
from __future__ import annotations
from typing import Any, AsyncIterator
from astrbot.api.event import AstrMessageEvent
from ..tool import (
generate_correct_leaderboard_text,
generate_hints_leaderboard_text,
generate_image_or_fallback,
generate_user_profile_text,
generate_wrong_leaderboard_text,
)
async def handle_correct_answers_leaderboard(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""获取正确个数的排行榜命令 /ccl 排行榜"""
if self.require_admin:
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以查看排行榜")
return
try:
# 获取排行榜数据前10名
users = await self.user_qna_repo.get_correct_answers_leaderboard(limit=10)
if not users:
yield event.plain_result("📊 当前还没有用户的答题记录哦~")
return
# 获取统计信息
summary = await self.user_qna_repo.get_leaderboard_summary()
# 使用统一的图片/文本生成函数
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_correct_leaderboard_image(users),
generate_text_func=lambda: generate_correct_leaderboard_text(users, summary),
):
yield result
except Exception as e:
yield event.plain_result(f"获取排行榜时出现错误: {str(e)}")
async def handle_wrong_answers_leaderboard(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""获取错误个数的排行榜命令 /ccl 错误排行榜"""
if self.require_admin:
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以查看排行榜")
return
try:
# 获取排行榜数据前10名
users = await self.user_qna_repo.get_wrong_answers_leaderboard(limit=10)
if not users:
yield event.plain_result("📊 当前还没有用户的答题记录哦~")
return
# 使用统一的图片/文本生成函数
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_wrong_leaderboard_image(users),
generate_text_func=lambda: generate_wrong_leaderboard_text(users),
):
yield result
except Exception as e:
yield event.plain_result(f"获取排行榜时出现错误: {str(e)}")
async def handle_hints_usage_leaderboard(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""获取使用提示次数的排行榜命令 /ccl 提示排行榜"""
if self.require_admin:
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以查看排行榜")
return
try:
# 获取排行榜数据前10名
users = await self.user_qna_repo.get_hints_usage_leaderboard(limit=10)
if not users:
yield event.plain_result("📊 当前还没有用户的答题记录哦~")
return
# 使用统一的图片/文本生成函数
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_hints_leaderboard_image(users),
generate_text_func=lambda: generate_hints_leaderboard_text(users),
):
yield result
except Exception as e:
yield event.plain_result(f"获取排行榜时出现错误: {str(e)}")
async def handle_user_profile_retrieval(
self,
event: AstrMessageEvent,
user_id: str | None = None,
) -> AsyncIterator[Any]:
"""获取个人信息获取 /ccl 名片 [user_id] (如果user_id为空默认为发送人)"""
try:
# 确定用户ID
target_user_id = user_id or event.get_sender_id()
# 获取用户信息及排名
user_stats, rank_info = await self.user_qna_repo.get_user_profile_with_rank(target_user_id)
# 获取用户荣誉
honors = await self.match_repo.get_user_honors(str(target_user_id))
# 没有任何记录时直接返回
if not user_stats and not honors:
yield event.plain_result("❌ 未找到该用户的答题记录")
return
# 没有答题记录但有荣誉:直接用文本输出(名片图片依赖 user_stats
if not user_stats:
yield event.plain_result(generate_user_profile_text(user_stats, rank_info, honors, str(target_user_id)))
return
# 使用统一的图片/文本生成函数
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_user_profile_image(user_stats, rank_info, honors),
generate_text_func=lambda: generate_user_profile_text(user_stats, rank_info, honors, str(target_user_id)),
):
yield result
except Exception as e:
yield event.plain_result(f"获取用户信息时出现错误: {str(e)}")

View File

@@ -1,199 +0,0 @@
from __future__ import annotations
import time
from typing import Any, AsyncIterator
import astrbot.api.message_components as Comp
from astrbot.api.event import AstrMessageEvent
from ..tool import generate_image_or_fallback, generate_match_leaderboard_text
async def handle_match_help(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""比赛模式帮助"""
if event.get_group_id() is None:
yield event.plain_result("请在群聊使用")
return
yield event.plain_result(
"""📋 比赛模式指令帮助
━━━━━━━━━━━━━━
/ccl 比赛创建 [名称] [题目限制] [时间限制(分钟)] - 创建比赛(仅管理员)
/ccl 比赛开始 - 开始比赛(仅管理员)
/ccl 比赛结束/结束比赛 - 结束比赛(仅管理员)
/ccl 比赛排行/排行 - 查看比赛排行榜
━━━━━━━━━━━━━━"""
)
async def handle_match_create(
self,
event: AstrMessageEvent,
name: str = "",
question_limit: int = 0,
time_limit: int = 0,
) -> AsyncIterator[Any]:
"""创建比赛(仅管理员)用法: /ccl 比赛创建 [名称] [题目限制] [时间限制(分钟)]"""
group_id_raw = event.get_group_id()
if group_id_raw is None:
yield event.plain_result("请在群聊使用")
return
group_id = str(group_id_raw)
sender_id = str(event.get_sender_id())
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
yield event.plain_result("❌ 只有管理员可以创建比赛")
return
# 检查是否已有进行中的比赛
existing = await self.match_repo.get_active_match(group_id)
if existing:
yield event.plain_result("❌ 当前群已有进行中的比赛")
return
# 设置题目限制和时间限制
q_limit = question_limit if question_limit >= 0 else self.match_question_limit
t_limit = time_limit if time_limit >= 0 else self.match_time_limit
if q_limit < 0 or t_limit < 0:
yield event.plain_result(f"参数未通过检验,q_limit:{q_limit},t_limit:{t_limit}")
return
# 创建比赛名称
match_name = name if name else f"比赛_{int(time.time())}"
# 创建比赛
await self.match_repo.create_match(group_id, match_name, q_limit, t_limit)
# 构建响应信息
info = f"✅ 比赛「{match_name}」已创建!"
if q_limit > 0:
info += f"\n📝 题目限制: {q_limit}"
if t_limit > 0:
info += f"\n⏱️ 时间限制: {t_limit}分钟"
info += "\n进行答题即可参与比赛"
yield event.plain_result(info)
async def match_start_precheck(self, event: AstrMessageEvent) -> tuple[bool, str | None, Any | None]:
"""`/ccl 比赛开始` 的锁外校验与 DB 状态更新。"""
group_id_raw = event.get_group_id()
if group_id_raw is None:
return False, None, event.plain_result("请在群聊使用")
sender_id = str(event.get_sender_id())
group_id = str(group_id_raw)
self.match_sessions[group_id] = event.unified_msg_origin
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
return False, group_id, event.plain_result("❌ 只有管理员可以开始比赛")
# 获取活跃比赛
match = await self.match_repo.get_active_match(group_id)
if not match:
return False, group_id, event.plain_result("❌ 当前没有进行中的比赛")
# 开始比赛
await self.match_repo.start_match(match.match_id)
return True, group_id, None
async def match_start_inlock(self, group_id: str) -> bytes | str | None:
"""`/ccl 比赛开始` 的锁内状态清理 + 出题逻辑。"""
# 防止上次比赛残留题目导致 fc_init 返回 already_exists
self.end_game(group_id)
# 取消旧的比赛循环/提示任务(防止重复启动)
if group_id in self.match_next_task:
self._safe_cancel_task(self.match_next_task.pop(group_id, None))
if group_id in self.match_loop_task:
self._safe_cancel_task(self.match_loop_task.pop(group_id, None))
self.match_question_state.pop(group_id, None)
# 初始化第一题
result = await self.fc_init(group_id)
if result and result != "already_exists":
self.match_question_state[group_id] = time.time()
self._schedule_match_hint(group_id)
return result
def build_match_start_response(event: AstrMessageEvent, result: bytes | str | None) -> Any:
if result and result != "already_exists":
return event.chain_result(
[
Comp.Plain("🏁 比赛已开始!答题即为参与比赛\n干员立绘,请使用/fcc [干员名称] 进行猜测"),
Comp.Image.fromBytes(result),
]
)
return event.plain_result("🏁 比赛已开始!第一题获取失败,请重试")
async def match_end_precheck(self, event: AstrMessageEvent) -> tuple[bool, str | None, Any | None]:
"""`/ccl 比赛结束` 的锁外校验。"""
group_id_raw = event.get_group_id()
if group_id_raw is None:
return False, None, event.plain_result("请在群聊使用")
sender_id = str(event.get_sender_id())
group_id = str(group_id_raw)
# 检查管理员权限
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
return False, group_id, event.plain_result("❌ 只有管理员可以结束比赛")
return True, group_id, None
async def match_end_inlock(self, group_id: str) -> tuple[bool, str, list]:
"""`/ccl 比赛结束` 的锁内结算逻辑。"""
# 重新获取活跃比赛,避免与自动结束并发导致重复荣誉
match_now = await self.match_repo.get_active_match(group_id)
if not match_now or not match_now.is_active:
return False, "", []
match_name, _, top_participants = await self._end_match_and_collect_top(group_id, match_now)
return True, match_name, top_participants
async def iter_match_end_results(
self,
event: AstrMessageEvent,
match_name: str,
top_participants: list,
) -> AsyncIterator[Any]:
"""`/ccl 比赛结束` 的锁外输出(图片优先,失败回退文本)。"""
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_match_leaderboard_image(
match_name,
top_participants,
title=f"比赛「{match_name}」已结束排行榜",
),
generate_text_func=lambda: generate_match_leaderboard_text(match_name, top_participants, ended=True),
):
yield result
async def handle_match_leaderboard(self, event: AstrMessageEvent) -> AsyncIterator[Any]:
"""使用`/ccl 比赛排行`获取比赛排行榜"""
group_id_raw = event.get_group_id()
if group_id_raw is None:
yield event.plain_result("请在群聊使用")
return
group_id = str(group_id_raw)
# 获取活跃比赛
match = await self.match_repo.get_active_match(group_id)
if not match:
yield event.plain_result("❌ 无进行中比赛")
return
# 获取参赛者列表并排序
participants = await self.match_repo.get_participants(match.match_id)
participants.sort(key=lambda p: p.score, reverse=True)
top_participants = participants[:10]
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_match_leaderboard_image(
match.match_name,
top_participants,
),
generate_text_func=lambda: generate_match_leaderboard_text(match.match_name, top_participants),
):
yield result

View File

@@ -1,351 +0,0 @@
from __future__ import annotations
import time
import traceback
from difflib import SequenceMatcher
from typing import Any, AsyncIterator
import astrbot.api.message_components as Comp
from astrbot.api import logger
from astrbot.api.event import AstrMessageEvent
from ..tool import (
calculate_char_coverage_set,
check_daily_limit,
check_homophone,
generate_image_or_fallback,
generate_match_leaderboard_text,
has_active_game,
resolve_alias,
)
async def handle_fc(
self,
event: AstrMessageEvent,
*,
user_id: str,
sender_id: str,
is_group: bool,
group_id: str | None,
) -> Any | None:
"""Core logic for `/fc` (expects room lock is held by caller)."""
response = None
# 确保数据库初始化
try:
await self.db.init_db()
logger.info("[Mrfzccl] 数据库初始化完成")
except Exception as e:
logger.error(f"[Mrfzccl] 数据库初始化失败: {e}")
response = event.chain_result(
[
Comp.At(qq=sender_id),
Comp.Plain(" 数据库初始化失败,请联系管理员"),
]
)
if response is None:
# 检查是否在比赛模式和是否限制(仅群聊)
match = await self.match_repo.get_active_match(group_id) if is_group else None
# 非管理员进行次数检测
if self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
# 非比赛模式下检查每日限制
if not match and not check_daily_limit(sender_id, self.daily_counter, self.daily_limit):
response = event.plain_result(f"今日游戏次数已达上限({self.daily_limit}次),请明天再来!")
if response is None:
try:
# 调用初始化游戏方法
result = await self.fc_init(user_id)
if result == "already_exists":
response = event.plain_result("已经初始化,请不要重复操作")
elif result is None:
response = event.plain_result("图片获取失败,请重试")
else:
# 发送游戏图片
response = event.chain_result(
[
Comp.Plain("干员立绘,请使用/fcc [干员名称] 进行猜测"),
Comp.Image.fromBytes(result),
]
)
except Exception as e:
logger.error(f"[fc] 命令执行失败: {e}")
logger.error(traceback.format_exc())
response = event.plain_result("游戏初始化失败,请稍后重试")
return response
async def handle_fcc(
self,
event: AstrMessageEvent,
*,
user_id: str,
sender_id: str,
is_group: bool,
group_id: str | None,
) -> tuple[list[Any], tuple[str, list] | None]:
"""Core logic for `/fcc` (expects room lock is held by caller)."""
responses: list[Any] = []
match_end_payload: tuple[str, list] | None = None # (ended_match_name, ended_top_participants)
logger.debug(
f"[fcc] user_id={user_id}, player_keys={list(self.player.keys())}, has_active={has_active_game(self.player, user_id)}"
)
# 检查是否有活跃比赛
match = await self.match_repo.get_active_match(group_id) if is_group else None
# 检查用户是否有活跃游戏
if not has_active_game(self.player, user_id):
if match:
responses.append(event.plain_result("比赛期间请等待管理员发送题目"))
else:
responses.append(event.plain_result("没有初始化房间,请使用/fc"))
return responses, match_end_payload
# 提取并清理用户输入的猜测内容
guess_text = self.extract_and_sanitize_input(event.message_str, "fcc")
if not guess_text:
responses.append(
event.chain_result(
[
Comp.At(qq=sender_id),
Comp.Plain(" 请输入要猜测的干员名称"),
]
)
)
return responses, match_end_payload
correct_name = self.player[user_id]["name"] # 获取正确答案
# 解析别名(将用户输入的别名转换为正式名称)
resolved_guess = resolve_alias(guess_text, self.alias_map)
# 计算相似度
similarity = SequenceMatcher(None, correct_name, resolved_guess).ratio()
# 计算字符覆盖率
calculate = calculate_char_coverage_set(correct_name, resolved_guess)
# 检查是否为同音字
homophone_match = check_homophone(correct_name, resolved_guess, enable_homophone=self.enable_homophone)
# 综合判断是否正确
is_correct = (similarity > self.similarity_threshold) or (calculate > self.calculate_threshold) or homophone_match
logger.debug(
f"[答题判断] 正确答案: {correct_name}, 用户回答: {resolved_guess}, 相似度: {similarity:.2f}, "
f"字匹配率: {calculate:.2f}, 同音匹配: {homophone_match}, 阈值: {self.similarity_threshold}/{self.calculate_threshold}, "
f"结果: {is_correct}"
)
sender_name = event.get_sender_name()
# 如果是比赛模式,更新比赛数据
if is_group and match and group_id is not None:
self.match_sessions[group_id] = event.unified_msg_origin
await self.match_repo.add_participant(match.match_id, str(sender_id), sender_name)
if is_correct:
await self.match_repo.increment_participant_score(match.match_id, str(sender_id))
# 取消当前题目的自动提示任务
if group_id in self.match_next_task:
self._safe_cancel_task(self.match_next_task.pop(group_id, None))
else:
await self.match_repo.increment_participant_wrong(match.match_id, str(sender_id))
# 处理回答结果
if is_correct:
chain = [
Comp.At(qq=sender_id),
Comp.Plain(f" 回答正确! 答案为: {correct_name}"),
]
responses.append(event.chain_result(chain))
responses.append(await self.send_original_image(user_id, event)) # 发送原图
# 更新用户正确计数
await self.user_qna_repo.increment_correct_count(
user_id=sender_id,
user_name=sender_name,
)
# 比赛模式:自动出下一题 / 自动结束
if is_group and match and group_id is not None:
# 重新获取活跃比赛,避免已自动结束后再次结算导致重复荣誉
match_now = await self.match_repo.get_active_match(group_id)
if match_now and match_now.is_active:
# 若已经有人推进到下一题,当前协程无需重复出题
existing = self.player.get(group_id)
if not (existing and existing.get("status") in {"active", "loading"}):
end_reason = await self._get_match_end_reason(match_now)
if end_reason:
ended_match_name, _, ended_top_participants = await self._end_match_and_collect_top(
group_id,
match_now,
)
if end_reason == "time_limit":
responses.append(
event.plain_result(f"⏱️ 已达到时间限制,比赛「{ended_match_name}」自动结束!")
)
else:
responses.append(
event.plain_result(f"📝 已达到题目上限,比赛「{ended_match_name}」自动结束!")
)
match_end_payload = (ended_match_name, ended_top_participants)
else:
next_bytes = await self.fc_init(group_id)
if next_bytes and next_bytes != "already_exists":
self.match_question_state[group_id] = time.time()
self._schedule_match_hint(group_id)
responses.append(
event.chain_result(
[
Comp.Plain("下一题来啦!\n干员立绘,请使用/fcc [干员名称] 进行猜测"),
Comp.Image.fromBytes(next_bytes),
]
)
)
else:
responses.append(event.plain_result("下一题获取失败,请管理员使用 /ccl 比赛开始 重试"))
else:
chain = [
Comp.At(qq=sender_id),
Comp.Plain(" 回答错误!"),
]
responses.append(event.chain_result(chain))
# 更新用户错误计数
await self.user_qna_repo.increment_wrong_count(
user_id=sender_id,
user_name=sender_name,
)
return responses, match_end_payload
async def iter_match_end_leaderboard(
self,
event: AstrMessageEvent,
match_end_payload: tuple[str, list],
) -> AsyncIterator[Any]:
"""Post-lock output for `/fcc` when a match ends (image preferred, text fallback)."""
ended_match_name, ended_top_participants = match_end_payload
async for result in generate_image_or_fallback(
event=event,
generate_image_func=lambda: self.renderer.generate_match_leaderboard_image(
ended_match_name,
ended_top_participants,
title=f"比赛「{ended_match_name}」已结束排行榜",
),
generate_text_func=lambda: generate_match_leaderboard_text(
ended_match_name,
ended_top_participants,
ended=True,
),
):
yield result
async def handle_fce(
self,
event: AstrMessageEvent,
*,
user_id: str,
sender_id: str,
is_group: bool,
group_id: str | None,
) -> list[Any]:
"""Core logic for `/fce` (expects room lock is held by caller)."""
responses: list[Any] = []
# 检查比赛模式下是否有权限
match = await self.match_repo.get_active_match(group_id) if is_group else None
if match and self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
responses.append(event.plain_result("❌ 比赛期间只有管理员可以强制结束"))
elif not has_active_game(self.player, user_id):
responses.append(event.plain_result("没有初始化房间,请使用/fc"))
else:
answer = self.player[user_id]["name"] # 获取答案
chain = [
Comp.At(qq=sender_id),
Comp.Plain(f" 游戏已结束,答案为: {answer}"),
]
responses.append(event.chain_result(chain))
responses.append(await self.send_original_image(user_id, event)) # 发送原图
return responses
async def handle_fct(
self,
event: AstrMessageEvent,
*,
user_id: str,
sender_id: str,
is_group: bool,
group_id: str | None,
) -> Any | None:
"""Core logic for `/fct` (expects room lock is held by caller)."""
response = None
# 检查比赛模式下是否有权限(仅群聊)
match = await self.match_repo.get_active_match(group_id) if is_group else None
if match and self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
response = event.plain_result("❌ 比赛期间只有管理员可以使用提示")
elif not has_active_game(self.player, user_id):
response = event.plain_result("没有初始化房间,请使用/fc")
else:
hint_text, _ = self._next_hint_text_and_advance(user_id)
response = event.plain_result(hint_text)
# 更新用户提示使用次数
await self.user_qna_repo.increment_tip_count(
user_id=event.get_sender_id(),
user_name=event.get_sender_name(),
)
return response
async def handle_fcw(
self,
event: AstrMessageEvent,
*,
user_id: str,
sender_id: str,
is_group: bool,
group_id: str | None,
) -> Any | None:
"""Core logic for `/fcw` (expects room lock is held by caller)."""
response = None
# 检查比赛模式下是否有权限(仅群聊)
match = await self.match_repo.get_active_match(group_id) if is_group else None
if match and self.admin_ids and sender_id not in [str(x) for x in self.admin_ids]:
response = event.plain_result("❌ 比赛期间只有管理员可以使用提示")
elif not has_active_game(self.player, user_id):
response = event.plain_result("没有初始化房间,请使用/fc")
else:
char_data = self.data.get(self.player[user_id]["name"], {})
logger.info(f"[fcw] player={self.player[user_id]}, char_data keys={list(char_data.keys()) if char_data else 'None'}")
# 获取职业及分支
profession = char_data.get("职业及分支", char_data.get("职业分支", "该干员没有该属性"))
# 星级转换为中文
star = char_data.get("星级", "")
star_map = {"1": "一星", "2": "二星", "3": "三星", "4": "四星", "5": "五星", "6": "六星"}
star_cn = star_map.get(str(star), star)
# 阵营
camp = char_data.get("阵营", char_data.get("所属阵营", "该干员没有该属性"))
# 构建提示消息
msg = "💡 一次性提示:\n"
msg += f"职业: {profession}\n"
msg += f"星级: {star_cn}\n"
msg += f"阵营: {camp}"
response = event.plain_result(msg)
# 设置提示计数为4跳过属性提示阶段
self.player[user_id]["fctn"] = 4
# 更新用户提示使用次数
await self.user_qna_repo.increment_tip_count(
user_id=sender_id,
user_name=event.get_sender_name(),
increment=3,
)
return response

View File

@@ -1,306 +0,0 @@
from collections import Counter
import os
from typing import Any, Callable, Iterable, Mapping, Optional
from astrbot.api.event import AstrMessageEvent
import astrbot.api.message_components as Comp
from pypinyin import lazy_pinyin, Style
from datetime import datetime
def calculate_char_coverage_set(correct_name: str, guess_text: str) -> float:
"""
计算guess_text包含correct_name中字符的比例去重版本
Args:
correct_name: 正确答案
guess_text: 用户猜测的答案
Returns:
float: 字符覆盖率 (0-1之间)
"""
if not correct_name:
return 0.0
# 转换为集合去重
correct_chars = set(correct_name)
guess_chars = set(guess_text)
# 计算匹配的字符数比例
matched_chars = correct_chars & guess_chars
coverage = len(matched_chars) / len(correct_chars)
return coverage
def calculate_char_coverage_counter(correct_name: str, guess_text: str) -> float:
"""
计算guess_text包含correct_name中字符的比例不去重版本
Args:
correct_name: 正确答案
guess_text: 用户猜测的答案
Returns:
float: 字符覆盖率 (0-1之间)
"""
if not correct_name:
return 0.0
# 使用Counter统计字符出现次数
correct_counter = Counter(correct_name)
guess_counter = Counter(guess_text)
# 计算总字符数和匹配的字符数
total_chars = sum(correct_counter.values())
matched_chars = 0
for char, count in correct_counter.items():
matched_chars += min(count, guess_counter.get(char, 0))
coverage = matched_chars / total_chars if total_chars > 0 else 0.0
return coverage
def generate_correct_leaderboard_text(users: Iterable[Any], summary: Optional[Mapping[str, Any]] = None) -> str:
"""生成正确量排行榜文本"""
users = list(users or [])
if not users:
return "📊 当前还没有用户的答题记录哦~"
message = "🏆 **正确量排行榜** 🏆\n\n"
for i, user in enumerate(users, 1):
if i == 1:
medal = "🥇"
elif i == 2:
medal = "🥈"
elif i == 3:
medal = "🥉"
else:
medal = f"{i}."
total_answers = getattr(user, "correct_count", 0) + getattr(user, "wrong_count", 0)
accuracy = (getattr(user, "correct_count", 0) / total_answers * 100) if total_answers > 0 else 0
message += f"{medal} {getattr(user, 'user_name', '-')}\n"
message += (
f" ✅ 正确: {getattr(user, 'correct_count', 0)} | ❌ 错误: {getattr(user, 'wrong_count', 0)} | 💡 提示: {getattr(user, 'tip_count', 0)}\n"
)
updated_at = getattr(user, "updated_at", None)
updated_str = updated_at.strftime("%Y-%m-%d") if hasattr(updated_at, "strftime") else "-"
message += f" 📈 准确率: {accuracy:.1f}% | 📅 最后更新: {updated_str}\n\n"
if summary:
message += "📊 **统计信息**\n"
message += f"总用户数: {summary.get('total_users', '-')} | 总答题数: {summary.get('total_questions', '-')}\n"
message += f"总正确数: {summary.get('total_correct', '-')} | 总错误数: {summary.get('total_wrong', '-')}\n"
message += f"平均正确数: {summary.get('avg_correct', 0):.1f}"
return message
def generate_wrong_leaderboard_text(users: Iterable[Any]) -> str:
"""生成错误个数排行榜文本"""
users = list(users or [])
if not users:
return "📊 当前还没有用户的答题记录哦~"
message = "💥 **错误个数排行榜** 💥\n\n"
for i, user in enumerate(users, 1):
if i == 1:
medal = "💣"
elif i == 2:
medal = "🧨"
elif i == 3:
medal = "🎆"
else:
medal = f"{i}."
total_answers = getattr(user, "correct_count", 0) + getattr(user, "wrong_count", 0)
error_rate = (getattr(user, "wrong_count", 0) / total_answers * 100) if total_answers > 0 else 0
message += f"{medal} {getattr(user, 'user_name', '-')}\n"
message += (
f" ❌ 错误: {getattr(user, 'wrong_count', 0)} | ✅ 正确: {getattr(user, 'correct_count', 0)} | 💡 提示: {getattr(user, 'tip_count', 0)}\n"
)
updated_at = getattr(user, "updated_at", None)
updated_str = updated_at.strftime("%Y-%m-%d") if hasattr(updated_at, "strftime") else "-"
message += f" 📉 错误率: {error_rate:.1f}% | 📅 最后更新: {updated_str}\n\n"
return message
def generate_hints_leaderboard_text(users: Iterable[Any]) -> str:
"""生成提示次数排行榜文本"""
users = list(users or [])
if not users:
return "📊 当前还没有用户的答题记录哦~"
message = "💡 **提示次数排行榜** 💡\n\n"
for i, user in enumerate(users, 1):
if i == 1:
medal = "🎯"
elif i == 2:
medal = "🔍"
elif i == 3:
medal = "🧩"
else:
medal = f"{i}."
total_answers = getattr(user, "correct_count", 0) + getattr(user, "wrong_count", 0)
tips_per_question = (getattr(user, "tip_count", 0) / total_answers) if total_answers > 0 else 0
message += f"{medal} {getattr(user, 'user_name', '-')}\n"
message += (
f" 💡 提示: {getattr(user, 'tip_count', 0)} | ✅ 正确: {getattr(user, 'correct_count', 0)} | ❌ 错误: {getattr(user, 'wrong_count', 0)}\n"
)
updated_at = getattr(user, "updated_at", None)
updated_str = updated_at.strftime("%Y-%m-%d") if hasattr(updated_at, "strftime") else "-"
message += f" 📊 提示频率: {tips_per_question:.2f}/题 | 📅 最后更新: {updated_str}\n\n"
return message
def generate_match_leaderboard_text(match_name: str, participants: Iterable[Any], ended: bool = False) -> str:
"""生成比赛排行榜文本(图片生成失败时的回退)"""
participants = list(participants or [])
if not participants:
status = "已结束" if ended else "排行榜"
return f"比赛「{match_name}{status}\n\n暂无参赛记录"
try:
participants.sort(key=lambda p: float(getattr(p, "score", 0.0) or 0.0), reverse=True)
except Exception:
pass
title = f"比赛「{match_name}」已结束\n排行榜" if ended else f"比赛「{match_name}」排行榜"
message = f"{title}\n----------------\n"
for i, p in enumerate(participants[:10], 1):
user_name = getattr(p, "user_name", "-")
correct = getattr(p, "correct_count", 0)
wrong = getattr(p, "wrong_count", 0)
try:
score_str = f"{float(getattr(p, 'score', 0.0) or 0.0):.2f}"
except Exception:
score_str = "-"
message += f"{i}. {user_name}: {correct}{wrong}{score_str}\n"
return message
def generate_user_profile_text(user_stats: Any, rank_info: Mapping[str, Any], honors=None, user_id: str | None = None) -> str:
"""生成用户个人信息文本"""
honors = list(honors or [])
title = getattr(user_stats, "user_name", None) if user_stats else None
title = title or (user_id or "未知用户")
message = f"👤 **用户信息 - {title}**\n\n"
if not user_stats:
message += "📊 **基础统计**\n"
message += "暂无答题记录\n"
else:
total_answers = getattr(user_stats, "correct_count", 0) + getattr(user_stats, "wrong_count", 0)
accuracy = (getattr(user_stats, "correct_count", 0) / total_answers * 100) if total_answers > 0 else 0
message += "📊 **基础统计**\n"
message += f"✅ 正确: {getattr(user_stats, 'correct_count', 0)}\n"
message += f"❌ 错误: {getattr(user_stats, 'wrong_count', 0)}\n"
message += f"💡 提示: {getattr(user_stats, 'tip_count', 0)}\n"
message += f"🎯 准确率: {accuracy:.1f}%\n"
message += f"📝 总答题数: {total_answers}\n\n"
if rank_info:
message += f"🏆 **排名信息** (共{rank_info.get('total_users', '?')}人)\n"
message += f"✅ 正确排名: 第{rank_info.get('correct_rank', '?')}\n"
message += f"❌ 错误排名: 第{rank_info.get('wrong_rank', '?')}\n"
message += f"💡 提示排名: 第{rank_info.get('tip_rank', '?')}\n\n"
created_at = getattr(user_stats, "created_at", None)
updated_at = getattr(user_stats, "updated_at", None)
created_str = created_at.strftime("%Y-%m-%d %H:%M") if hasattr(created_at, "strftime") else "-"
updated_str = updated_at.strftime("%Y-%m-%d %H:%M") if hasattr(updated_at, "strftime") else "-"
message += "📅 **时间信息**\n"
message += f"⏰ 注册时间: {created_str}\n"
message += f"🔄 最后更新: {updated_str}\n"
if honors:
message += "\n🏅 **比赛荣誉**\n"
for h in honors[:5]:
try:
score_str = f"{float(getattr(h, 'score', 0.0)):.1f}"
except Exception:
score_str = "-"
message += (
f"{getattr(h, 'medal', '')} {getattr(h, 'match_name', '-')}: "
f"{getattr(h, 'rank', '?')}名(✅{getattr(h, 'correct_count', 0)}/"
f"{getattr(h, 'wrong_count', 0)}S{score_str}\n"
)
else:
message += "\n暂无荣誉记录\n"
return message
async def generate_image_or_fallback(
event: AstrMessageEvent,
generate_image_func: Callable[..., Any],
generate_text_func: Callable[..., str],
*args,
**kwargs,
):
"""统一的图片生成和回退处理"""
try:
image_path = await generate_image_func(*args, **kwargs)
if image_path and os.path.exists(image_path):
yield event.chain_result([Comp.Image.fromFileSystem(image_path)])
return
text_message = generate_text_func(*args, **kwargs)
yield event.plain_result(f"图片生成失败,使用文本模式显示\n\n{text_message}")
except Exception as render_error:
text_message = generate_text_func(*args, **kwargs)
yield event.plain_result(f"图片生成失败,使用文本模式显示\n错误: {str(render_error)}\n\n{text_message}")
def parse_aliases(alias_str: str) -> dict[str, str]:
"""解析别名配置字符串为映射表:别名:正名,别名:正名"""
alias_map: dict[str, str] = {}
if not alias_str:
return alias_map
for pair in str(alias_str).split(","):
if ":" not in pair:
continue
alias, name = pair.split(":", 1)
alias = alias.strip()
name = name.strip()
if not alias or not name:
continue
alias_map[alias] = name
return alias_map
def resolve_alias(name: str, alias_map: Mapping[str, str]) -> str:
"""将别名解析为正名(若不存在则返回原值)"""
return (alias_map or {}).get(name, name)
def get_pinyin(text: str) -> str:
"""获取汉字的拼音(不带声调)"""
return "".join(lazy_pinyin(text, style=Style.NORMAL))
def check_homophone(correct: str, guess: str, enable_homophone: bool = False) -> bool:
"""检查两个字符串是否同音(基于拼音)"""
if not enable_homophone:
return False
return get_pinyin(correct) == get_pinyin(guess)
def check_daily_limit(user_id: str, daily_counter: dict, daily_limit: int) -> bool:
"""检查并更新每日计数器,返回是否允许继续游戏"""
today = datetime.now().date()
key = f"{user_id}_{today}"
count = daily_counter.get(key, 0)
if count >= daily_limit:
return False
daily_counter[key] = count + 1
return True
def has_active_game(player: Mapping[str, Any], user_id: str) -> bool:
"""检查用户是否有活跃游戏"""
data = (player or {}).get(user_id)
return bool(data and data.get("status") == "active")

View File

@@ -8,7 +8,6 @@ from __future__ import annotations
import sys
import tempfile
import textwrap
import types
from pathlib import Path
import pytest
@@ -21,34 +20,6 @@ from astrbot_sdk.runtime.loader import (
)
def _install_mrfzccl_optional_dependency_stubs(monkeypatch: pytest.MonkeyPatch) -> None:
"""为真实旧插件夹具补齐仓库测试环境里缺失的可选依赖。"""
pypinyin = types.ModuleType("pypinyin")
class _Style:
NORMAL = "normal"
def _lazy_pinyin(text, style=None):
return list(str(text or ""))
pypinyin.Style = _Style
pypinyin.lazy_pinyin = _lazy_pinyin
monkeypatch.setitem(sys.modules, "pypinyin", pypinyin)
html2image = types.ModuleType("html2image")
class _Html2Image:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def screenshot(self, *args, **kwargs):
return []
html2image.Html2Image = _Html2Image
monkeypatch.setitem(sys.modules, "html2image", html2image)
class TestLegacyPluginImports:
"""测试旧版 API 导入路径是否可用。"""
@@ -565,68 +536,6 @@ class TestRealTestPlugin:
if p in sys.path:
sys.path.remove(p)
def test_load_real_external_legacy_plugin_fixture(
self, monkeypatch: pytest.MonkeyPatch
):
"""测试仓库中的真实外部旧插件夹具。"""
project_root = Path(__file__).parent.parent
plugin_dir = project_root / "test_plugin" / "old" / "mrfzccl"
if not plugin_dir.exists():
pytest.skip("external legacy plugin fixture not found")
_install_mrfzccl_optional_dependency_stubs(monkeypatch)
spec = load_plugin_spec(plugin_dir)
paths_to_add = []
if str(plugin_dir) not in sys.path:
sys.path.insert(0, str(plugin_dir))
paths_to_add.append(str(plugin_dir))
src_new = project_root / "src-new"
if str(src_new) not in sys.path:
sys.path.insert(0, str(src_new))
paths_to_add.append(str(src_new))
try:
loaded = load_plugin(spec)
assert loaded.plugin.name == "astrbot_plugin_mrfzccl"
assert len(loaded.instances) == 1
assert len(loaded.handlers) >= 10
command_names = {
handler.descriptor.trigger.command
for handler in loaded.handlers
if isinstance(handler.descriptor.trigger, CommandTrigger)
}
assert {
"fc",
"fcc",
"fce",
"fct",
"fcw",
"ccl 排行榜",
"ccl 错误排行榜",
"ccl 提示排行榜",
} <= command_names
instance = loaded.instances[0]
assert Path(instance.storage_dir) == plugin_dir / "data"
assert instance.db_path == str((plugin_dir / "data" / "mrfzccl.db"))
assert instance.renderer.theme == "light"
finally:
synthetic_modules = [
name
for name in list(sys.modules)
if name.startswith("_astrbot_legacy_pkg_mrfzccl")
]
for module_name in synthetic_modules:
sys.modules.pop(module_name, None)
for p in paths_to_add:
if p in sys.path:
sys.path.remove(p)
if __name__ == "__main__":
pytest.main([__file__, "-v"])