Merge remote-tracking branch 'origin/main' into feature_250525/skill_card

# Conflicts:
#	kotonebot/kaa/game_ui/idols_overview.py
#	kotonebot/kaa/tasks/produce/produce.py
This commit is contained in:
WinterChimes 2025-06-29 21:07:19 +08:00
commit 90cf4e6896
63 changed files with 2467 additions and 504 deletions

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -68,6 +68,41 @@ TODO
> 建议**使用亲密度至少为 7 的偶像**进行培育,
> 因为琴音小助手暂时无法处理亲密度提升事件。
## 开源协议
kaa 本体及框架kotonebot 文件夹、相关辅助脚本tools 文件夹)使用 **GPLv3 协议**开源。kaa 开发工具kotonebot-devtool、启动器bootstrap 文件夹)以 **MIT 协议**开源。
kaa 的开发主要用到了以下开源项目:
* [GkmasObjectManager
](https://github.com/AllenHeartcore/GkmasObjectManager):用于提取游戏图像资源,以 GPLv3 协议开源。
* [gakumasu-diff](https://github.com/vertesan/gakumasu-diff):游戏数据。
## 免责声明
**请在使用本项目前仔细阅读以下内容。使用本脚本将带来包括但不限于账号被封禁的风险。**
### 总则
本项目(琴音小助手)是一个为游戏 **《学园偶像大师》(学園アイドルマスター)** 设计的自动操作脚本。本项目的创建目的仅为技术学习与研究,并非为了提供商业服务或鼓励不正当的游戏行为。
### 版权声明
本项目所使用的部分资源文件,包括但不限于图像、音频、模型等,其版权归属于其原始权利人。该游戏的开发商为 **QualiArts**,发行商为**万代南梦宫娱乐Bandai Namco Entertainment Inc.**。
1. **权利归属**:本项目中使用的所有相关游戏资源文件的版权、商标权及其他一切知识产权,均归 **QualiArts**、**万代南梦宫娱乐**或其相关权利方所有。
2. **非官方性质**:本项目为非官方、非商业性质的开源项目。本项目的开发者与 **QualiArts** 及 **万代南梦宫娱乐**没有任何形式的关联、合作或官方授权。
### 核心风险与责任限制
1. **账号封禁风险****您必须清楚地认识到,使用任何形式的第三方自动操作脚本(包括本项目)都有违反《学园偶像大师》的用户协议(利用規約)的潜在风险。游戏运营商有权对使用此类脚本的账号采取惩罚措施,包括但不限于临时或永久封禁账号。对于因使用本脚本而导致的任何账号损失(如封号、数据回滚等),项目作者概不负责。**
> ・对本服务的服务器等进行非法访问、窃取数据、使用使软件进行非法处理的程序、使用工具等获取信息或使用工具等不正当推进游戏的行为。
> ・本サービスのサーバー等への不正アクセス行為、データ窃取行為、ソフトウェアに不正な処理を行わせるプログラムを使用する行為、ツール等を使用して情報を取得する行為またはツール等を使用して不正にゲームを有利に進める行為
2. **使用限制**:本项目的全部内容**严禁用于任何商业用途或恶意破坏游戏平衡的行为**。任何将本项目用于此类活动的行为,均可能构成对版权方的侵权和对游戏运营商的违约,由此产生的一切法律责任由使用者自行承担。
3. **无担保与责任限制**:本项目按“原样”提供,不附带任何形式的明示或暗示担保,包括其功能的稳定性、准确性或持续可用性。对于因使用或无法使用本项目而导致的任何直接、间接、偶然、特殊或继发性损害(**包括但不限于账号封禁**),项目作者概不负责。
**继续下载、安装或使用本项目,即表示您已完全阅读、理解并同意承担以上所有风险和条款。如果您不同意,请立即停止使用并删除本项目的所有相关文件。**
## 开发
见 [DEVELOPMENT.md](./docs/DEVELOPMENT.md)

View File

@ -1,5 +1,42 @@
# 更新日志
## kaa
### v2025.6.23.0
脚本:
* [新增] 优化了培育开始的逻辑,修复若干 bug#86313ec
框架:
* [修复] 修复由于分离 AndroidDevice 方法导致的 typing 问题(#4d76e1a
* [重构] 将 Commandable 分离为 WindowsCommandable 与 AndroidCommandable#16a267d
* [重构] 将启动 remote_server 的逻辑移动到 kaa cli 中(#b8b5ba8
* [重构] 提取三个 adb-based 截图方法的工厂函数的共同部分(#bd57dc4
* [重构] 将创建设备的逻辑从 init_context 中移除(#f2599e6
* [重构] 重构 Device 与 Impl 的创建方式(#2fc9ad5
其他:
* [其他] 更新上游 submodules#810c341
### v2025.6.8.0
脚本:
* [新增] 新增支持自动禁用与恢复 Gakumasu Localify 汉化插件(#264dac2
* [修复] 修复外出事件中可用按钮数量小于 2 导致的下标越界问题(#2452c8c
* [修复] 尝试修复第一次领取饮料有几率卡住的问题(#7f2e588
框架:
* [新增] 新增全局暂停脚本执行功能(#a8e1f0d
其他:
* [其他] 新增开源协议与免责声明(#733aa6a
### v2025.5.23.3
脚本:
* [修复] 尝试修复行动页有时进入行动失效的问题(#5901771
界面:
* [修复] 修复 UI 中模拟器 Tab 初值不正确的问题(#5f5d99c
其他:
* [其他] 更新上游 submodule#cd6e128
### v2025.5.23.2
脚本:
* [修复] 将配置项 adb_emulator_name 默认值置为 None#f3ef360

Binary file not shown.

After

Width:  |  Height:  |  Size: 885 KiB

View File

@ -0,0 +1 @@
{"definitions":{"a0bd6a5f-784d-4f0a-9d66-10f4b80c8d3e":{"name":"Produce.LogoNia","displayName":"NIA LOGO (NEXT IDOL AUDITION)","type":"template","annotationId":"a0bd6a5f-784d-4f0a-9d66-10f4b80c8d3e","useHintRect":false},"48a458a9-b6cf-4199-850e-78f679f4f337":{"name":"Produce.PointNiaToHajime","displayName":"NIA 左侧翻页箭头","type":"hint-point","annotationId":"48a458a9-b6cf-4199-850e-78f679f4f337","useHintRect":false}},"annotations":[{"id":"a0bd6a5f-784d-4f0a-9d66-10f4b80c8d3e","type":"rect","data":{"x1":195,"y1":424,"x2":540,"y2":466}},{"id":"48a458a9-b6cf-4199-850e-78f679f4f337","type":"point","data":{"x":34,"y":596}}]}

View File

@ -1 +1 @@
{"definitions":{"12c5fd7c-0a6f-423c-bbfa-e88d19806bbe":{"name":"Produce.BoxModeButtons","displayName":"培育模式选择按钮","type":"hint-box","annotationId":"12c5fd7c-0a6f-423c-bbfa-e88d19806bbe","useHintRect":false}},"annotations":[{"id":"12c5fd7c-0a6f-423c-bbfa-e88d19806bbe","type":"rect","data":{"x1":7,"y1":818,"x2":713,"y2":996}}]}
{"definitions":{"6cd80be8-c9b3-4ba5-bf17-3ffc9b000743":{"name":"Produce.ButtonHajime0Regular","displayName":"","type":"template","annotationId":"6cd80be8-c9b3-4ba5-bf17-3ffc9b000743","useHintRect":false},"55f7db71-0a18-4b3d-b847-57959b8d2e32":{"name":"Produce.ButtonHajime0Pro","displayName":"","type":"template","annotationId":"55f7db71-0a18-4b3d-b847-57959b8d2e32","useHintRect":false}},"annotations":[{"id":"6cd80be8-c9b3-4ba5-bf17-3ffc9b000743","type":"rect","data":{"x1":145,"y1":859,"x2":314,"y2":960}},{"id":"55f7db71-0a18-4b3d-b847-57959b8d2e32","type":"rect","data":{"x1":434,"y1":857,"x2":545,"y2":961}}]}

Binary file not shown.

After

Width:  |  Height:  |  Size: 791 KiB

View File

@ -0,0 +1 @@
{"definitions":{"3b473fe6-e147-477f-b088-9b8fb042a4f6":{"name":"Produce.ButtonHajime1Regular","displayName":"","type":"template","annotationId":"3b473fe6-e147-477f-b088-9b8fb042a4f6","useHintRect":false},"2ededcf5-1d80-4e2a-9c83-2a31998331ce":{"name":"Produce.ButtonHajime1Pro","displayName":"","type":"template","annotationId":"2ededcf5-1d80-4e2a-9c83-2a31998331ce","useHintRect":false},"24e99232-9434-457f-a9a0-69dd7ecf675f":{"name":"Produce.ButtonHajime1Master","displayName":"","type":"template","annotationId":"24e99232-9434-457f-a9a0-69dd7ecf675f","useHintRect":false},"aca9e953-1955-46eb-920c-77b1750bcb34":{"name":"Produce.PointHajimeToNia","displayName":"Hajime 右侧翻页箭头","type":"hint-point","annotationId":"aca9e953-1955-46eb-920c-77b1750bcb34","useHintRect":false},"e6b45405-cd9f-4c6e-a9f1-6ec953747c65":{"name":"Produce.LogoHajime","displayName":"Hajime LOGO 定期公演","type":"template","annotationId":"e6b45405-cd9f-4c6e-a9f1-6ec953747c65","useHintRect":false}},"annotations":[{"id":"3b473fe6-e147-477f-b088-9b8fb042a4f6","type":"rect","data":{"x1":65,"y1":867,"x2":214,"y2":950}},{"id":"2ededcf5-1d80-4e2a-9c83-2a31998331ce","type":"rect","data":{"x1":307,"y1":869,"x2":421,"y2":952}},{"id":"24e99232-9434-457f-a9a0-69dd7ecf675f","type":"rect","data":{"x1":521,"y1":863,"x2":657,"y2":951}},{"id":"aca9e953-1955-46eb-920c-77b1750bcb34","type":"point","data":{"x":680,"y":592}},{"id":"e6b45405-cd9f-4c6e-a9f1-6ec953747c65","type":"rect","data":{"x1":274,"y1":169,"x2":443,"y2":212}}]}

View File

@ -1 +1 @@
{"definitions":{"e88c9ad1-ec37-4fcd-b086-862e1e7ce8fd":{"name":"Produce.ButtonPIdolOverview","displayName":"Pアイドルー覧 P偶像列表展示","type":"template","annotationId":"e88c9ad1-ec37-4fcd-b086-862e1e7ce8fd","useHintRect":false},"44ba8515-4a60-42c9-8878-b42e4e34ee15":{"name":"Produce.TextStepIndicator1","displayName":"1. アイドル選択","type":"template","annotationId":"44ba8515-4a60-42c9-8878-b42e4e34ee15","useHintRect":false}},"annotations":[{"id":"e88c9ad1-ec37-4fcd-b086-862e1e7ce8fd","type":"rect","data":{"x1":49,"y1":736,"x2":185,"y2":759},"tip":"Pアイドルー覧 P偶像列表展示"},{"id":"44ba8515-4a60-42c9-8878-b42e4e34ee15","type":"rect","data":{"x1":18,"y1":32,"x2":168,"y2":66}}]}
{"definitions":{"e88c9ad1-ec37-4fcd-b086-862e1e7ce8fd":{"name":"Produce.ButtonPIdolOverview","displayName":"Pアイドルー覧 P偶像列表展示","type":"template","annotationId":"e88c9ad1-ec37-4fcd-b086-862e1e7ce8fd","useHintRect":false},"44ba8515-4a60-42c9-8878-b42e4e34ee15":{"name":"Produce.TextStepIndicator1","displayName":"1. アイドル選択","type":"template","annotationId":"44ba8515-4a60-42c9-8878-b42e4e34ee15","useHintRect":false},"34606d7d-52c8-4cd1-b7f4-b31032f1fb70":{"name":"Produce.BoxSelectedIdol","displayName":"当前选中的偶像","type":"hint-box","annotationId":"34606d7d-52c8-4cd1-b7f4-b31032f1fb70","useHintRect":false,"description":"偶像选择界面当前选中的偶像"}},"annotations":[{"id":"e88c9ad1-ec37-4fcd-b086-862e1e7ce8fd","type":"rect","data":{"x1":49,"y1":736,"x2":185,"y2":759},"tip":"Pアイドルー覧 P偶像列表展示"},{"id":"44ba8515-4a60-42c9-8878-b42e4e34ee15","type":"rect","data":{"x1":18,"y1":32,"x2":168,"y2":66}},{"id":"34606d7d-52c8-4cd1-b7f4-b31032f1fb70","type":"rect","data":{"x1":149,"y1":783,"x2":317,"y2":1006}}]}

Binary file not shown.

After

Width:  |  Height:  |  Size: 934 KiB

View File

@ -0,0 +1 @@
{"definitions":{"d3424d31-0502-4623-996e-f0194e5085ce":{"name":"Produce.EmptySupportCardSlot","displayName":"空支援卡槽位","type":"template","annotationId":"d3424d31-0502-4623-996e-f0194e5085ce","useHintRect":false}},"annotations":[{"id":"d3424d31-0502-4623-996e-f0194e5085ce","type":"rect","data":{"x1":481,"y1":844,"x2":692,"y2":962}}]}

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 KiB

View File

@ -0,0 +1 @@
{"definitions":{"f5c16d2f-ebc5-4617-9b96-971696af7c52":{"name":"Produce.TextAutoSet","displayName":"おまかせ編成","type":"template","annotationId":"f5c16d2f-ebc5-4617-9b96-971696af7c52","useHintRect":false}},"annotations":[{"id":"f5c16d2f-ebc5-4617-9b96-971696af7c52","type":"rect","data":{"x1":56,"y1":919,"x2":257,"y2":957}}]}

Binary file not shown.

After

Width:  |  Height:  |  Size: 499 KiB

View File

@ -0,0 +1 @@
{"definitions":{"74ec3510-583d-4a76-ac69-38480fbf1387":{"name":"Produce.TextRentAvailable","displayName":"レンタル可能","type":"template","annotationId":"74ec3510-583d-4a76-ac69-38480fbf1387","useHintRect":false}},"annotations":[{"id":"74ec3510-583d-4a76-ac69-38480fbf1387","type":"rect","data":{"x1":53,"y1":848,"x2":256,"y2":887}}]}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -32,7 +32,7 @@ class RunStatus:
callstack: list[Task | Action] = field(default_factory=list)
def interrupt(self):
vars.interrupted.set()
vars.flow.request_interrupt()
# Modified from https://stackoverflow.com/questions/70982565/how-do-i-make-an-event-listener-with-decorators-in-python
Params = ParamSpec('Params')
@ -158,7 +158,7 @@ class KotoneBot:
d = self._on_create_device()
init_context(config_path=self.config_path, config_type=self.config_type, target_device=d)
self._on_after_init_context()
vars.interrupted.clear()
vars.flow.clear_interrupt()
if by_priority:
tasks = sorted(tasks, key=lambda x: x.priority, reverse=True)
@ -180,7 +180,7 @@ class KotoneBot:
logger.exception('Keyboard interrupt detected.')
for task1 in tasks[tasks.index(task):]:
self.events.task_status_changed.trigger(task1, 'cancelled')
vars.interrupted.clear()
vars.flow.clear_interrupt()
break
# 其他错误
except Exception as e:

View File

@ -3,6 +3,7 @@ import re
import time
import logging
import warnings
import threading
from datetime import datetime
from threading import Event
from typing import (
@ -24,7 +25,8 @@ from typing_extensions import deprecated
import cv2
from cv2.typing import MatLike
from kotonebot.client.device import Device
from kotonebot.client.device import Device, AndroidDevice, WindowsDevice
from kotonebot.backend.flow_controller import FlowController
import kotonebot.backend.image as raw_image
from kotonebot.backend.image import (
TemplateMatchResult,
@ -44,12 +46,12 @@ from kotonebot.backend.color import (
from kotonebot.backend.ocr import (
Ocr, OcrResult, OcrResultList, jp, en, StringMatchFunction
)
from kotonebot.client.factory import create_device
from kotonebot.client.registration import AdbBasedImpl, create_device
from kotonebot.config.manager import load_config, save_config
from kotonebot.config.base_config import UserConfig
from kotonebot.backend.core import Image, HintBox
from kotonebot.errors import KotonebotWarning
from kotonebot.client.factory import DeviceImpl
from kotonebot.client import DeviceImpl
from kotonebot.backend.preprocessor import PreprocessorProtocol
from kotonebot.primitives import Rect
@ -126,8 +128,7 @@ def interruptible(func: Callable[P, T]) -> Callable[P, T]:
"""
def _decorator(*args: P.args, **kwargs: P.kwargs) -> T:
global vars
if vars.interrupted.is_set():
raise KeyboardInterrupt("User requested interrupt.")
vars.flow.check()
return func(*args, **kwargs)
return _decorator
@ -145,15 +146,13 @@ def interruptible_class(cls: Type[T]) -> Type[T]:
def sleep(seconds: float, /):
"""
可中断sleep 函数
可中断和可暂停sleep 函数
建议使用本函数代替 `time.sleep()`
这样能以最快速度响应用户请求中断
这样能以最快速度响应用户请求中断和暂停
"""
global vars
vars.interrupted.wait(timeout=seconds)
if vars.interrupted.is_set():
raise KeyboardInterrupt("User requested interrupt.")
vars.flow.sleep(seconds)
def warn_manual_screenshot_mode(name: str, alternative: str):
"""
@ -175,8 +174,8 @@ def is_manual_screenshot_mode() -> bool:
class ContextGlobalVars:
def __init__(self):
self.__vars = dict[str, Any]()
self.interrupted: Event = Event()
"""用户请求中断事件"""
self.flow: FlowController = FlowController()
"""流程控制器,负责停止、暂停、恢复等操作"""
def __getitem__(self, key: str) -> Any:
return self.__vars[key]
@ -198,6 +197,17 @@ class ContextGlobalVars:
def clear(self):
self.__vars.clear()
self.flow.reset() # 重置流程控制器
def check_flow_control():
"""
统一的流程控制检查函数
检查用户是否请求中断或暂停如果是则相应处理
- 如果请求中断抛出 KeyboardInterrupt 异常
- 如果请求暂停等待直到恢复
"""
vars.flow.check()
class ContextStackVars:
stack: list['ContextStackVars'] = []
@ -707,15 +717,17 @@ class Forwarded:
raise ValueError(f"Forwarded object {self._FORWARD_name} called before initialization.")
setattr(self._FORWARD_getter(), name, value)
# HACK: 这应该要有个更好的实现方式
class ContextDevice(Device):
def __init__(self, device: Device):
T_Device = TypeVar('T_Device', bound=Device)
class ContextDevice(Generic[T_Device], Device):
def __init__(self, device: T_Device):
self._device = device
def screenshot(self, *, force: bool = False):
"""
截图返回截图数据同时更新当前上下文的截图数据
"""
check_flow_control()
global next_wait, last_screenshot_time, next_wait_time
current = ContextStackVars.ensure_current()
if force:
@ -735,26 +747,42 @@ class ContextDevice(Device):
current._screenshot = img
return img
def __getattribute__(self, name: str) -> Any:
if name in ['_device', 'screenshot']:
def __getattribute__(self, name: str):
if name in ['_device', 'screenshot', 'of_android', 'of_windows']:
return object.__getattribute__(self, name)
else:
return getattr(self._device, name)
def __setattr__(self, name: str, value: Any):
if name in ['_device', 'screenshot']:
if name in ['_device', 'screenshot', 'of_android', 'of_windows']:
return object.__setattr__(self, name, value)
else:
return setattr(self._device, name, value)
def of_android(self) -> 'ContextDevice | AndroidDevice':
"""
确保此 ContextDevice 底层为 Android 平台
同时通过返回的对象可以调用 Android 平台特有的方法
"""
if not isinstance(self._device, AndroidDevice):
raise ValueError("Device is not AndroidDevice")
return self
def of_windows(self) -> 'ContextDevice | WindowsDevice':
"""
确保此 ContextDevice 底层为 Windows 平台
同时通过返回的对象可以调用 Windows 平台特有的方法
"""
if not isinstance(self._device, WindowsDevice):
raise ValueError("Device is not WindowsDevice")
return self
class Context(Generic[T]):
def __init__(
self,
config_path: str,
config_type: Type[T],
screenshot_impl: Optional[DeviceImpl] = None,
device: Optional[Device] = None
device: Device
):
self.__ocr = ContextOcr(self)
self.__image = ContextImage(self)
@ -762,14 +790,7 @@ class Context(Generic[T]):
self.__vars = ContextGlobalVars()
self.__debug = ContextDebug(self)
self.__config = ContextConfig[T](self, config_path, config_type)
ip = self.config.current.backend.adb_ip
port = self.config.current.backend.adb_port
# TODO: 处理链接失败情况
if screenshot_impl is None:
screenshot_impl = self.config.current.backend.screenshot_impl
logger.info(f'Using "{screenshot_impl}" as screenshot implementation')
self.__device = ContextDevice(device or create_device(f'{ip}:{port}', screenshot_impl))
self.__device = ContextDevice(device)
def inject(
self,
@ -880,8 +901,7 @@ def init_context(
config_path: str = 'config.json',
config_type: Type[T] = dict[str, Any],
force: bool = False,
screenshot_impl: Optional[DeviceImpl] = None,
target_device: Device | None = None,
target_device: Device,
):
"""
初始化 Context 模块
@ -892,8 +912,6 @@ def init_context(
默认为 `dict[str, Any]`即普通的 JSON 数据不包含任何类型信息
:param force: 是否强制重新初始化
若为 `True`则忽略已存在的 Context 实例并重新创建一个新的实例
:param screenshot_impl: 截图实现
若为 `None`则使用默认配置文件中指定的截图实现
:param target_device: 目标设备
"""
global _c, device, ocr, image, color, vars, debug, config
@ -902,8 +920,7 @@ def init_context(
_c = Context(
config_path=config_path,
config_type=config_type,
screenshot_impl=screenshot_impl,
device=target_device
device=target_device,
)
device._FORWARD_getter = lambda: _c.device # type: ignore
ocr._FORWARD_getter = lambda: _c.ocr # type: ignore
@ -950,5 +967,4 @@ def manual_context(screenshot_mode: ScreenshotMode = 'auto') -> ManualContextMan
默认情况下Context* 类仅允许在 @task/@action 函数中使用
如果想要在其他地方使用使用此函数手动创建一个上下文
"""
return ManualContextManager(screenshot_mode)
return ManualContextManager(screenshot_mode)

View File

@ -115,7 +115,7 @@ async def run_code(request: RunCodeRequest):
except KeyboardInterrupt as e:
result = {"status": "error", "result": stdout.getvalue(), "message": str(e), "traceback": traceback.format_exc()}
finally:
context_vars.interrupted.clear()
context_vars.flow.clear_interrupt()
event.set()
threading.Thread(target=_runner, daemon=True).start()
await event.wait()
@ -124,8 +124,8 @@ async def run_code(request: RunCodeRequest):
@app.get("/api/code/stop")
async def stop_code():
from kotonebot.backend.context import vars
vars.interrupted.set()
while vars.interrupted.is_set():
vars.flow.request_interrupt()
while vars.flow.is_interrupted:
await asyncio.sleep(0.1)
return {"status": "ok"}
@ -216,8 +216,6 @@ def wait_message_all_done():
threading.Thread(target=_wait, daemon=True).start()
if __name__ == "__main__":
from kotonebot.backend.context import init_context
init_context()
debug_vars.debug.hide_server_log = False
process = subprocess.Popen(["pylsp", "--port", "5479", "--ws"])
print("LSP started. PID=", process.pid)

View File

@ -328,20 +328,4 @@ class SimpleDispatcher:
self.result = self.timeout_result
break
device.screenshot()
return self.result
if __name__ == '__main__':
from .context.task_action import action
from .context import init_context
init_context()
@action('inner', dispatcher=True)
def inner(ctx: DispatcherContext):
print('inner')
ctx.finish()
@action('test', dispatcher=True)
def test(ctx: DispatcherContext):
print('test')
inner()
ctx.finish()
test()
return self.result

View File

@ -0,0 +1,195 @@
import time
import logging
import threading
from typing import Literal
logger = logging.getLogger(__name__)
class FlowController:
"""
一个用于控制任务执行流程如停止暂停恢复的类
这个类是线程安全的提供了以下功能
* 停止任务执行通过中断信号
* 暂停/恢复任务执行
* 可中断和可暂停的 sleep 功能
* 流程状态检查
使用方法::
controller = FlowController()
# 在任务的关键路径上调用检查
controller.check()
# 使用可控制的 sleep
controller.sleep(1.0)
# 外部控制
controller.request_pause() # 暂停
controller.request_resume() # 恢复
controller.request_stop() # 停止
"""
def __init__(self):
self.interrupt_event: threading.Event = threading.Event()
"""中断事件,用于停止任务"""
self.paused: bool = False
"""暂停标志"""
self.pause_condition: threading.Condition = threading.Condition()
"""暂停条件变量,用于线程间同步"""
def check(self) -> None:
"""
检查当前流程状态
如果收到停止请求则抛出 KeyboardInterrupt 异常
如果收到暂停请求则阻塞直到恢复
这是核心的检查点方法应在任务的关键路径上如循环或等待前调用
:raises KeyboardInterrupt: 当收到停止请求时
"""
# 优先检查中断信号
if self.interrupt_event.is_set():
raise KeyboardInterrupt("User requested interrupt.")
# 检查暂停状态
with self.pause_condition:
while self.paused:
self.pause_condition.wait()
def sleep(self, seconds: float) -> None:
"""
一个可被中断和暂停的 sleep 方法
与标准的 time.sleep() 不同这个方法会响应停止和暂停请求
在暂停状态下计时器会暂停恢复后继续计时
:param seconds: 睡眠时间
:raises KeyboardInterrupt: 当收到停止请求时
"""
with self.pause_condition:
end_time = time.time() + seconds
while True:
self.check() # 每次循环都检查状态
remaining = end_time - time.time()
if remaining <= 0:
break
# 等待指定时间或直到被唤醒
self.pause_condition.wait(timeout=remaining)
# 结束后再次检查状态
self.check()
def request_interrupt(self) -> None:
"""
请求停止任务
设置中断信号所有正在执行的任务将在下一个检查点停止
停止的优先级高于暂停
"""
logger.info('Interrupt requested.')
self.interrupt_event.set()
def request_pause(self) -> None:
"""
请求暂停任务
设置暂停标志所有正在执行的任务将在下一个检查点暂停
如果任务已经暂停此操作无效果
"""
with self.pause_condition:
if not self.paused:
logger.info('Pause requested.')
self.paused = True
def request_resume(self) -> None:
"""
请求恢复任务
清除暂停标志并通知所有等待的线程恢复执行
如果任务没有暂停此操作无效果
"""
with self.pause_condition:
if self.paused:
logger.info('Resume requested.')
self.paused = False
self.pause_condition.notify_all()
def toggle_pause(self) -> bool:
"""
切换暂停/恢复状态
:returns: 操作后的暂停状态True 表示已暂停False 表示已恢复
"""
with self.pause_condition:
logger.info('Pause toggled.')
if self.paused:
self.paused = False
self.pause_condition.notify_all()
return False
else:
self.paused = True
return True
def clear_interrupt(self) -> None:
"""
清除中断信号
用于任务正常结束或重启时重置状态
通常在开始新任务前调用
"""
self.interrupt_event.clear()
logger.info('Interrupt cleared.')
def reset(self) -> None:
"""
重置流程控制器到初始状态
清除所有信号和状态相当于重新创建一个新的控制器
"""
self.interrupt_event.clear()
with self.pause_condition:
if self.paused:
self.paused = False
self.pause_condition.notify_all()
logger.info('FlowController reset.')
@property
def is_interrupted(self) -> bool:
"""
检查是否收到中断请求
:returns: True 表示已收到中断请求
"""
return self.interrupt_event.is_set()
@property
def is_paused(self) -> bool:
"""
检查是否处于暂停状态
:returns: True 表示当前处于暂停状态
"""
return self.paused
@property
def status(self) -> Literal['running', 'paused', 'interrupted']:
"""
获取当前状态的字符串描述
:returns: 状态描述可能的值'running', 'paused', 'interrupted'
"""
if self.is_interrupted:
return 'interrupted'
elif self.is_paused:
return 'paused'
else:
return 'running'
def __repr__(self) -> str:
return f"FlowController(status='{self.status}')"

277
kotonebot/backend/loop.py Normal file
View File

@ -0,0 +1,277 @@
import time
from functools import lru_cache, partial
from typing import Callable, Any, overload, Literal, Generic, TypeVar, cast, get_args, get_origin
from cv2.typing import MatLike
from kotonebot.util import Interval
from kotonebot import device, image, ocr
from kotonebot.backend.core import Image
from kotonebot.backend.ocr import TextComparator
from kotonebot.client.protocol import ClickableObjectProtocol
class LoopAction:
def __init__(self, loop: 'Loop', func: Callable[[], ClickableObjectProtocol | None]):
self.loop = loop
self.func = func
self.result: ClickableObjectProtocol | None = None
@property
def found(self):
"""
是否找到结果若父 Loop 未在运行中则返回 False
"""
if not self.loop.running:
return False
return bool(self.result)
def __bool__(self):
return self.found
def reset(self):
"""
重置 LoopAction以复用此对象
"""
self.result = None
def do(self):
"""
执行 LoopAction
:return: 执行结果
"""
if not self.loop.running:
return
if self.loop.found_anything:
# 本轮循环已执行任意操作,因此不需要再继续检测
return
self.result = self.func()
if self.result:
self.loop.found_anything = True
def click(self, *, at: tuple[int, int] | None = None):
"""
点击寻找结果若结果为空会跳过执行
:return:
"""
if self.result:
if at is not None:
device.click(*at)
else:
device.click(self.result)
def call(self, func: Callable[[ClickableObjectProtocol], Any]):
pass
class Loop:
def __init__(
self,
*,
timeout: float = 300,
interval: float = 0.3,
auto_screenshot: bool = True
):
self.running = True
self.found_anything = False
self.auto_screenshot = auto_screenshot
"""
是否在每次循环开始时Loop.tick() 被调用时截图
"""
self.__last_loop: float = -1
self.__interval = Interval(interval)
self.screenshot: MatLike | None = None
"""上次截图时的图像数据。"""
def __iter__(self):
self.__interval.reset()
return self
def __next__(self):
if not self.running:
raise StopIteration
self.found_anything = False
self.__last_loop = time.time()
return self.tick()
def tick(self):
self.__interval.wait()
if self.auto_screenshot:
self.screenshot = device.screenshot()
self.__last_loop = time.time()
self.found_anything = False
return self
def exit(self):
"""
结束循环
"""
self.running = False
@overload
def when(self, condition: Image) -> LoopAction:
...
@overload
def when(self, condition: TextComparator) -> LoopAction:
...
def when(self, condition: Any):
"""
判断某个条件是否成立
:param condition:
:return:
"""
if isinstance(condition, Image):
func = partial(image.find, condition)
elif isinstance(condition, TextComparator):
func = partial(ocr.find, condition)
else:
raise ValueError('Invalid condition type.')
la = LoopAction(self, func)
la.reset()
la.do()
return la
def until(self, condition: Any):
"""
当满足指定条件时结束循环
等价于 ``loop.when(...).call(lambda _: loop.exit())``
"""
return self.when(condition).call(lambda _: self.exit())
def click_if(self, condition: Any, *, at: tuple[int, int] | None = None):
"""
检测指定对象是否出现若出现点击该对象或指定位置
``click_if()`` 等价于 ``loop.when(...).click(...)``
:param condition: 检测目标
:param at: 点击位置若为 None表示点击找到的目标
"""
return self.when(condition).click(at=at)
StateType = TypeVar('StateType')
class StatedLoop(Loop, Generic[StateType]):
def __init__(
self,
states: list[Any] | None = None,
initial_state: StateType | None = None,
*,
timeout: float = 300,
interval: float = 0.3,
auto_screenshot: bool = True
):
self.__tmp_states = states
self.__tmp_initial_state = initial_state
self.state: StateType
super().__init__(timeout=timeout, interval=interval, auto_screenshot=auto_screenshot)
def __iter__(self):
# __retrive_state_values() 只能在非 __init__ 中调用
self.__retrive_state_values()
return super().__iter__()
def __retrive_state_values(self):
# HACK: __orig_class__ 是 undocumented 属性
if not hasattr(self, '__orig_class__'):
# 如果 Foo 不是以参数化泛型的方式实例化的,可能没有 __orig_class__
if self.state is None:
raise ValueError('Either specify `states` or use StatedLoop[Literal[...]] syntax.')
else:
generic_type_args = get_args(self.__orig_class__) # type: ignore
if len(generic_type_args) != 1:
raise ValueError('StatedLoop must have exactly one generic type argument.')
state_values = get_args(generic_type_args[0])
if not state_values:
raise ValueError('StatedLoop must have at least one state value.')
self.states = cast(tuple[StateType, ...], state_values)
self.state = self.__tmp_initial_state or self.states[0]
return state_values
def StatedLoop2(states: StateType) -> StatedLoop[StateType]:
state_values = get_args(states)
return cast(StatedLoop[StateType], Loop())
if __name__ == '__main__':
from kotonebot.kaa.tasks import R
from kotonebot.backend.ocr import contains
from kotonebot.backend.context import manual_context, init_context
# T = TypeVar('T')
# class Foo(Generic[T]):
# def get_literal_params(self) -> list | None:
# """
# 尝试获取泛型参数 T (如果它是 Literal 类型) 的参数列表。
# """
# # self.__orig_class__ 会是 Foo 的具体参数化类型,
# # 例如 Foo[Literal['p0', 'p1', 'p2', 'p3', 'ap']]
# if not hasattr(self, '__orig_class__'):
# # 如果 Foo 不是以参数化泛型的方式实例化的,可能没有 __orig_class__
# return None
#
# # generic_type_args 是传递给 Foo 的类型参数元组
# # 例如 (Literal['p0', 'p1', 'p2', 'p3', 'ap'],)
# generic_type_args = get_args(self.__orig_class__)
#
# if not generic_type_args:
# # Foo 没有类型参数
# return None
#
# # T_type 是 Foo 的第一个类型参数
# # 例如 Literal['p0', 'p1', 'p2', 'p3', 'ap']
# t_type = generic_type_args[0]
#
# # 检查 T_type 是否是 Literal 类型
# if get_origin(t_type) is Literal:
# # literal_args 是 Literal 类型的参数元组
# # 例如 ('p0', 'p1', 'p2', 'p3', 'ap')
# literal_args = get_args(t_type)
# return list(literal_args)
# else:
# # T 不是 Literal 类型
# return None
# f = Foo[Literal['p0', 'p1', 'p2', 'p3', 'ap']]()
# values = f.get_literal_params()
# 1
from typing_extensions import reveal_type
slp = StatedLoop[Literal['p0', 'p1', 'p2', 'p3', 'ap']]()
for l in slp:
reveal_type(l.states)
# init_context()
# manual_context().begin()
# for l in Loop():
# l.when(R.Produce.ButtonUse).click()
# l.when(R.Produce.ButtonRefillAP).click()
# l.when(contains("123")).click()
# l.click_if(contains("!23"), at=(1, 2))
# State = Literal['p0', 'p1', 'p2', 'p3', 'ap']
# for sl in StatedLoop[State]():
# match sl.state:
# case 'p0':
# sl.click_if(R.Produce.ButtonProduce)
# sl.click_if(contains('master'))
# sl.when(R.Produce.ButtonPIdolOverview).goto('p1')
# # AP 不足
# sl.when(R.Produce.TextAPInsufficient).goto('ap')
# case 'ap':
# pass
# # p1: 选择偶像
# case 'p1':
# sl.call(lambda _: select_idol(idol_skin_id), once=True)
# sl.when(R.Produce.TextAnotherIdolAvailableDialog).call(dialog.no)
# sl.click_if(R.Common.ButtonNextNoIcon)
# sl.until(R.Produce.TextStepIndicator2).goto('p2')
# case 'p2':
# sl.when(contains("123")).click()
# case 'p3':
# sl.click_if(contains("!23"), at=(1, 2))
# case _:
# assert_never(sl.state)

View File

@ -1,5 +1,8 @@
from .device import Device
from .factory import create_device, DeviceImpl
from .registration import create_device, DeviceImpl
# 确保所有实现都被注册
from . import implements # noqa: F401
__all__ = [
'Device',

View File

@ -11,7 +11,7 @@ from adbutils._device import AdbDevice as AdbUtilsDevice
from ..backend.debug import result
from kotonebot.backend.core import HintBox
from kotonebot.primitives import Rect, Point, is_point
from .protocol import ClickableObjectProtocol, Commandable, Touchable, Screenshotable
from .protocol import ClickableObjectProtocol, Commandable, Touchable, Screenshotable, AndroidCommandable, WindowsCommandable
logger = logging.getLogger(__name__)
@ -71,7 +71,6 @@ class Device:
横屏时为 'landscape'竖屏时为 'portrait'
"""
self._command: Commandable
self._touch: Touchable
self._screenshot: Screenshotable
@ -90,12 +89,6 @@ class Device:
def adb(self, value: AdbUtilsDevice) -> None:
self._adb = value
def launch_app(self, package_name: str) -> None:
"""
根据包名启动 app
"""
self._command.launch_app(package_name)
@overload
def click(self) -> None:
"""
@ -306,17 +299,6 @@ class Device:
"""
return self._screenshot.screen_size
def current_package(self) -> str | None:
"""
获取前台 APP 的包名
:return: 前台 APP 的包名如果获取失败则返回 None
:exception: 如果设备不支持此功能则抛出 NotImplementedError
"""
ret = self._command.current_package()
logger.debug("current_package: %s", ret)
return ret
def detect_orientation(self) -> Literal['portrait', 'landscape'] | None:
"""
检测当前设备方向并设置 `self.orientation` 属性
@ -330,10 +312,30 @@ class AndroidDevice(Device):
def __init__(self, adb_connection: AdbUtilsDevice | None = None) -> None:
super().__init__('android')
self._adb: AdbUtilsDevice | None = adb_connection
self.commands: AndroidCommandable
def current_package(self) -> str | None:
"""
获取前台 APP 的包名
:return: 前台 APP 的包名如果获取失败则返回 None
:exception: 如果设备不支持此功能则抛出 NotImplementedError
"""
ret = self.commands.current_package()
logger.debug("current_package: %s", ret)
return ret
def launch_app(self, package_name: str) -> None:
"""
根据包名启动 app
"""
self.commands.launch_app(package_name)
class WindowsDevice(Device):
def __init__(self) -> None:
super().__init__('windows')
self.commands: WindowsCommandable
if __name__ == "__main__":
@ -346,10 +348,10 @@ if __name__ == "__main__":
d = adb.device_list()[-1]
d.shell("dumpsys activity top | grep ACTIVITY | tail -n 1")
dd = AndroidDevice(d)
adb_imp = AdbRawImpl(dd)
dd._command = adb_imp
adb_imp = AdbRawImpl(d)
dd._touch = adb_imp
dd._screenshot = adb_imp
dd.commands = adb_imp
# dd._screenshot = MinicapScreenshotImpl(dd)
# dd._screenshot = UiAutomator2Impl(dd)

View File

@ -1,92 +0,0 @@
import logging
from typing import Literal
from .implements.adb import AdbImpl
from .implements.adb_raw import AdbRawImpl
from .implements.windows import WindowsImpl
from .implements.remote_windows import RemoteWindowsImpl
from .implements.uiautomator2 import UiAutomator2Impl
from .device import Device, AndroidDevice, WindowsDevice
from adbutils import adb
DeviceImpl = Literal['adb', 'adb_raw', 'uiautomator2', 'windows', 'remote_windows']
logger = logging.getLogger(__name__)
def create_device(
addr: str,
impl: DeviceImpl,
*,
connect: bool = True,
disconnect: bool = True,
device_serial: str | None = None,
timeout: float = 180,
) -> Device:
"""
根据指定的实现方式创建 Device 实例
:param addr: 设备地址 `127.0.0.1:5555`
仅当通过无线方式连接 Android 设备或者使用 `remote_windows` 时有效
:param impl: 实现方式
:param connect: 是否在创建时连接设备默认为 True
仅对 ADB-based 的实现方式有效
:param disconnect: 是否在连接前先断开设备默认为 True
仅对 ADB-based 的实现方式有效
:param device_serial: 设备序列号默认为 None
若为非 None则当存在多个设备时通过该值判断是否为目标设备
仅对 ADB-based 的实现方式有效
:param timeout: 连接超时时间默认为 180
仅对 ADB-based 的实现方式有效
"""
if impl in ['adb', 'adb_raw', 'uiautomator2']:
if disconnect:
logger.debug('adb disconnect %s', addr)
adb.disconnect(addr)
if connect:
logger.debug('adb connect %s', addr)
result = adb.connect(addr)
if 'cannot connect to' in result:
raise ValueError(result)
serial = device_serial or addr
logger.debug('adb wait for %s', serial)
adb.wait_for(serial, timeout=timeout)
devices = adb.device_list()
logger.debug('adb device_list: %s', devices)
d = [d for d in devices if d.serial == serial]
if len(d) == 0:
raise ValueError(f"Device {addr} not found")
d = d[0]
device = AndroidDevice(d)
if impl == 'adb':
device._command = AdbImpl(device)
device._touch = AdbImpl(device)
device._screenshot = AdbImpl(device)
elif impl == 'adb_raw':
device._command = AdbRawImpl(device)
device._touch = AdbRawImpl(device)
device._screenshot = AdbRawImpl(device)
elif impl == 'uiautomator2':
device._command = UiAutomator2Impl(device)
device._touch = UiAutomator2Impl(device)
device._screenshot = UiAutomator2Impl(device)
elif impl == 'windows':
device = WindowsDevice()
device._touch = WindowsImpl(device)
device._screenshot = WindowsImpl(device)
elif impl == 'remote_windows':
# For remote_windows, addr should be in the format 'host:port'
if ':' not in addr:
raise ValueError(f"Invalid address format for remote_windows: {addr}. Expected format: 'host:port'")
host, port_str = addr.split(':', 1)
try:
port = int(port_str)
except ValueError:
raise ValueError(f"Invalid port in address: {port_str}")
device = WindowsDevice()
remote_impl = RemoteWindowsImpl(device, host, port)
device._touch = remote_impl
device._screenshot = remote_impl
else:
raise ValueError(f"Unsupported device implementation: {impl}")
return device

View File

@ -1,10 +1,11 @@
from .protocol import HostProtocol, Instance
from .protocol import HostProtocol, Instance, AdbHostConfig, WindowsHostConfig, RemoteWindowsHostConfig
from .custom import CustomInstance, create as create_custom
from .mumu12_host import Mumu12Host, Mumu12Instance
from .leidian_host import LeidianHost, LeidianInstance
__all__ = [
'HostProtocol', 'Instance',
'AdbHostConfig', 'WindowsHostConfig', 'RemoteWindowsHostConfig',
'CustomInstance', 'create_custom',
'Mumu12Host', 'Mumu12Instance',
'LeidianHost', 'LeidianInstance'

View File

@ -1,19 +1,22 @@
import os
import subprocess
from psutil import process_iter
from .protocol import HostProtocol, Instance
from typing import Optional, ParamSpec, TypeVar, TypeGuard
from .protocol import Instance, AdbHostConfig
from typing import ParamSpec, TypeVar, cast
from typing_extensions import override
from kotonebot import logging
from kotonebot.client import DeviceImpl
from kotonebot.client.device import Device
from kotonebot.client.registration import AdbBasedImpl, create_device
from kotonebot.client.implements.adb import AdbImplConfig
logger = logging.getLogger(__name__)
P = ParamSpec('P')
T = TypeVar('T')
class CustomInstance(Instance):
class CustomInstance(Instance[AdbHostConfig]):
def __init__(self, exe_path: str | None, emulator_args: str = "", *args, **kwargs):
super().__init__(*args, **kwargs)
self.exe_path: str | None = exe_path
@ -65,6 +68,26 @@ class CustomInstance(Instance):
def refresh(self):
pass
@override
def create_device(self, impl: DeviceImpl, host_config: AdbHostConfig) -> Device:
"""为自定义实例创建 Device。"""
if self.adb_port is None:
raise ValueError("ADB port is not set and is required.")
# 为 ADB 相关的实现创建配置
if impl in ['adb', 'adb_raw', 'uiautomator2']:
config = AdbImplConfig(
addr=f'{self.adb_ip}:{self.adb_port}',
connect=True,
disconnect=True,
device_serial=self.adb_name,
timeout=host_config.timeout
)
impl = cast(AdbBasedImpl, impl) # make pylance happy
return create_device(impl, config)
else:
raise ValueError(f'Unsupported device implementation for Custom: {impl}')
def __repr__(self) -> str:
return f'CustomInstance(#{self.id}# at "{self.exe_path}" with {self.adb_ip}:{self.adb_port})'

View File

@ -1,13 +1,16 @@
import os
import subprocess
from typing import cast
from functools import lru_cache
from typing_extensions import override
from kotonebot import logging
from kotonebot.client import DeviceImpl, create_device
from kotonebot.client import DeviceImpl
from kotonebot.client.device import Device
from kotonebot.client.registration import AdbBasedImpl, create_device
from kotonebot.client.implements.adb import AdbImplConfig
from kotonebot.util import Countdown, Interval
from .protocol import HostProtocol, Instance, copy_type
from .protocol import HostProtocol, Instance, copy_type, AdbHostConfig
logger = logging.getLogger(__name__)
@ -18,7 +21,7 @@ else:
"""Stub for read_reg on non-Windows platforms."""
return default
class LeidianInstance(Instance):
class LeidianInstance(Instance[AdbHostConfig]):
@copy_type(Instance.__init__)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@ -70,16 +73,24 @@ class LeidianInstance(Instance):
return result.strip() == 'running'
@override
def create_device(self, impl: DeviceImpl, *, timeout: float = 180) -> Device:
def create_device(self, impl: DeviceImpl, host_config: AdbHostConfig) -> Device:
"""为雷电模拟器实例创建 Device。"""
if self.adb_port is None:
raise ValueError("ADB port is not set and is required.")
return create_device(
addr=f'{self.adb_ip}:{self.adb_port}',
impl=impl,
device_serial=self.adb_name,
connect=False,
timeout=timeout
)
# 为 ADB 相关的实现创建配置
if impl in ['adb', 'adb_raw', 'uiautomator2']:
config = AdbImplConfig(
addr=f'{self.adb_ip}:{self.adb_port}',
connect=False, # 雷电模拟器不需要 adb connect
disconnect=False,
device_serial=self.adb_name,
timeout=host_config.timeout
)
impl = cast(AdbBasedImpl, impl) # make pylance happy
return create_device(impl, config)
else:
raise ValueError(f'Unsupported device implementation for Leidian: {impl}')
class LeidianHost(HostProtocol):
@staticmethod

View File

@ -2,13 +2,15 @@ import os
import json
import subprocess
from functools import lru_cache
from typing import Any
from typing import Any, cast
from typing_extensions import override
from kotonebot import logging
from kotonebot.client import DeviceImpl, Device
from kotonebot.client.registration import AdbBasedImpl, create_device
from kotonebot.client.implements.adb import AdbImplConfig
from kotonebot.util import Countdown, Interval
from .protocol import HostProtocol, Instance, copy_type
from .protocol import HostProtocol, Instance, copy_type, AdbHostConfig
logger = logging.getLogger(__name__)
@ -19,7 +21,7 @@ else:
"""Stub for read_reg on non-Windows platforms."""
return default
class Mumu12Instance(Instance):
class Mumu12Instance(Instance[AdbHostConfig]):
@copy_type(Instance.__init__)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@ -70,6 +72,26 @@ class Mumu12Instance(Instance):
def running(self) -> bool:
return self.is_android_started
@override
def create_device(self, impl: DeviceImpl, host_config: AdbHostConfig) -> Device:
"""为MuMu12模拟器实例创建 Device。"""
if self.adb_port is None:
raise ValueError("ADB port is not set and is required.")
# 为 ADB 相关的实现创建配置
if impl in ['adb', 'adb_raw', 'uiautomator2']:
config = AdbImplConfig(
addr=f'{self.adb_ip}:{self.adb_port}',
connect=True,
disconnect=True,
device_serial=self.adb_name,
timeout=host_config.timeout
)
impl = cast(AdbBasedImpl, impl) # make pylance happy
return create_device(impl, config)
else:
raise ValueError(f'Unsupported device implementation for MuMu12: {impl}')
class Mumu12Host(HostProtocol):
@staticmethod
@lru_cache(maxsize=1)

View File

@ -1,14 +1,15 @@
import time
import socket
from abc import ABC, abstractmethod
from typing_extensions import ParamSpec, Concatenate
from typing import Callable, TypeVar, Generic, Protocol, runtime_checkable, Type, Any
from typing import Callable, TypeVar, Protocol, Any, Generic
from dataclasses import dataclass
from adbutils import adb, AdbTimeout, AdbError
from adbutils._device import AdbDevice
from kotonebot import logging
from kotonebot.client import Device, create_device, DeviceImpl
from kotonebot.client import Device, DeviceImpl
from kotonebot.util import Countdown, Interval
logger = logging.getLogger(__name__)
@ -17,6 +18,28 @@ _T = TypeVar("_T")
def copy_type(_: _T) -> Callable[[Any], _T]:
return lambda x: x
# --- 定义专用的 HostConfig 数据类 ---
@dataclass
class AdbHostConfig:
"""由外部为基于 ADB 的主机提供的配置。"""
timeout: float = 180
@dataclass
class WindowsHostConfig:
"""由外部为 Windows 实现提供配置。"""
window_title: str
ahk_exe_path: str
@dataclass
class RemoteWindowsHostConfig:
"""由外部为远程 Windows 实现提供配置。"""
windows_host_config: WindowsHostConfig
host: str
port: int
# --- 使用泛型改造 Instance 协议 ---
T_HostConfig = TypeVar("T_HostConfig")
def tcp_ping(host: str, port: int, timeout: float = 1.0) -> bool:
"""
通过 TCP ping 检查主机和端口是否可达
@ -36,7 +59,11 @@ def tcp_ping(host: str, port: int, timeout: float = 1.0) -> bool:
return False
class Instance(ABC):
class Instance(Generic[T_HostConfig], ABC):
"""
代表一个可运行环境的实例如一个模拟器
使用泛型来约束 create_device 方法的配置参数类型
"""
def __init__(self,
id: str,
name: str,
@ -68,7 +95,7 @@ class Instance(ABC):
启动模拟器实例
"""
raise NotImplementedError()
@abstractmethod
def stop(self):
"""
@ -80,21 +107,16 @@ class Instance(ABC):
def running(self) -> bool:
raise NotImplementedError()
def create_device(self, impl: DeviceImpl, *, timeout: float = 180) -> Device:
@abstractmethod
def create_device(self, impl: DeviceImpl, host_config: T_HostConfig) -> Device:
"""
创建 Device 实例可用于控制模拟器系统
:return: Device 实例
根据实现名称和类型化的主机配置创建设备
:param impl: 设备实现的名称
:param host_config: 一个类型化的数据对象包含创建所需的所有外部配置
:return: 配置好的 Device 实例
"""
if self.adb_port is None:
raise ValueError("ADB port is not set and is required.")
return create_device(
addr=f'{self.adb_ip}:{self.adb_port}',
impl=impl,
device_serial=self.adb_name,
connect=True,
timeout=timeout
)
raise NotImplementedError()
def wait_available(self, timeout: float = 180):
logger.info('Starting to wait for emulator %s(127.0.0.1:%d) to be available...', self.name, self.adb_port)

View File

@ -0,0 +1,6 @@
# 导入所有内置实现,以触发它们的 @register_impl 装饰器
from . import adb # noqa: F401
from . import adb_raw # noqa: F401
from . import remote_windows # noqa: F401
from . import uiautomator2 # noqa: F401
from . import windows # noqa: F401

View File

@ -5,16 +5,27 @@ from typing_extensions import override
import cv2
import numpy as np
from cv2.typing import MatLike
from adbutils._device import AdbDevice as AdbUtilsDevice
from ..device import Device
from ..protocol import Commandable, Touchable, Screenshotable
from ..device import AndroidDevice
from ..protocol import AndroidCommandable, Touchable, Screenshotable
from ..registration import register_impl, ImplConfig
from dataclasses import dataclass
logger = logging.getLogger(__name__)
class AdbImpl(Commandable, Touchable, Screenshotable):
def __init__(self, device: Device):
self.device = device
self.adb = device.adb
# 定义配置模型
@dataclass
class AdbImplConfig(ImplConfig):
addr: str
connect: bool = True
disconnect: bool = True
device_serial: str | None = None
timeout: float = 180
class AdbImpl(AndroidCommandable, Touchable, Screenshotable):
def __init__(self, adb_connection: AdbUtilsDevice):
self.adb = adb_connection
@override
def launch_app(self, package_name: str) -> None:
@ -36,6 +47,10 @@ class AdbImpl(Commandable, Touchable, Screenshotable):
package = activity.split('/')[0]
return package
def adb_shell(self, cmd: str) -> str:
"""执行 ADB shell 命令"""
return cast(str, self.adb.shell(cmd))
@override
def detect_orientation(self):
# 判断方向https://stackoverflow.com/questions/10040624/check-if-device-is-landscape-via-adb
@ -50,7 +65,9 @@ class AdbImpl(Commandable, Touchable, Screenshotable):
def screen_size(self) -> tuple[int, int]:
ret = cast(str, self.adb.shell("wm size")).strip('Physical size: ')
spiltted = tuple(map(int, ret.split("x")))
landscape = self.device.orientation == 'landscape'
# 检测当前方向
orientation = self.detect_orientation()
landscape = orientation == 'landscape'
spiltted = tuple(sorted(spiltted, reverse=landscape))
if len(spiltted) != 2:
raise ValueError(f"Invalid screen size: {ret}")
@ -66,3 +83,46 @@ class AdbImpl(Commandable, Touchable, Screenshotable):
if duration is not None:
logger.warning("Swipe duration is not supported with AdbDevice. Ignoring duration.")
self.adb.shell(f"input touchscreen swipe {x1} {y1} {x2} {y2}")
def _create_adb_device_base(config: AdbImplConfig, impl_class: type) -> AndroidDevice:
"""
通用的 ADB 设备创建工厂函数
其他任意基于 ADB Impl 可以直接复用这个函数
:param config: ADB 实现配置
:param impl_class: 实现类或工厂函数构造函数接收 adb_connection 参数
"""
from adbutils import adb
if config.disconnect:
logger.debug('adb disconnect %s', config.addr)
adb.disconnect(config.addr)
if config.connect:
logger.debug('adb connect %s', config.addr)
result = adb.connect(config.addr)
if 'cannot connect to' in result:
raise ValueError(result)
serial = config.device_serial or config.addr
logger.debug('adb wait for %s', serial)
adb.wait_for(serial, timeout=config.timeout)
devices = adb.device_list()
logger.debug('adb device_list: %s', devices)
d = [d for d in devices if d.serial == serial]
if len(d) == 0:
raise ValueError(f"Device {config.addr} not found")
d = d[0]
device = AndroidDevice(d)
impl = impl_class(d)
device._touch = impl
device._screenshot = impl
device.commands = impl
return device
@register_impl('adb', config_model=AdbImplConfig)
def create_adb_device(config: AdbImplConfig) -> AndroidDevice:
"""AdbImpl 工厂函数"""
return _create_adb_device_base(config, AdbImpl)

View File

@ -11,8 +11,9 @@ import numpy as np
from cv2.typing import MatLike
from adbutils._utils import adb_path
from .adb import AdbImpl
from ..device import Device
from .adb import AdbImpl, AdbImplConfig, _create_adb_device_base
from adbutils._device import AdbDevice as AdbUtilsDevice
from ..registration import register_impl
from kotonebot import logging
logger = logging.getLogger(__name__)
@ -27,8 +28,8 @@ done
"""
class AdbRawImpl(AdbImpl):
def __init__(self, device: Device):
super().__init__(device)
def __init__(self, adb_connection: AdbUtilsDevice):
super().__init__(adb_connection)
self.__worker: Thread | None = None
self.__process: subprocess.Popen | None = None
self.__data: MatLike | None = None
@ -156,4 +157,10 @@ class AdbRawImpl(AdbImpl):
logger.verbose(f"adb raw screenshot wait time: {time.time() - start_time:.4f}s")
data = self.__data
self.__data = None
return data
return data
@register_impl('adb_raw', config_model=AdbImplConfig)
def create_adb_raw_device(config: AdbImplConfig):
"""AdbRawImpl 工厂函数"""
return _create_adb_device_base(config, AdbRawImpl)

View File

@ -14,6 +14,7 @@ import xmlrpc.server
from typing import Literal, cast, Any, Tuple
from functools import cached_property
from threading import Thread
from dataclasses import dataclass
import cv2
import numpy as np
@ -22,10 +23,18 @@ from cv2.typing import MatLike
from kotonebot import logging
from ..device import Device, WindowsDevice
from ..protocol import Touchable, Screenshotable
from .windows import WindowsImpl
from ..registration import register_impl, ImplConfig
from .windows import WindowsImpl, WindowsImplConfig, create_windows_device
logger = logging.getLogger(__name__)
# 定义配置模型
@dataclass
class RemoteWindowsImplConfig(ImplConfig):
windows_impl_config: WindowsImplConfig
host: str = "localhost"
port: int = 8000
def _encode_image(image: MatLike) -> str:
"""Encode an image as a base64 string."""
success, buffer = cv2.imencode('.png', image)
@ -48,13 +57,13 @@ class RemoteWindowsServer:
This class wraps a WindowsImpl instance and exposes its methods via XML-RPC.
"""
def __init__(self, host="localhost", port=8000):
def __init__(self, windows_impl_config: WindowsImplConfig, host="localhost", port=8000):
"""Initialize the server with the given host and port."""
self.host = host
self.port = port
self.server = None
self.device = WindowsDevice()
self.impl = WindowsImpl(self.device)
self.impl = create_windows_device(windows_impl_config)
self.device._screenshot = self.impl
self.device._touch = self.impl
@ -180,18 +189,11 @@ class RemoteWindowsImpl(Touchable, Screenshotable):
raise RuntimeError(f"Failed to swipe from ({x1}, {y1}) to ({x2}, {y2})")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Remote Windows XML-RPC Server")
parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
parser.add_argument("--port", type=int, default=8000, help="Port to bind to")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
server = RemoteWindowsServer(args.host, args.port)
try:
server.start()
except KeyboardInterrupt:
logger.info("Server stopped by user")
# 编写并注册创建函数
@register_impl('remote_windows', config_model=RemoteWindowsImplConfig)
def create_remote_windows_device(config: RemoteWindowsImplConfig) -> Device:
device = WindowsDevice()
remote_impl = RemoteWindowsImpl(device, config.host, config.port)
device._touch = remote_impl
device._screenshot = remote_impl
return device

View File

@ -8,6 +8,8 @@ from cv2.typing import MatLike
from kotonebot import logging
from ..device import Device
from ..protocol import Screenshotable, Commandable, Touchable
from ..registration import register_impl
from .adb import AdbImplConfig, _create_adb_device_base
logger = logging.getLogger(__name__)
@ -83,3 +85,9 @@ class UiAutomator2Impl(Screenshotable, Commandable, Touchable):
滑动屏幕
"""
self.u2_client.swipe(x1, y1, x2, y2, duration=duration or 0.1)
@register_impl('uiautomator2', config_model=AdbImplConfig)
def create_uiautomator2_device(config: AdbImplConfig) -> Device:
"""UiAutomator2Impl 工厂函数"""
return _create_adb_device_base(config, UiAutomator2Impl)

View File

@ -2,31 +2,51 @@ from ctypes import windll
from typing import Literal
from importlib import resources
from functools import cached_property
from dataclasses import dataclass
import cv2
import win32ui
import win32gui
import numpy as np
from ahk import AHK
from ahk import AHK, MsgBoxIcon
from cv2.typing import MatLike
from ..device import Device
from ..device import Device, WindowsDevice
from ..protocol import Commandable, Touchable, Screenshotable
from ..registration import register_impl, ImplConfig
# 1. 定义配置模型
@dataclass
class WindowsImplConfig(ImplConfig):
window_title: str
ahk_exe_path: str
class WindowsImpl(Touchable, Screenshotable):
def __init__(self, device: Device):
def __init__(self, device: Device, window_title: str, ahk_exe_path: str):
self.__hwnd: int | None = None
# TODO: 硬编码路径
self.ahk = AHK(executable_path=str(resources.files('kaa.res.bin') / 'AutoHotkey.exe'))
self.window_title = window_title
self.ahk = AHK(executable_path=ahk_exe_path)
self.device = device
self.emergency = False
# 设置 DPI aware否则高缩放显示器上返回的坐标会错误
windll.user32.SetProcessDPIAware()
def toggle_emergency():
self.emergency = True
self.ahk.msg_box('已启用紧急暂停模式')
self.ahk.add_hotkey('^F4', toggle_emergency)
# TODO: 这个应该移动到其他地方去
def _stop():
from kotonebot.backend.context.context import vars
vars.flow.request_interrupt()
self.ahk.msg_box('任务已停止。', title='琴音小助手', icon=MsgBoxIcon.EXCLAMATION)
def _toggle_pause():
from kotonebot.backend.context.context import vars
if vars.flow.is_paused:
self.ahk.msg_box('任务即将恢复。\n关闭此消息框后将会继续执行', title='琴音小助手', icon=MsgBoxIcon.EXCLAMATION)
vars.flow.request_resume()
else:
vars.flow.request_pause()
self.ahk.msg_box('任务已暂停。\n关闭此消息框后再按一次快捷键恢复执行。', title='琴音小助手', icon=MsgBoxIcon.EXCLAMATION)
self.ahk.add_hotkey('^F4', _toggle_pause) # Ctrl+F4 暂停/恢复
self.ahk.add_hotkey('^F3', _stop) # Ctrl+F3 停止
self.ahk.start_hotkeys()
# 将点击坐标设置为相对 Client
self.ahk.set_coord_mode('Mouse', 'Client')
@ -43,9 +63,9 @@ class WindowsImpl(Touchable, Screenshotable):
@property
def hwnd(self) -> int:
if self.__hwnd is None:
self.__hwnd = win32gui.FindWindow(None, 'gakumas')
self.__hwnd = win32gui.FindWindow(None, self.window_title)
if self.__hwnd is None or self.__hwnd == 0:
raise RuntimeError('Failed to find window')
raise RuntimeError(f'Failed to find window: {self.window_title}')
return self.__hwnd
def __client_rect(self) -> tuple[int, int, int, int]:
@ -60,14 +80,9 @@ class WindowsImpl(Touchable, Screenshotable):
"""将 Client 区域坐标转换为屏幕坐标"""
return win32gui.ClientToScreen(hwnd, (x, y))
def __wait_not_emergency(self):
from time import sleep # TODO: 改为 kotonebot.backend.context.sleep
while self.emergency:
sleep(0.2)
def screenshot(self) -> MatLike:
if not self.ahk.win_is_active('gakumas'):
self.ahk.win_activate('gakumas')
if not self.ahk.win_is_active(self.window_title):
self.ahk.win_activate(self.window_title)
hwnd = self.hwnd
# TODO: 需要检查下面这些 WinAPI 的返回结果
@ -123,7 +138,7 @@ class WindowsImpl(Touchable, Screenshotable):
return 720, 1280
def detect_orientation(self) -> None | Literal['portrait'] | Literal['landscape']:
pos = self.ahk.win_get_position('gakumas')
pos = self.ahk.win_get_position(self.window_title)
if pos is None:
return None
w, h = pos.width, pos.height
@ -133,7 +148,6 @@ class WindowsImpl(Touchable, Screenshotable):
return 'portrait'
def click(self, x: int, y: int) -> None:
self.__wait_not_emergency()
# x, y = self.__client_to_screen(self.hwnd, x, y)
# (0, 0) 很可能会点到窗口边框上
if x == 0:
@ -141,25 +155,39 @@ class WindowsImpl(Touchable, Screenshotable):
if y == 0:
y = 2
x, y = int(x / self.scale_ratio), int(y / self.scale_ratio)
if not self.ahk.win_is_active('gakumas'):
self.ahk.win_activate('gakumas')
if not self.ahk.win_is_active(self.window_title):
self.ahk.win_activate(self.window_title)
self.ahk.click(x, y)
def swipe(self, x1: int, y1: int, x2: int, y2: int, duration: float | None = None) -> None:
self.__wait_not_emergency()
if not self.ahk.win_is_active('gakumas'):
self.ahk.win_activate('gakumas')
if not self.ahk.win_is_active(self.window_title):
self.ahk.win_activate(self.window_title)
x1, y1 = int(x1 / self.scale_ratio), int(y1 / self.scale_ratio)
x2, y2 = int(x2 / self.scale_ratio), int(y2 / self.scale_ratio)
# TODO: 这个 speed 的单位是什么?
self.ahk.mouse_drag(x2, y2, from_position=(x1, y1), coord_mode='Client', speed=10)
# 3. 编写并注册创建函数
@register_impl('windows', config_model=WindowsImplConfig)
def create_windows_device(config: WindowsImplConfig) -> Device:
device = WindowsDevice()
impl = WindowsImpl(
device,
window_title=config.window_title,
ahk_exe_path=config.ahk_exe_path
)
device._touch = impl
device._screenshot = impl
return device
if __name__ == '__main__':
from ..device import Device
from time import sleep
device = Device()
impl = WindowsImpl(device)
# 在测试环境中直接使用默认路径
ahk_path = str(resources.files('kaa.res.bin') / 'AutoHotkey.exe')
impl = WindowsImpl(device, window_title='gakumas', ahk_exe_path=ahk_path)
device._screenshot = impl
device._touch = impl
device.swipe_scaled(0.5, 0.8, 0.5, 0.2)

View File

@ -28,6 +28,19 @@ class Commandable(Protocol):
def launch_app(self, package_name: str) -> None: ...
def current_package(self) -> str | None: ...
@runtime_checkable
class AndroidCommandable(Protocol):
"""定义 Android 平台的特定命令"""
def launch_app(self, package_name: str) -> None: ...
def current_package(self) -> str | None: ...
def adb_shell(self, cmd: str) -> str: ...
@runtime_checkable
class WindowsCommandable(Protocol):
"""定义 Windows 平台的特定命令"""
def get_foreground_window(self) -> tuple[int, str]: ...
def exec_command(self, command: str) -> tuple[int, str, str]: ...
@runtime_checkable
class Screenshotable(Protocol):
def __init__(self, device: 'Device'): ...

View File

@ -0,0 +1,89 @@
from dataclasses import dataclass
from typing import TypeVar, Callable, Dict, Type, Any, overload, Literal, cast, TYPE_CHECKING
from ..errors import KotonebotError
from .device import Device
if TYPE_CHECKING:
from .implements.adb import AdbImplConfig
from .implements.remote_windows import RemoteWindowsImplConfig
from .implements.windows import WindowsImplConfig
AdbBasedImpl = Literal['adb', 'adb_raw', 'uiautomator2']
DeviceImpl = str | AdbBasedImpl | Literal['windows', 'remote_windows']
# --- 核心类型定义 ---
class ImplRegistrationError(KotonebotError):
"""与 impl 注册相关的错误"""
pass
@dataclass
class ImplConfig:
"""所有设备实现配置模型的名义上的基类,便于类型约束。"""
pass
T_Config = TypeVar("T_Config", bound=ImplConfig)
# 定义两种创建者函数类型
CreatorWithConfig = Callable[[Any], Device]
CreatorWithoutConfig = Callable[[], Device]
# --- 底层 API: 公开的注册表 ---
# 注册表结构: {'impl_name': (创建函数, 配置模型类 或 None)}
DEVICE_CREATORS: Dict[str, tuple[Callable[..., Device], Type[ImplConfig] | None]] = {}
def register_impl(name: str, config_model: Type[ImplConfig] | None = None) -> Callable[..., Any]:
"""
一个统一的装饰器用于向 DEVICE_CREATORS 注册表中注册一个设备实现
:param name: 实现的名称 (e.g., 'windows', 'adb')
:param config_model: (可选) 与该实现关联的 dataclass 配置模型
"""
def decorator(creator_func: Callable[..., Device]) -> Callable[..., Device]:
if name in DEVICE_CREATORS:
raise ImplRegistrationError(f"实现 '{name}' 已被注册。")
DEVICE_CREATORS[name] = (creator_func, config_model)
return creator_func
return decorator
# --- 高层 API: 带 overload 的便利函数 ---
# 为需要配置的已知 impl 提供 overload
@overload
def create_device(impl_name: Literal['windows'], config: 'WindowsImplConfig') -> Device: ...
@overload
def create_device(impl_name: Literal['remote_windows'], config: 'RemoteWindowsImplConfig') -> Device: ...
@overload
def create_device(impl_name: AdbBasedImpl, config: 'AdbImplConfig') -> Device: ...
# 函数的实际实现
def create_device(impl_name: DeviceImpl, config: ImplConfig | None = None) -> Device:
"""
根据名称和可选的配置对象统一创建设备
"""
creator_tuple = DEVICE_CREATORS.get(impl_name)
if not creator_tuple:
raise ImplRegistrationError(f"未找到名为 '{impl_name}' 的实现。")
creator_func, registered_config_model = creator_tuple
# 情况 A: 实现需要配置
if registered_config_model is not None:
creator_with_config = cast(CreatorWithConfig, creator_func)
if config is None:
raise ValueError(f"实现 '{impl_name}' 需要一个配置对象,但传入的是 None。")
if not isinstance(config, registered_config_model):
raise TypeError(f"'{impl_name}' 传入的配置类型错误,应为 '{registered_config_model.__name__}',实际为 '{type(config).__name__}'")
return creator_with_config(config)
# 情况 B: 实现无需配置
else:
creator_without_config = cast(CreatorWithoutConfig, creator_func)
if config is not None:
print(f"提示:实现 '{impl_name}' 无需配置,但你提供了一个配置对象,它将被忽略。")
return creator_without_config()

View File

@ -3,7 +3,7 @@ from typing import Generic, TypeVar, Literal
from pydantic import BaseModel, ConfigDict
from kotonebot.client.factory import DeviceImpl
from kotonebot.client import DeviceImpl
T = TypeVar('T')
BackendType = Literal['custom', 'mumu12', 'leidian', 'dmm']
@ -44,6 +44,10 @@ class BackendConfig(ConfigBaseModel):
"""模拟器 exe 文件路径"""
emulator_args: str = ""
"""模拟器启动时的命令行参数"""
windows_window_title: str = 'gakumas'
"""Windows 截图方式的窗口标题"""
windows_ahk_path: str | None = None
"""Windows 截图方式的 AutoHotkey 可执行文件路径,为 None 时使用默认路径"""
class PushConfig(ConfigBaseModel):
"""推送配置。"""

View File

@ -17,10 +17,15 @@ def run_script(script_path: str) -> None:
print(f"正在运行脚本: {script_path}")
# 运行脚本
from kotonebot.backend.context import init_context
from kotonebot.backend.context import init_context, manual_context
from kotonebot.kaa.main.kaa import Kaa
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s] [%(lineno)d] %(message)s')
logging.getLogger('kotonebot').setLevel(logging.DEBUG)
init_context(config_type=BaseConfig)
config_path = './config.json'
kaa_instance = Kaa(config_path)
init_context(config_type=BaseConfig, target_device=kaa_instance._on_create_device())
kaa_instance._on_after_init_context()
manual_context().begin()
runpy.run_module(module_name, run_name="__main__")
def main():

View File

@ -28,7 +28,4 @@ def clear_logs():
logger.info('Clearing logs done.')
if __name__ == '__main__':
from kotonebot.backend.context import init_context, manual_context
init_context()
manual_context().begin()
clear_logs()

View File

@ -425,6 +425,20 @@ class StartGameConfig(ConfigBaseModel):
kuyo_package_name: str = 'org.kuyo.game'
"""Kuyo包名"""
disable_gakumas_localify: bool = False
"""
自动检测并禁用 Gakumas Localify 汉化插件
目前仅对 DMM 版有效
"""
dmm_game_path: str | None = None
"""
DMM 版游戏路径若不填写会自动检测
`F:\\Games\\gakumas\\gakumas.exe`
"""
class EndGameConfig(ConfigBaseModel):
exit_kaa: bool = False
@ -439,6 +453,13 @@ class EndGameConfig(ConfigBaseModel):
"""关闭系统"""
hibernate: bool = False
"""休眠系统"""
restore_gakumas_localify: bool = False
"""
恢复 Gakumas Localify 汉化插件状态至启动前通常与
`disable_gakumas_localify` 配对使用
目前仅对 DMM 版有效
"""
class BaseConfig(ConfigBaseModel):
purchase: PurchaseConfig = PurchaseConfig()

View File

@ -2,10 +2,10 @@ import cv2
import numpy as np
from cv2.typing import MatLike
from kotonebot import action, color, image
from kotonebot.backend.color import HsvColor
from kotonebot.primitives import RectTuple, Rect
from kotonebot.primitives import Rect
from kotonebot.backend.core import Image
from kotonebot.backend.color import HsvColor
from kotonebot import action, color, image, device
from kotonebot.backend.preprocessor import HsvColorFilter
@ -88,7 +88,4 @@ class WhiteFilter(HsvColorFilter):
if __name__ == '__main__':
from kotonebot.backend.context import init_context, manual_context, device
init_context()
manual_context().begin()
pass

View File

@ -1,45 +1,65 @@
import logging
from kotonebot.kaa.tasks import R
from kotonebot import device, image
def expect_yes():
logger = logging.getLogger(__name__)
def expect_yes(*, msg: str | None = None):
"""
点击对话框上的按钮若不存在会等待其出现直至超时异常
前置条件当前打开了任意对话框\n
结束状态点击了肯定意义按钮图标橙色背景后瞬间
:param msg: 成功点击后输出的日志信息信息中的动词建议使用过去式
"""
device.click(image.expect(R.Common.IconButtonCheck))
if msg is not None:
logger.debug(msg)
def yes() -> bool:
def yes(*, msg: str | None = None) -> bool:
"""
点击对话框上的按钮
前置条件当前打开了任意对话框\n
结束状态点击了肯定意义按钮图标橙色背景后瞬间
:param msg: 成功点击后输出的日志信息信息中的动词建议使用过去式
"""
if image.find(R.Common.IconButtonCheck):
device.click()
if msg is not None:
logger.debug(msg)
return True
return False
def expect_no():
def expect_no(*, msg: str | None = None):
"""
点击对话框上的按钮若不存在会等待其出现直至超时异常
前置条件当前打开了任意对话框\n
结束状态点击了否定意义按钮图标白色背景后瞬间
:param msg: 成功点击后输出的日志信息信息中的动词建议使用过去式
"""
device.click(image.expect(R.Common.IconButtonCross))
if msg is not None:
logger.debug(msg)
def no():
def no(*, msg: str | None = None):
"""
点击对话框上的按钮
前置条件当前打开了任意对话框\n
结束状态点击了否定意义按钮图标白色背景后瞬间
:param msg: 成功点击后输出的日志信息信息中的动词建议使用过去式
"""
if image.find(R.Common.IconButtonCross):
device.click()
if msg is not None:
logger.debug(msg)
return True
return False

View File

@ -10,7 +10,8 @@ from kotonebot.kaa.util import paths
from kotonebot.primitives import RectTuple, Rect
from kotonebot.kaa.game_ui import Scrollable
from kotonebot import device, action
from kotonebot.kaa.image_db import ImageDatabase, HistDescriptor, FileDataSource
from kotonebot.util import cv2_imread
from kotonebot.kaa.image_db import ImageDatabase, HistDescriptor, FileDataSource, DatabaseQueryResult
from kotonebot.backend.preprocessor import HsvColorsRemover
logger = logging.getLogger(__name__)
@ -110,9 +111,33 @@ def idols_db() -> ImageDatabase:
_db = ImageDatabase(FileDataSource(str(path)), db_path, HistDescriptor(8), name='idols')
return _db
def match_idol(skin_id: str, idol_img: MatLike) -> DatabaseQueryResult | None:
"""
将给定图像与指定偶像 ID 进行匹配
:param skin_id: 偶像 ID
:param idol_img: 待匹配偶像图像
:return: 若匹配成功则返回匹配结果否则返回 None
"""
db = idols_db()
match = db.match(idol_img, 20)
if match and match.key.startswith(skin_id):
return match
else:
return None
@action('定位偶像', screenshot_mode='manual-inherit')
def locate_idol(skin_id: str):
def locate_idol(skin_id: str) -> Rect | None:
"""
定位并选中指定偶像
前置条件位于偶像总览界面\n
结束状态位于偶像总览界面
:param skin_id: 目标偶像的 Skin ID
:return: 若成功返回目标偶像的范围 (x, y, w, h)否则返回 None
"""
device.screenshot()
logger.info('Locating idol %s', skin_id)
x, y, w, h = R.Produce.BoxIdolOverviewIdols.xywh
@ -170,14 +195,5 @@ def find_idol_skin_id_on_resume_produce(img: MatLike) -> str | None:
return None
def test():
from kotonebot.backend.context import init_context, manual_context
init_context()
manual_context().begin()
locate_idol('i_card-skin-fktn-3-006')
if __name__ == '__main__':
from kotonebot.util import cv2_imread
test()
locate_idol('i_card-skin-fktn-3-006')

View File

@ -0,0 +1,55 @@
import cv2
import numpy as np
from typing import Optional
from cv2.typing import MatLike
from kotonebot import action, image, device
from kotonebot.backend.core import Image
from kotonebot.backend.image import TemplateMatchResult
def primary_button_state(img: MatLike) -> Optional[bool]:
"""
分析按钮图像并根据红色通道直方图返回按钮状态
:param img: 输入的按钮图像 (BGR格式)
:return: True - 启用状态
False - 禁用状态
None - 未知状态或输入无效
"""
# 确保图像有效
if img is None or img.size == 0:
return None
# 计算红色通道直方图(五箱)
_, _, r = cv2.split(img)
hist = cv2.calcHist([r], [0], None, [5], [0, 256])
# 归一化并找出红色集中在哪一箱
hist = hist.ravel() / hist.sum()
max_idx = np.argmax(hist)
if max_idx == 3:
return False
elif max_idx == 4:
return True
else:
return None
@action('寻找按钮', screenshot_mode='manual-inherit')
def find_button(template: MatLike | Image, state: Optional[bool] = None) -> Optional[bool]:
"""
在图像中寻找按钮并返回其状态
:param template: 按钮模板图像 (BGR格式)
:param state: 按钮状态 (True - 启用, False - 禁用, None - 任意)
:return: True - 启用状态
False - 禁用状态
None - 未找到按钮或状态未知
"""
img = device.screenshot()
result = image.find(template)
if result is None:
return None
x, y, w, h = result.rect.xywh
button_img = img[y:y+h, x:x+w]
return primary_button_state(button_img)

View File

@ -327,12 +327,7 @@ class Scrollable:
return ScrollableIterator(self, int(self.track_height * step), start, end, skip_first)
if __name__ == '__main__':
from kotonebot.backend.context import init_context, manual_context, device
init_context()
manual_context().begin()
from kotonebot import device
import cv2
from kotonebot.util import cv2_imread
import time
logger.setLevel(logging.DEBUG)

View File

@ -1,13 +1,15 @@
import os
import sys
import runpy
import logging
import argparse
import importlib.metadata
from datetime import datetime
from .kaa import Kaa
from ..util.paths import get_ahk_path
from kotonebot.client.implements.windows import WindowsImplConfig
from kotonebot.backend.context import tasks_from_id, task_registry
from kotonebot.client.implements.remote_windows import RemoteWindowsServer
version = importlib.metadata.version('ksaa')
@ -90,9 +92,12 @@ def task_list() -> int:
def remote_server() -> int:
args = psr.parse_args()
try:
# 使用runpy运行remote_windows.py模块
sys.argv = ['remote_windows.py', f'--host={args.host}', f'--port={args.port}']
runpy.run_module('kotonebot.client.implements.remote_windows', run_name='__main__')
ahk_path = get_ahk_path()
server = RemoteWindowsServer(WindowsImplConfig(window_title='gakumas', ahk_exe_path=ahk_path), args.host, args.port)
server.start()
return 0
except KeyboardInterrupt:
print("Server stopped by user")
return 0
except Exception as e:
print(f'Error starting remote server: {e}')

View File

@ -1,11 +1,18 @@
from importlib import resources
from typing_extensions import override
from kotonebot.client import Device, create_device
from kotonebot.client import DeviceImpl, Device
from kotonebot.client import Device, DeviceImpl
from kotonebot.client.registration import create_device
from kotonebot.client.implements.windows import WindowsImplConfig
from kotonebot.client.implements.remote_windows import RemoteWindowsImplConfig
from kotonebot.client.host import HostProtocol, Instance
from kotonebot.client.host.protocol import WindowsHostConfig, RemoteWindowsHostConfig
DmmHostConfigs = WindowsHostConfig | RemoteWindowsHostConfig
# TODO: 可能应该把 start_game 和 end_game 里对启停的操作移动到这里来
class DmmInstance(Instance):
class DmmInstance(Instance[DmmHostConfigs]):
def __init__(self):
super().__init__('dmm', 'gakumas')
@ -30,10 +37,29 @@ class DmmInstance(Instance):
raise NotImplementedError()
@override
def create_device(self, impl: DeviceImpl, *, timeout: float = 180) -> Device:
if impl not in ['windows', 'remote_windows']:
raise ValueError(f'Unsupported device implementation: {impl}')
return create_device('', impl, timeout=timeout)
def create_device(self, impl: DeviceImpl, host_config: DmmHostConfigs) -> Device:
if impl == 'windows':
assert isinstance(host_config, WindowsHostConfig)
win_config = WindowsImplConfig(
window_title=host_config.window_title,
ahk_exe_path=host_config.ahk_exe_path
)
return create_device(impl, win_config)
elif impl == 'remote_windows':
assert isinstance(host_config, RemoteWindowsHostConfig)
config = RemoteWindowsImplConfig(
windows_impl_config=WindowsImplConfig(
window_title=host_config.windows_host_config.window_title,
ahk_exe_path=host_config.windows_host_config.ahk_exe_path
),
host=host_config.host,
port=host_config.port
)
return create_device(impl, config)
else:
raise ValueError(f'Unsupported impl for DMM: {impl}')
class DmmHost(HostProtocol):
instance = DmmInstance()

View File

@ -15,6 +15,7 @@ from kotonebot.kaa.db import IdolCard
from kotonebot.config.manager import load_config, save_config
from kotonebot.config.base_config import UserConfig, BackendConfig
from kotonebot.backend.context import task_registry, ContextStackVars
from kotonebot.backend.context.context import vars
from kotonebot.client.host import Mumu12Host, LeidianHost
from kotonebot.kaa.common import (
BaseConfig, APShopItems, CapsuleToysConfig, ClubRewardConfig, PurchaseConfig, ActivityFundsConfig,
@ -69,12 +70,14 @@ ConfigKey = Literal[
'anomaly_capsule_toys_count',
# start game
'start_game_enabled', 'start_through_kuyo',
'start_game_enabled', 'start_through_kuyo',
'game_package_name', 'kuyo_package_name',
'disable_gakumas_localify', 'dmm_game_path',
# end game
'exit_kaa', 'kill_game', 'kill_dmm',
'exit_kaa', 'kill_game', 'kill_dmm',
'kill_emulator', 'shutdown', 'hibernate',
'restore_gakumas_localify',
'activity_funds',
'presents',
@ -180,6 +183,8 @@ class KotoneBotUI:
def __init__(self, kaa: Kaa) -> None:
self.is_running: bool = False
self.single_task_running: bool = False
self.is_stopping: bool = False # 新增:标记是否正在停止过程中
self.is_single_task_stopping: bool = False # 新增:标记单个任务是否正在停止
self._kaa = kaa
self._load_config()
self._setup_kaa()
@ -230,14 +235,20 @@ class KotoneBotUI:
return f"已导出到 {zip_filename}"
def get_button_status(self) -> str:
def get_button_status(self) -> Tuple[str, bool]:
"""获取按钮状态和交互性"""
if not hasattr(self, 'run_status'):
return "启动"
return "启动", True
if not self.run_status.running:
self.is_running = False
return "启动"
return "停止"
self.is_stopping = False # 重置停止状态
return "启动", True
if self.is_stopping:
return "停止中...", False # 停止中时禁用按钮
return "停止", True
def update_task_status(self) -> List[List[str]]:
status_list: List[List[str]] = []
@ -260,6 +271,11 @@ class KotoneBotUI:
def toggle_run(self) -> Tuple[str, List[List[str]]]:
if not self.is_running:
return self.start_run()
# 如果正在停止过程中,忽略重复点击
if self.is_stopping:
return "停止中...", self.update_task_status()
return self.stop_run()
def start_run(self) -> Tuple[str, List[List[str]]]:
@ -268,10 +284,19 @@ class KotoneBotUI:
return "停止", self.update_task_status()
def stop_run(self) -> Tuple[str, List[List[str]]]:
self.is_stopping = True # 设置停止状态
# 如果当前处于暂停状态,先恢复再停止
if vars.flow.is_paused:
gr.Info("检测到任务暂停,正在恢复后停止...")
vars.flow.request_resume()
self.is_running = False
if self._kaa:
self.run_status.interrupt()
return "启动", self.update_task_status()
gr.Info("正在停止任务...")
return "停止中...", self.update_task_status()
def start_single_task(self, task_name: str) -> Tuple[str, str]:
if not task_name:
@ -292,11 +317,48 @@ class KotoneBotUI:
return "停止任务", f"正在执行任务: {task_name}"
def stop_single_task(self) -> Tuple[str, str]:
self.is_single_task_stopping = True # 设置单个任务停止状态
# 如果当前处于暂停状态,先恢复再停止
if vars.flow.is_paused:
gr.Info("检测到任务暂停,正在恢复后停止...")
vars.flow.request_resume()
self.single_task_running = False
if hasattr(self, 'run_status') and self._kaa:
self.run_status.interrupt()
gr.Info("任务已停止")
return "执行任务", "任务已停止"
gr.Info("正在停止任务...")
return "停止中...", "正在停止任务..."
def toggle_pause(self) -> str:
"""切换暂停/恢复状态"""
if vars.flow.is_paused:
vars.flow.request_resume()
gr.Info("任务已恢复")
return "暂停"
else:
vars.flow.request_pause()
gr.Info("任务已暂停")
return "恢复"
def get_pause_button_status(self) -> str:
"""获取暂停按钮的状态"""
if vars.flow.is_paused:
return "恢复"
else:
return "暂停"
def get_pause_button_with_interactive(self) -> gr.Button:
"""获取暂停按钮的状态和交互性"""
try:
text = "恢复" if vars.flow.is_paused else "暂停"
except ValueError:
# ValueError: Forwarded object vars called before initialization.
# TODO: vars.flow.is_paused 应该要可以在脚本正式启动前就能访问
text = '未启动'
# 如果正在停止过程中,禁用暂停按钮
interactive = not (self.is_stopping or self.is_single_task_stopping)
return gr.Button(value=text, interactive=interactive)
def save_settings2(self, return_values: list[ConfigBuilderReturnValue], *args) -> str:
options = BaseConfig()
@ -326,7 +388,8 @@ class KotoneBotUI:
gr.Markdown("## 状态")
with gr.Row():
run_btn = gr.Button("启动", scale=1)
run_btn = gr.Button("启动", scale=2)
pause_btn = gr.Button("暂停", scale=1)
if self._kaa.upgrade_msg:
gr.Markdown('### 配置升级报告')
gr.Markdown(self._kaa.upgrade_msg)
@ -338,19 +401,39 @@ class KotoneBotUI:
label="任务状态"
)
def on_run_click(evt: gr.EventData) -> Tuple[str, List[List[str]]]:
return self.toggle_run()
def on_run_click(evt: gr.EventData) -> Tuple[gr.Button, List[List[str]]]:
result = self.toggle_run()
# 如果正在停止,禁用按钮
interactive = not self.is_stopping
button = gr.Button(value=result[0], interactive=interactive)
return button, result[1]
def on_pause_click(evt: gr.EventData) -> str:
return self.toggle_pause()
run_btn.click(
fn=on_run_click,
outputs=[run_btn, task_status]
)
pause_btn.click(
fn=on_pause_click,
outputs=[pause_btn]
)
# 添加定时器,分别更新按钮状态和任务状态
def update_run_button_status():
text, interactive = self.get_button_status()
return gr.Button(value=text, interactive=interactive)
gr.Timer(1.0).tick(
fn=self.get_button_status,
fn=update_run_button_status,
outputs=[run_btn]
)
gr.Timer(1.0).tick(
fn=self.get_pause_button_with_interactive,
outputs=[pause_btn]
)
gr.Timer(1.0).tick(
fn=self.update_task_status,
outputs=[task_status]
@ -370,21 +453,34 @@ class KotoneBotUI:
value=None
)
# 创建执行按钮
execute_btn = gr.Button("执行任务")
# 创建执行按钮和暂停按钮
with gr.Row():
execute_btn = gr.Button("执行任务", scale=2)
pause_btn = gr.Button("暂停", scale=1)
task_result = gr.Markdown("")
def toggle_single_task(task_name: str) -> Tuple[str, str]:
def toggle_single_task(task_name: str) -> Tuple[gr.Button, str]:
if self.single_task_running:
return self.stop_single_task()
else:
return self.start_single_task(task_name)
# 如果正在停止过程中,忽略重复点击
if self.is_single_task_stopping:
return gr.Button(value="停止中...", interactive=False), "正在停止任务..."
def get_task_button_status() -> str:
result = self.stop_single_task()
return gr.Button(value=result[0], interactive=False), result[1]
else:
result = self.start_single_task(task_name)
return gr.Button(value=result[0], interactive=True), result[1]
def get_task_button_status() -> gr.Button:
if not hasattr(self, 'run_status') or not self.run_status.running:
self.single_task_running = False
return "执行任务"
return "停止任务"
self.is_single_task_stopping = False # 重置停止状态
return gr.Button(value="执行任务", interactive=True)
if self.is_single_task_stopping:
return gr.Button(value="停止中...", interactive=False) # 停止中时禁用按钮
return gr.Button(value="停止任务", interactive=True)
def get_single_task_status() -> str:
if not hasattr(self, 'run_status'):
@ -417,17 +513,29 @@ class KotoneBotUI:
return ""
def on_pause_click(evt: gr.EventData) -> str:
return self.toggle_pause()
execute_btn.click(
fn=toggle_single_task,
inputs=[task_dropdown],
outputs=[execute_btn, task_result]
)
pause_btn.click(
fn=on_pause_click,
outputs=[pause_btn]
)
# 添加定时器更新按钮状态和任务状态
gr.Timer(1.0).tick(
fn=get_task_button_status,
outputs=[execute_btn]
)
gr.Timer(1.0).tick(
fn=self.get_pause_button_with_interactive,
outputs=[pause_btn]
)
gr.Timer(1.0).tick(
fn=get_single_task_status,
outputs=[task_result]
@ -461,9 +569,10 @@ class KotoneBotUI:
if has_mumu12:
try:
instances = Mumu12Host.list()
is_mumu12 = self.current_config.backend.type == 'mumu12'
mumu_instance = gr.Dropdown(
label="选择多开实例",
value=self.current_config.backend.instance_id,
value=self.current_config.backend.instance_id if is_mumu12 else None,
choices=[(i.name, i.id) for i in instances],
interactive=True
)
@ -480,9 +589,10 @@ class KotoneBotUI:
if has_leidian:
try:
instances = LeidianHost.list()
is_leidian = self.current_config.backend.type == 'leidian'
leidian_instance = gr.Dropdown(
label="选择多开实例",
value=self.current_config.backend.instance_id,
value=self.current_config.backend.instance_id if is_leidian else None,
choices=[(i.name, i.id) for i in instances],
interactive=True
)
@ -572,6 +682,30 @@ class KotoneBotUI:
tab_custom.select(fn=partial(_update_emulator_tab_options, selected_index=2), inputs=[screenshot_impl], outputs=[screenshot_impl])
tab_dmm.select(fn=partial(_update_emulator_tab_options, selected_index=3), inputs=[screenshot_impl], outputs=[screenshot_impl])
# 初值
if self.current_config.backend.type == 'mumu12':
_update_emulator_tab_options(
impl_value=self.current_config.backend.screenshot_impl,
selected_index=0
)
elif self.current_config.backend.type == 'leidian':
_update_emulator_tab_options(
impl_value=self.current_config.backend.screenshot_impl,
selected_index=1
)
elif self.current_config.backend.type == 'custom':
_update_emulator_tab_options(
impl_value=self.current_config.backend.screenshot_impl,
selected_index=2
)
elif self.current_config.backend.type == 'dmm':
_update_emulator_tab_options(
impl_value=self.current_config.backend.screenshot_impl,
selected_index=3
)
else:
gr.Warning(f"未知的模拟器类型:{self.current_config.backend.type}")
def set_config(_: BaseConfig, data: dict[ConfigKey, Any]) -> None:
# current_tab is updated by _update_emulator_tab_options
if current_tab == 0: # Mumu
@ -1080,6 +1214,17 @@ class KotoneBotUI:
label="Kuyo包名",
info=StartGameConfig.model_fields['kuyo_package_name'].description
)
disable_gakumas_localify = gr.Checkbox(
label="禁用 Gakumas Localify 汉化插件",
value=self.current_config.options.start_game.disable_gakumas_localify,
info=StartGameConfig.model_fields['disable_gakumas_localify'].description
)
dmm_game_path = gr.Textbox(
value=self.current_config.options.start_game.dmm_game_path or "",
label="DMM 版游戏路径",
info=StartGameConfig.model_fields['dmm_game_path'].description,
placeholder="F:\\Games\\gakumas\\gakumas.exe"
)
start_game_enabled.change(
fn=lambda x: gr.Group(visible=x),
inputs=[start_game_enabled],
@ -1091,12 +1236,16 @@ class KotoneBotUI:
config.start_game.start_through_kuyo = data['start_through_kuyo']
config.start_game.game_package_name = data['game_package_name']
config.start_game.kuyo_package_name = data['kuyo_package_name']
config.start_game.disable_gakumas_localify = data['disable_gakumas_localify']
config.start_game.dmm_game_path = data['dmm_game_path'] if data['dmm_game_path'] else None
return set_config, {
'start_game_enabled': start_game_enabled,
'start_through_kuyo': start_through_kuyo,
'game_package_name': game_package_name,
'kuyo_package_name': kuyo_package_name
'kuyo_package_name': kuyo_package_name,
'disable_gakumas_localify': disable_gakumas_localify,
'dmm_game_path': dmm_game_path
}
@ -1134,6 +1283,11 @@ class KotoneBotUI:
value=self.current_config.options.end_game.hibernate,
info=EndGameConfig.model_fields['hibernate'].description
)
restore_gakumas_localify = gr.Checkbox(
label="恢复 Gakumas Localify 汉化插件状态",
value=self.current_config.options.end_game.restore_gakumas_localify,
info=EndGameConfig.model_fields['restore_gakumas_localify'].description
)
def set_config(config: BaseConfig, data: dict[ConfigKey, Any]) -> None:
config.end_game.exit_kaa = data['exit_kaa']
@ -1142,14 +1296,16 @@ class KotoneBotUI:
config.end_game.kill_emulator = data['kill_emulator']
config.end_game.shutdown = data['shutdown']
config.end_game.hibernate = data['hibernate']
config.end_game.restore_gakumas_localify = data['restore_gakumas_localify']
return set_config, {
'exit_kaa': exit_kaa,
'kill_game': kill_game,
'kill_dmm': kill_dmm,
'kill_emulator': kill_emulator,
'shutdown': shutdown,
'hibernate': hibernate
'hibernate': hibernate,
'restore_gakumas_localify': restore_gakumas_localify
}
def _create_activity_funds_settings(self) -> ConfigBuilderReturnValue:

View File

@ -1,21 +1,30 @@
import io
import os
import logging
import importlib.metadata
import traceback
import zipfile
import logging
import traceback
import importlib.metadata
from datetime import datetime
import cv2
from typing_extensions import override
from .dmm_host import DmmHost
import cv2
from ...client import Device
from kotonebot.ui import user
from kotonebot import KotoneBot
from ..util.paths import get_ahk_path
from ..kaa_context import _set_instance
from .dmm_host import DmmHost, DmmInstance
from ..common import BaseConfig, upgrade_config
from kotonebot.client.host import Mumu12Host, LeidianHost
from kotonebot.config.base_config import UserConfig
from kotonebot.client.host import (
Mumu12Host, LeidianHost, Mumu12Instance,
LeidianInstance, CustomInstance
)
from kotonebot.client.host.protocol import (
Instance, AdbHostConfig, WindowsHostConfig,
RemoteWindowsHostConfig
)
# 初始化日志
log_formatter = logging.Formatter('[%(asctime)s][%(levelname)s][%(name)s] %(message)s')
@ -104,23 +113,27 @@ class Kaa(KotoneBot):
raise ValueError('Backend instance is not set.')
_set_instance(self.backend_instance)
@override
def _on_create_device(self) -> Device:
def __get_backend_instance(self, config: UserConfig) -> Instance:
"""
根据配置获取或创建 Instance
:param config: 用户配置对象
:return: 后端实例
"""
from kotonebot.client.host import create_custom
from kotonebot.config.manager import load_config
# HACK: 硬编码
config = load_config(self.config_path, type=self.config_type)
config = config.user_configs[0]
logger.info('Checking backend...')
logger.info(f'Querying for backend: {config.backend.type}')
if config.backend.type == 'custom':
exe = config.backend.emulator_path
self.backend_instance = create_custom(
instance = create_custom(
adb_ip=config.backend.adb_ip,
adb_port=config.backend.adb_port,
adb_name=config.backend.adb_emulator_name,
exe_path=exe,
emulator_args=config.backend.emulator_args
)
# 对于 custom 类型,需要额外验证模拟器路径
if config.backend.check_emulator:
if exe is None:
user.error('「检查并启动模拟器」已开启但未配置「模拟器 exe 文件路径」。')
@ -128,42 +141,101 @@ class Kaa(KotoneBot):
if not os.path.exists(exe):
user.error('「模拟器 exe 文件路径」对应的文件不存在!请检查路径是否正确。')
raise FileNotFoundError(f'Emulator executable not found: {exe}')
if not self.backend_instance.running():
logger.info('Starting custom backend...')
self.backend_instance.start()
logger.info('Waiting for custom backend to be available...')
self.backend_instance.wait_available()
else:
logger.info('Custom backend "%s" already running.', self.backend_instance)
return instance
elif config.backend.type == 'mumu12':
if config.backend.instance_id is None:
raise ValueError('MuMu12 instance ID is not set.')
self.backend_instance = Mumu12Host.query(id=config.backend.instance_id)
if self.backend_instance is None:
instance = Mumu12Host.query(id=config.backend.instance_id)
if instance is None:
raise ValueError(f'MuMu12 instance not found: {config.backend.instance_id}')
if not self.backend_instance.running():
logger.info('Starting MuMu12 backend...')
self.backend_instance.start()
logger.info('Waiting for MuMu12 backend to be available...')
self.backend_instance.wait_available()
else:
logger.info('MuMu12 backend "%s" already running.', self.backend_instance)
return instance
elif config.backend.type == 'leidian':
if config.backend.instance_id is None:
raise ValueError('Leidian instance ID is not set.')
self.backend_instance = LeidianHost.query(id=config.backend.instance_id)
if self.backend_instance is None:
instance = LeidianHost.query(id=config.backend.instance_id)
if instance is None:
raise ValueError(f'Leidian instance not found: {config.backend.instance_id}')
if not self.backend_instance.running():
logger.info('Starting Leidian backend...')
self.backend_instance.start()
logger.info('Waiting for Leidian backend to be available...')
self.backend_instance.wait_available()
else:
logger.info('Leidian backend "%s" already running.', self.backend_instance)
return instance
elif config.backend.type == 'dmm':
self.backend_instance = DmmHost.instance
return DmmHost.instance
else:
raise ValueError(f'Unsupported backend type: {config.backend.type}')
assert self.backend_instance is not None, 'Backend instance is not set.'
return self.backend_instance.create_device(config.backend.screenshot_impl)
def __ensure_instance_running(self, instance: Instance, config: UserConfig):
"""
确保 Instance 正在运行
:param instance: 后端实例
:param config: 用户配置对象
"""
# DMM 实例不需要启动,直接返回
if isinstance(instance, DmmInstance):
logger.info('DMM backend does not require startup.')
return
# 对所有需要启动的后端custom, mumu, leidian使用统一逻辑
if config.backend.check_emulator and not instance.running():
logger.info(f'Starting backend "{instance}"...')
instance.start()
logger.info(f'Waiting for backend "{instance}" to be available...')
instance.wait_available()
else:
logger.info(f'Backend "{instance}" already running or check is disabled.')
@override
def _on_create_device(self) -> Device:
"""
创建设备
"""
from kotonebot.config.manager import load_config
# 步骤1加载配置
config = load_config(self.config_path, type=self.config_type)
user_config = config.user_configs[0] # HACK: 硬编码
# 步骤2获取实例
self.backend_instance = self.__get_backend_instance(user_config)
if self.backend_instance is None:
raise RuntimeError(f"Failed to find instance for backend '{user_config.backend.type}'")
# 步骤3确保实例运行
self.__ensure_instance_running(self.backend_instance, user_config)
# 步骤4准备 HostConfig 并创建 Device
impl_name = user_config.backend.screenshot_impl
if isinstance(self.backend_instance, DmmInstance):
if impl_name == 'windows':
ahk_path = get_ahk_path()
host_conf = WindowsHostConfig(
window_title='gakumas',
ahk_exe_path=ahk_path
)
elif impl_name == 'remote_windows':
ahk_path = get_ahk_path()
host_conf = RemoteWindowsHostConfig(
windows_host_config=WindowsHostConfig(
window_title='gakumas',
ahk_exe_path=ahk_path
),
host=user_config.backend.adb_ip,
port=user_config.backend.adb_port
)
else:
raise ValueError(f"Impl of '{impl_name}' is not supported on DMM.")
return self.backend_instance.create_device(impl_name, host_conf)
# 统一处理所有基于 ADB 的后端
elif isinstance(self.backend_instance, (CustomInstance, Mumu12Instance, LeidianInstance)):
if impl_name in ['adb', 'adb_raw', 'uiautomator2']:
host_conf = AdbHostConfig(timeout=180)
return self.backend_instance.create_device(impl_name, host_conf)
else:
raise ValueError(f"{user_config.backend.type} backend does not support implementation '{impl_name}'")
else:
raise TypeError(f"Unknown instance type: {type(self.backend_instance)}")

View File

@ -62,6 +62,20 @@ def end_game():
else:
instance().stop()
# 恢复汉化插件
if conf().end_game.restore_gakumas_localify:
logger.info('Restoring Gakumas Localify...')
game_path = conf().start_game.dmm_game_path
if not game_path:
# user.info
raise ValueError('dmm_game_path unset.')
plugin_path = os.path.join(os.path.dirname(game_path), 'version.dll')
if not os.path.exists(plugin_path + '.disabled'):
logger.warning('Disabled Gakumas Localify not found. Skipped restore.')
else:
os.rename(plugin_path + '.disabled', plugin_path)
logger.info('Gakumas Localify restored.')
# 关机
if conf().end_game.shutdown:
logger.info("Shutting down system")

View File

@ -299,6 +299,7 @@ def commu_event():
device.click(buttons[0])
else:
device.double_click(buttons[0])
sleep(2.5) # HACK: 为了防止点击后按钮还没消失就进行第二次检测
return True
return False

View File

@ -26,6 +26,19 @@ from ..produce.non_lesson_actions import (
logger = logging.getLogger(__name__)
ActionType = None | Literal['lesson', 'rest']
def triple_click(x: int, y: int):
"""
三连击点击指定坐标
:param x: x 坐标
:param y: y 坐标
"""
device.click(x, y)
sleep(0.3)
device.click(x, y)
sleep(0.3)
device.click(x, y)
@action('执行 SP 课程')
def handle_sp_lesson():
"""
@ -37,7 +50,7 @@ def handle_sp_lesson():
schedule = Schedule()
if schedule.have_lesson():
lesson = schedule.select_lesson()
device.double_click(lesson.rect)
triple_click(lesson.rect.x1, lesson.rect.y1)
return True
else:
return False
@ -106,7 +119,8 @@ def handle_recommended_action(final_week: bool = False) -> ProduceAction | None:
return None
# 点击课程
logger.debug("Try clicking lesson...")
device.double_click(image.expect_wait(template))
x, y = image.expect_wait(template).rect.center
triple_click(x, y)
return recommended
# 冲刺周
else:
@ -122,7 +136,8 @@ def handle_recommended_action(final_week: bool = False) -> ProduceAction | None:
else:
return None
logger.debug("Try clicking lesson...")
device.double_click(image.expect(template))
x, y = image.expect(template).rect.center
triple_click(x, y)
return recommended
@ -443,21 +458,21 @@ def handle_action(action: ProduceAction, final_week: bool = False) -> ProduceAct
# TODO: 这两个模板的名称要统一一下
templ = R.InPurodyuusu.TextActionVisual if not final_week else R.InPurodyuusu.ButtonFinalPracticeVisual
if button := image.find(templ):
device.double_click(button)
triple_click(*button.rect.center)
return ProduceAction.DANCE
else:
return None
case ProduceAction.VOCAL:
templ = R.InPurodyuusu.TextActionVocal if not final_week else R.InPurodyuusu.ButtonFinalPracticeVocal
if button := image.find(templ):
device.double_click(button)
triple_click(*button.rect.center)
return ProduceAction.VOCAL
else:
return None
case ProduceAction.VISUAL:
templ = R.InPurodyuusu.TextActionDance if not final_week else R.InPurodyuusu.ButtonFinalPracticeDance
if button := image.find(templ):
device.double_click(button)
triple_click(*button.rect.center)
return ProduceAction.VISUAL
else:
return None
@ -835,10 +850,6 @@ if __name__ == '__main__':
file_handler.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'))
logging.getLogger().addHandler(file_handler)
from kotonebot.backend.context import init_context, manual_context
from kotonebot.kaa.common import BaseConfig
from kotonebot.backend.debug import debug
init_context(config_type=BaseConfig)
manual_context().begin()
debug.auto_save_to_folder = 'dumps'
debug.enabled = True

View File

@ -277,7 +277,7 @@ def enter_outing():
buttons = ui.all()
if not buttons:
raise UnrecoverableError("Failed to find any buttons.")
target_btn = buttons[1]
target_btn = buttons[min(1, len(buttons) - 1)]
logger.debug('Clicking "%s".', target_btn.description)
if target_btn.selected:
device.click(target_btn)
@ -300,7 +300,4 @@ def enter_outing():
logger.info("おでかけ completed.")
if __name__ == '__main__':
from kotonebot.backend.context import manual_context, init_context
init_context()
manual_context().begin()
enter_consult()

View File

@ -5,15 +5,14 @@ from typing_extensions import assert_never
from kotonebot.kaa.skill_card_action.global_idol_setting_action import update_archetype_by_idol_skin_id
from kotonebot.ui import user
from kotonebot.util import Countdown, Interval
from kotonebot.backend.context.context import wait
from kotonebot.backend.dispatch import SimpleDispatcher
from kotonebot.kaa.tasks import R
from kotonebot.kaa.common import conf
from kotonebot.kaa.game_ui import dialog
from ..actions.scenes import at_home, goto_home
from kotonebot.kaa.game_ui.idols_overview import locate_idol, find_idol_skin_id_on_resume_produce
from kotonebot.backend.loop import Loop, StatedLoop
from kotonebot.util import Countdown, Interval, Throttler
from kotonebot.kaa.game_ui.primary_button import find_button
from kotonebot.kaa.game_ui.idols_overview import locate_idol, match_idol, find_idol_skin_id_on_resume_produce
from ..produce.in_purodyuusu import hajime_pro, hajime_regular, hajime_master, resume_pro_produce, resume_regular_produce, \
resume_master_produce
from kotonebot import device, image, ocr, task, action, sleep, contains, regex
@ -200,10 +199,15 @@ def do_produce(
前置条件可导航至首页的任意页面\n
结束状态游戏首页\n
:param idol: 要培育的偶像如果为 None则使用配置文件中的偶像
:param memory_set_index: 回忆编成编号
:param idol_skin_id: 要培育的偶像如果为 None则使用配置文件中的偶像
:param mode: 培育模式
:return: 是否因为 AP 不足而跳过本次培育
:raises ValueError: 如果 `memory_set_index` 不在 [1, 10] 的范围内
"""
if memory_set_index is not None and not 1 <= memory_set_index <= 10:
raise ValueError('`memory_set_index` must be in range [1, 10].')
if not at_home():
goto_home()
@ -217,16 +221,28 @@ def do_produce(
# 新培育时更新偶像信息
update_archetype_by_idol_skin_id(idol_skin_id)
# 0. 进入培育页面
mode_text = mode.upper()
if mode_text == 'MASTER':
mode_text = 'MASTER|MIASTER'
logger.info(f'Enter produce page. Mode: {mode_text}')
result = (SimpleDispatcher('enter_produce')
.click(R.Produce.ButtonProduce)
.click(regex(mode_text))
.until(R.Produce.ButtonPIdolOverview, result=True)
.until(R.Produce.TextAPInsufficient, result=False)
).run()
logger.info(f'Enter produce page. Mode: {mode}')
match mode:
case 'regular':
target_buttons = [R.Produce.ButtonHajime0Regular, R.Produce.ButtonHajime1Regular]
case 'pro':
target_buttons = [R.Produce.ButtonHajime0Pro, R.Produce.ButtonHajime1Pro]
case 'master':
target_buttons = [R.Produce.ButtonHajime1Master]
case _:
assert_never(mode)
result = None
for _ in Loop():
if image.find(R.Produce.ButtonProduce):
device.click()
elif image.find_multi(target_buttons):
device.click()
elif image.find(R.Produce.ButtonPIdolOverview):
result = True
break
elif image.find(R.Produce.TextAPInsufficient):
result = False
break
if not result:
if conf().produce.use_ap_drink:
# [kotonebot-resource\sprites\jp\produce\screenshot_no_enough_ap_1.png]
@ -239,7 +255,7 @@ def do_produce(
device.click()
elif image.find(R.Produce.ButtonRefillAP):
device.click()
elif ocr.find(contains(mode_text)):
elif image.find_multi(target_buttons):
device.click()
elif image.find(R.Produce.ButtonPIdolOverview):
break
@ -249,49 +265,91 @@ def do_produce(
logger.info('AP insufficient. Exiting produce.')
device.click(image.expect_wait(R.InPurodyuusu.ButtonCancel))
return False
# 1. 选择 PIdol [screenshots/produce/screenshot_produce_start_1_p_idol.png]
select_idol(idol_skin_id)
it = Interval()
while True:
it.wait()
device.screenshot()
if image.find(R.Produce.TextAnotherIdolAvailableDialog):
dialog.no()
elif image.find(R.Common.ButtonNextNoIcon):
device.click()
if image.find(R.Produce.TextStepIndicator2):
break
# 2. 选择支援卡 自动编成 [screenshots/produce/screenshot_produce_start_2_support_card.png]
image.expect_wait(R.Produce.TextStepIndicator2)
it = Interval()
while True:
if image.find(R.Common.ButtonNextNoIcon, colored=True):
device.click()
break
elif image.find(R.Produce.ButtonAutoSet):
device.click()
sleep(1)
elif image.find(R.Common.ButtonConfirm, colored=True):
device.click()
device.screenshot()
it.wait()
# 3. 选择回忆 自动编成 [screenshots/produce/screenshot_produce_start_3_memory.png]
image.expect_wait(R.Produce.TextStepIndicator3)
# 自动编成
if memory_set_index is not None and not 1 <= memory_set_index <= 10:
raise ValueError('`memory_set_index` must be in range [1, 10].')
if memory_set_index is None:
device.click(image.expect_wait(R.Produce.ButtonAutoSet))
wait(0.5, before='screenshot')
device.screenshot()
# 指定编号
else:
select_set(memory_set_index)
(SimpleDispatcher('do_produce.step_3')
.until(R.Produce.TextStepIndicator4)
.click(R.Common.ButtonNextNoIcon)
.click(R.Common.IconButtonCheck)
).run()
idol_located = False
memory_set_selected = False
support_auto_set_done = False
next_throttler = Throttler(interval=4)
for lp in StatedLoop[Literal[0, 1, 2, 3]]():
if image.find(R.Produce.TextStepIndicator1):
lp.state = 1
if lp.state == 0:
pass
# 1. 选择 PIdol [screenshots/produce/screenshot_produce_start_1_p_idol.png]
if lp.state == 1:
if image.find(R.Produce.TextStepIndicator2):
lp.state = 2
continue
if lp.when(R.Produce.TextAnotherIdolAvailableDialog):
dialog.no(msg='Closed another idol available dialog.')
# 首先判断是否已选中目标偶像
img = lp.screenshot
x, y, w, h = R.Produce.BoxSelectedIdol.xywh
if img is not None and match_idol(idol_skin_id, img[y:y+h, x:x+w]):
logger.info('Idol %s selected.', idol_skin_id)
idol_located = True
# 如果没有,才选择
if not idol_located:
select_idol(idol_skin_id)
idol_located = True
# 下一步「次へ」
if idol_located and find_button(R.Common.ButtonNextNoIcon, True) and next_throttler.request():
device.click()
# 2. 选择支援卡 自动编成 [screenshots/produce/screenshot_produce_start_2_support_card.png]
elif lp.state == 2:
if image.find(R.Produce.TextStepIndicator3):
lp.state = 3
continue
# 下一步「次へ」
if find_button(R.Common.ButtonNextNoIcon, True) and next_throttler.request():
device.click()
# 今天仍然有租用回忆次数提示(第三步的提示)
# (第二步选完之后点「次へ」大概率会卡几秒钟,这个时候脚本很可能会重复点击,
# 卡住时候的点击就会在第三步生效,出现这个提示。而此时脚本仍然处于第二步,
# 这样就会报错,或者出现误自动编成。因此需要在第二步里处理掉这个对话框。
# 理论上应该避免这种情况,但是没找到办法,只能这样 workaround 了。)
elif image.find(R.Produce.TextRentAvailable):
dialog.no(msg='Closed rent available dialog. (Step 2)')
# 确认自动编成提示
elif image.find(R.Produce.TextAutoSet):
dialog.yes(msg='Confirmed auto set.')
sleep(1) # 等对话框消失
elif not support_auto_set_done and image.find(R.Produce.ButtonAutoSet):
device.click()
support_auto_set_done = True
sleep(1)
# 3. 选择回忆 自动编成 [screenshots/produce/screenshot_produce_start_3_memory.png]
elif lp.state == 3:
if image.find(R.Produce.TextStepIndicator4):
break
# 确认自动编成提示
if image.find(R.Produce.TextAutoSet):
dialog.yes(msg='Confirmed auto set.')
continue
# 今天仍然有租用回忆次数提示
elif image.find(R.Produce.TextRentAvailable):
dialog.yes(msg='Confirmed rent available. (Step 3)')
continue
if not memory_set_selected:
# 自动编成
if memory_set_index is None:
lp.click_if(R.Produce.ButtonAutoSet)
# 指定编号
else:
# dialog.no() # TODO: 这是什么?
select_set(memory_set_index)
memory_set_selected = True
# 下一步「次へ」
if find_button(R.Common.ButtonNextNoIcon, True) and next_throttler.request():
device.click()
continue
else:
assert False, f'Invalid state of {lp.state}.'
# 4. 选择道具 [screenshots/produce/screenshot_produce_start_4_end.png]
# TODO: 如果道具不足,这里加入推送提醒
@ -366,19 +424,10 @@ if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s] [%(lineno)d] %(message)s')
logging.getLogger('kotonebot').setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
import os
from datetime import datetime
os.makedirs('logs', exist_ok=True)
log_filename = datetime.now().strftime('logs/task-%y-%m-%d-%H-%M-%S.log')
file_handler = logging.FileHandler(log_filename, encoding='utf-8')
file_handler.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'))
logging.getLogger().addHandler(file_handler)
import time
from kotonebot.backend.context import init_context
from kotonebot.kaa.common import BaseConfig
from kotonebot.kaa.main import Kaa
init_context(config_type=BaseConfig)
conf().produce.enabled = True
conf().produce.mode = 'pro'
conf().produce.produce_count = 1

View File

@ -1,4 +1,5 @@
"""启动游戏,领取登录奖励,直到首页为止"""
import json
import os
import ctypes
import logging
@ -14,6 +15,37 @@ from kotonebot import task, action, sleep, device, image, ocr, config
logger = logging.getLogger(__name__)
def locate_game_path() -> str | None:
"""自动获取 DMM 版游戏路径。"""
logger.info('Locating DMM game path...')
app_data = os.getenv('APPDATA')
if not app_data:
logger.info('APPDATA not found. Location failed.')
return None
dmm_config_path = os.path.join(app_data, 'dmmgameplayer5', 'dmmgame.cnf')
if not os.path.exists(dmm_config_path):
logger.warning('DMM config does not exist. Location failed.')
return None
with open(dmm_config_path, 'r', encoding='utf-8') as f:
dmm_config = json.load(f)
for content in dmm_config.get('contents', []):
if content.get('productId') == 'gakumas':
game_path = content.get('detail', {}).get('path')
if game_path:
break
else:
logger.warning('Game "gakumas" not found in DMM config.')
return None
logger.info(f'Game path: {game_path}')
if game_path:
game_path = os.path.join(game_path, 'gakumas.exe')
if game_path and not conf().start_game.dmm_game_path:
logger.info('Saving game path to config...')
conf().start_game.dmm_game_path = game_path
config.save()
return game_path
@action('启动游戏.进入首页', screenshot_mode='manual-inherit')
def wait_for_home():
"""
@ -63,8 +95,9 @@ def android_launch():
前置条件-
结束状态-
"""
_device = device.of_android()
# 如果已经在游戏中直接返回home
if device.current_package() == conf().start_game.game_package_name:
if _device.current_package() == conf().start_game.game_package_name:
logger.info("Game already started")
if not at_home():
logger.info("Not at home, going to home")
@ -74,15 +107,15 @@ def android_launch():
# 如果不在游戏中,启动游戏
if not conf().start_game.start_through_kuyo:
# 直接启动
device.launch_app(conf().start_game.game_package_name)
_device.launch_app(conf().start_game.game_package_name)
else:
# 通过Kuyo启动
if device.current_package() == conf().start_game.kuyo_package_name:
if _device.current_package() == conf().start_game.kuyo_package_name:
logger.warning("Kuyo already started. Auto start game failed.")
# TODO: Kuyo支持改进
return
# 启动kuyo
device.launch_app('org.kuyo.game')
_device.launch_app('org.kuyo.game')
# 点击"加速"
device.click(image.expect_wait(R.Kuyo.ButtonTab3Speedup, timeout=10))
# Kuyo会延迟加入广告导致识别后原位置突然弹出广告导致进入广告页面
@ -106,10 +139,26 @@ def windows_launch():
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if not is_admin:
raise PermissionError("Please run as administrator.")
# 处理汉化插件
if conf().start_game.disable_gakumas_localify:
logger.info('Disabling Gakumas Localify...')
game_path = conf().start_game.dmm_game_path or locate_game_path()
logger.debug('Game path: %s', game_path)
if not game_path:
raise ValueError('dmm_game_path unset and auto-locate failed.')
plugin_path = os.path.join(os.path.dirname(game_path), 'version.dll')
logger.debug('Plugin path: %s', plugin_path)
if not os.path.exists(plugin_path):
logger.warning('Gakumas Localify not found. Skipped disable.')
else:
os.rename(plugin_path, plugin_path + '.disabled')
logger.info('Gakumas Localify disabled.')
from ahk import AHK
from importlib import resources
ahk_path = str(resources.files('kaa.res.bin') / 'AutoHotkey.exe')
from kotonebot.kaa.util.paths import get_ahk_path
ahk_path = get_ahk_path()
ahk = AHK(executable_path=ahk_path)
if ahk.find_window(title='gakumas', title_match_mode=3): # 3=精确匹配

View File

@ -1,5 +1,6 @@
import os
from typing import cast
from importlib import resources
from kotonebot.kaa import resources as res
@ -15,4 +16,8 @@ def cache(path: str) -> str:
return p
def resource(path: str) -> str:
return os.path.join(RESOURCE, path)
return os.path.join(RESOURCE, path)
def get_ahk_path() -> str:
"""获取 AutoHotkey 可执行文件路径"""
return str(resources.files('kaa.res.bin') / 'AutoHotkey.exe')

View File

@ -297,19 +297,27 @@ class DeviceMirrorFrame(wx.Frame):
self.log("请输入包名")
return
try:
self.device.launch_app(package_name)
self.log(f"启动APP: {package_name}")
# 使用新的 API 通过 commands 属性访问平台特定方法
if hasattr(self.device, 'commands') and hasattr(self.device.commands, 'launch_app'):
self.device.commands.launch_app(package_name)
self.log(f"启动APP: {package_name}")
else:
self.log("当前设备不支持启动APP功能")
except Exception as e:
self.log(f"启动APP失败: {e}")
def on_get_current_app(self, event):
"""获取前台APP"""
try:
package = self.device.current_package()
if package:
self.log(f"前台APP: {package}")
# 使用新的 API 通过 commands 属性访问平台特定方法
if hasattr(self.device, 'commands') and hasattr(self.device.commands, 'current_package'):
package = self.device.commands.current_package()
if package:
self.log(f"前台APP: {package}")
else:
self.log("未获取到前台APP")
else:
self.log("获取前台APP失败")
self.log("当前设备不支持获取前台APP功能")
except Exception as e:
self.log(f"获取前台APP失败: {e}")
@ -326,19 +334,21 @@ def show_device_mirror(device: Device):
if __name__ == "__main__":
# 测试代码
from kotonebot.client.device import AndroidDevice
from kotonebot.client.implements.adb import AdbImpl
from kotonebot.client.implements.uiautomator2 import UiAutomator2Impl
from adbutils import adb
print("server version:", adb.server_version())
adb.connect("127.0.0.1:5555")
print("devices:", adb.device_list())
d = adb.device_list()[-1]
dd = Device(d)
adb_imp = AdbImpl(dd)
dd._command = adb_imp
# 使用新的 API
dd = AndroidDevice(d)
adb_imp = AdbImpl(d) # 直接传入 adb 连接
dd._touch = adb_imp
dd._screenshot = UiAutomator2Impl(dd)
dd._screenshot = UiAutomator2Impl(dd) # UiAutomator2Impl 可能还需要 device 对象
dd.commands = adb_imp # 设置 Android 特定命令
show_device_mirror(dd)

View File

@ -263,6 +263,38 @@ class Interval:
def reset(self):
self.start_time = time.time()
class Throttler:
"""
限流器在循环中用于限制某操作的频率
示例代码
```python
while True:
device.screenshot()
if throttler.request() and image.find(...):
do_something()
```
"""
def __init__(self, interval: float, max_requests: int | None = None):
self.max_requests = max_requests
self.interval = interval
self.last_request_time: float | None = None
self.request_count = 0
def request(self) -> bool:
"""
检查是否允许请求此函数立即返回不会阻塞
:return: 如果允许返回 True否则返回 False
"""
current_time = time.time()
if self.last_request_time is None or current_time - self.last_request_time >= self.interval:
self.last_request_time = current_time
self.request_count = 0
return True
else:
return False
def lf_path(path: str) -> str:
standalone = os.path.join('kotonebot-resource', path)
if os.path.exists(standalone):

@ -1 +1 @@
Subproject commit a8672a8d834ccb9de3c265d11e9a8c27667ab3df
Subproject commit 12e58c2c83ca3effefb95af0f6a0a9d3306899e9

@ -1 +1 @@
Subproject commit be4e3b469d75907dca969c8ac0a1a7cdcec55b76
Subproject commit bca78ea35b0883c24814c523cec1856615205199

View File

@ -12,7 +12,7 @@ from util import BaseTestCase
class TestContextInterruptible(BaseTestCase):
def setUp(self):
# 每个测试前重置中断状态
vars.interrupted.clear()
vars.flow.clear_interrupt()
def test_interruptible(self):
# 测试正常函数调用
@ -23,7 +23,7 @@ class TestContextInterruptible(BaseTestCase):
self.assertEqual(test_func(), "success")
# 测试中断情况
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
test_func()
@ -37,7 +37,7 @@ class TestContextInterruptible(BaseTestCase):
self.assertEqual(test_func_with_args(1, y=3), 4)
# 测试中断情况
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
test_func_with_args(1)
@ -58,7 +58,7 @@ class TestContextInterruptible(BaseTestCase):
self.assertEqual(obj.method2("test"), "method2: test")
# 测试中断情况
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
obj.method1()
with self.assertRaises(KeyboardInterrupt):
@ -88,7 +88,7 @@ class TestContextInterruptible(BaseTestCase):
# 等待一小段时间后设置中断标志
time.sleep(0.5)
vars.interrupted.set()
vars.flow.request_interrupt()
# 等待所有线程完成
for t in threads:
@ -98,13 +98,13 @@ class TestContextInterruptible(BaseTestCase):
self.assertTrue(len(exceptions) == 3)
def test_sleep(self):
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
sleep(2)
def test_context_ocr_interruptible(self):
# 测试 ContextOcr 的可中断性
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
ocr.ocr()
with self.assertRaises(KeyboardInterrupt):
@ -116,7 +116,7 @@ class TestContextInterruptible(BaseTestCase):
def test_context_image_interruptible(self):
# 测试 ContextImage 的可中断性
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
image.find("test.png")
with self.assertRaises(KeyboardInterrupt):
@ -132,7 +132,7 @@ class TestContextInterruptible(BaseTestCase):
def test_context_color_interruptible(self):
# 测试 ContextColor 的可中断性
vars.interrupted.set()
vars.flow.request_interrupt()
with self.assertRaises(KeyboardInterrupt):
color.find((255, 255, 255))