├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── assets ├── 404.png ├── abyss.png ├── abyss_greedy.png ├── backgroud_godwar.png ├── backgroud_no_godwar.png ├── bf.png ├── chara.png ├── equipment_0.png ├── equipment_2.png ├── equipment_3.png ├── equipment_4.png ├── equipment_5.png ├── equipment_6.png ├── example.png ├── example_finance.png ├── example_valk.png ├── finance.png ├── font │ ├── HYLingXinTiJ.ttf │ ├── HYWenHei-65W.ttf │ ├── HYWenHei-85W.ttf │ └── sarasa-ui-sc-semibold.ttf ├── header.png ├── no-data.png ├── no-data2.png └── star │ ├── 1.png │ ├── 1_of_2.png │ ├── 2.png │ ├── 2_of_2.png │ ├── 2_of_3.png │ ├── 3.png │ ├── 3_of_3.png │ ├── 3_of_4.png │ ├── 4.png │ ├── 4_of_4.png │ ├── 4_of_5.png │ ├── 5.png │ ├── 5_of_5.png │ ├── 6_of_6.png │ ├── a.png │ ├── b.png │ ├── s.png │ ├── ss.png │ ├── sss.png │ ├── 星.png │ └── 灰星.png ├── autosign ├── README.md ├── __init__.py └── mysign.py ├── config_example.yaml ├── guess_voice ├── __init__.py ├── answer_template.json ├── game.py └── readme.md ├── modules ├── __init__.py ├── database.py ├── image_handle.py ├── mytyping.py ├── query.py └── util.py ├── region.json └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | .idea/ 153 | .vscode 154 | config.json 155 | data/* 156 | example.db 157 | config.yaml 158 | test.py 159 | assets/AvatarCardFigures/* 160 | assets/AvatarCardIcons/* 161 | assets/AvatarIcon/* 162 | assets/ElfCardIcons/* 163 | assets/QuestBossIcon/* 164 | assets/StigmataIcons/* 165 | assets/WeaponIcons/* 166 | assets/record/* 167 | guess_voice/record.json 168 | guess_voice/answer.json 169 | autosign/sign_on.json 170 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 崩坏3米游社查询 2 | 仿[egenshin的player_info](https://github.com/pcrbot/erinilis-modules/tree/master/egenshin/player_info)样式做的崩坏3角色卡片. 3 | - [崩坏3米游社查询](#崩坏3米游社查询) 4 | - [安装](#安装) 5 | - [使用](#使用) 6 | - [更新日志](#更新日志) 7 | - [2022/3/31](#2022331) 8 | - [2022/3/17](#2022317) 9 | - [2022/2/16](#2022216) 10 | - [2022/2/13](#2022213) 11 | - [2022/1/28](#2022128) 12 | - [2022/1/23](#2022123) 13 | - [致谢](#致谢) 14 | ## 安装 15 | - 在hoshino的modules文件夹下clone本仓库 16 | ``` bash 17 | git clone https://github.com/chingkingm/honkai_mys.git 18 | ``` 19 | - 安装依赖 20 | ``` bash 21 | pip install -r requirements.txt 22 | ``` 23 | - 重命名 `config_example.yaml` 为 `config.yaml`,并按照格式填入cookie 24 | - 配置语音资源 25 | - 前往[B站视频](https://www.bilibili.com/video/BV16J41157du),根据简介下载语音文件 26 | - 完全解压后放到./assets/record文件夹下 27 | - ps:5.5版本有一个语音命名有问题,参照[说明](./guess_voice/readme.md)进行重命名 28 | - 按需[配置](./autosign/README.md)邮箱 29 | - 修改__bot__.py,加入插件,重启bot 30 | 31 | ## 使用 32 | | 命令 | 功能 | 备注 | 33 | | ---------------------- | ---------------------------- | ---------------------- | 34 | | bh# | 玩家卡片 | 35 | | bhv# | 所有女武神 | 36 | | bhf | 手账 | 不需要uid | 37 | | 崩坏3猜语音 | 正常语音 | 38 | | 崩坏3猜语音困难 | 语气及拟声词 | 39 | | 崩坏3语音+名字 | 随机发送指定角色或人偶的语音 | 40 | | 更新崩坏3语音列表 | | 首次或语音更新后使用 | 41 | | 开启/关闭崩坏3自动签到 | | 开启后每天定时自动签到 | 42 | | 崩坏3自动签到 | | 手动触发签到 | 43 | 1. 通过游戏uid加服务器查询 44 | - `命令<服务器>`,如`bh#100074751b`. 45 | 2. 通过米游社id查询 46 | - `命令<米游社>`,即在提供米游社ID的同时加上"米游社"或"mys",如`bh#75098978米游社` 47 | 3. 不提供id 48 | - `命令`,会查询用户上一次查询的UID信息,如`bh#` 49 | 50 | ps:每个uid只有首次查询的时候需要提供服务器. 51 | 52 |
53 | 玩家卡片示意图 54 | 55 | ![image](./assets/example.png) 56 | 57 |
58 | 59 |
60 | 女武神卡片示意图 61 | 62 | ![image](./assets/example_valk.png) 63 | 64 |
65 | 66 |
67 | 手账示意图 68 | 69 | ![alt](./assets/example_finance.png) 70 | 71 |
72 | 73 | ## 更新日志 74 | ### 2022/3/31 75 | 1. 新增米游社福利补给自动签到[#26](https://github.com/chingkingm/honkai_mys/issues/26) 76 | 1. 开启后每日4:10或16:10自动执行签到 77 | 2. 签到结果通过私聊发送,如果未添加bot好友,则通过邮件发送(需要[配置smtp](./autosign/README.md),不配置或不可用则发送给SUPERUSER) 78 | ### 2022/3/17 79 | 1. 适配乐土、量子流形改动 80 | 2. 调整代码结构 81 | 3. fix:角色卡片右上角UID超出图片的问题 82 | 4. 超弦空间加杯时显示+号 83 | ### 2022/2/16 84 | 1. 更改了女武神卡片的样式,增加了抬头 85 | 2. 调整了装备星级图片的逻辑,现在会保存图片以重复使用 86 | ### 2022/2/13 87 | 1. 新增猜语音,发送指定角色语音 88 | 1. 初次使用前或资源更新后,发送`更新崩坏3语音列表`以生成或更新语音列表 89 | 2. 语音的分类有些粗犷,会出现例如缭乱星棘不是丽塔这种问题,可以自行调整answer.json或使用`崩坏3语音新增答案缭乱星棘:丽塔`进行添加。 90 | ### 2022/1/28 91 | 1. 新增查询手账 92 | 1. 支持使用egenshin已绑定的cookie,需要在config中填写配置,详见[config_example.yaml](config_example.yaml) 93 | 2. 支持单独绑定,发送`bhf?`获取帮助 94 | ### 2022/1/23 95 | 1. 新增查询所有女武神,命令为`bhv#`,注意:第一次生成图片时,因为要下载圣痕,武器的素材,所以耗费的时间较长,可以下载release里的压缩包来减少届时的下载延迟 96 | 2. 调整了部分导入,方便调试 97 | 3. 新增了水晶手账相关代码,但具体样式未实现,该功能不可用 98 | 4. 更新了README,加入了更新日志 99 | 5. 完善渠道信息 100 | 6. 优化初次查询时的报错信息 101 | ## 致谢 102 | - [egenshin](https://github.com/pcrbot/erinilis-modules/tree/master/egenshin),用了部分艾琳佬造好的轮子 103 | - [YSJS有所建树](https://space.bilibili.com/402667766)整理的语音素材 104 | - [genshinhelper2](https://github.com/y1ndan/genshinhelper2) 105 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | 4 | from hoshino import HoshinoBot, Service, get_bot 5 | from hoshino.typing import CQEvent, MessageSegment 6 | 7 | from .modules.database import DB 8 | from .modules.image_handle import (DrawCharacter, DrawFinance, DrawIndex, 9 | ItemTrans) 10 | from .modules.mytyping import Index 11 | from .modules.query import Finance, GetInfo, InfoError 12 | from .modules.util import NotBindError 13 | 14 | _help = """ 15 | [bh#uid服务器]:查询角色卡片 16 | [bhv#uid服务器]:查询拥有的女武神 17 | [bhf]:查询手账 18 | """ 19 | _bot = get_bot() 20 | sv = Service( 21 | "崩坏3角色卡片", enable_on_default=True, visible=True, bundle="崩坏3", help_=_help 22 | ) 23 | 24 | 25 | def handle_id(ev: CQEvent): 26 | msg = ev.message.extract_plain_text().strip() 27 | qid = str(ev.user_id) 28 | for mes in ev.message: 29 | if mes.type == "at": 30 | qid = mes.data["qq"] 31 | region_db = DB("uid.sqlite", tablename="uid_region") 32 | qid_db = DB("uid.sqlite", tablename="qid_uid") 33 | role_id = re.search(r"\d{1,}", msg) 34 | region_name = re.search(r"\D{1,}\d?", msg) 35 | if re.search(r"[mM][yY][sS]|米游社", msg): 36 | spider = GetInfo(mysid=role_id.group()) 37 | region_id, role_id = spider.mys2role(spider.getrole) 38 | elif role_id is None: 39 | try: 40 | role_id = qid_db.get_uid_by_qid(qid) 41 | region_id = region_db.get_region(role_id) 42 | except KeyError: 43 | raise InfoError( 44 | "请在原有指令后面输入游戏uid及服务器,只需要输入一次就会记住下次直接使用bh#获取就好\n例如:bh#100074751官服" 45 | ) 46 | elif role_id is not None and region_name is None: 47 | region_id = region_db.get_region(role_id.group()) 48 | if not region_id: 49 | raise InfoError( 50 | f"{role_id.group()}为首次查询,请输入服务器名称.如:bh#100074751官服") 51 | else: 52 | try: 53 | region_id = ItemTrans.server2id(region_name.group()) 54 | except InfoError as e: 55 | raise InfoError(str(e)) 56 | now_region_id = region_db.get_region(role_id.group()) 57 | if now_region_id is not None and now_region_id != region_id: 58 | raise InfoError( 59 | f"服务器信息与uid不匹配,可联系管理员修改." 60 | ) # 输入的服务器与数据库中保存的不一致,可手动delete该条数据 61 | role_id = role_id if isinstance(role_id, str) else role_id.group() 62 | return role_id, region_id, qid 63 | 64 | 65 | @sv.on_prefix("bh#") 66 | async def bh3_player_card(bot: HoshinoBot, ev: CQEvent): 67 | region_db = DB("uid.sqlite", tablename="uid_region") 68 | qid_db = DB("uid.sqlite", tablename="qid_uid") 69 | try: 70 | role_id, region_id, qid = handle_id(ev) 71 | except InfoError as e: 72 | await bot.send(ev, str(e), at_sender=True) 73 | return 74 | spider = GetInfo(server_id=region_id, role_id=role_id) 75 | try: 76 | ind = await spider.part() 77 | except InfoError as e: 78 | await bot.send(ev, str(e)) 79 | return 80 | await bot.send(ev, MessageSegment.reply(ev.message_id) + "制图中,请稍后") 81 | region_db.set_region(role_id, region_id) 82 | qid_db.set_uid_by_qid(qid, role_id) 83 | ind = DrawIndex(**ind) 84 | im = await ind.draw_card(qid) 85 | img = MessageSegment.image(im) 86 | await bot.send(ev, img, at_sender=True) 87 | 88 | 89 | @sv.on_prefix("bhv#") 90 | async def bh3_chara_card(bot: HoshinoBot, ev: CQEvent): 91 | region_db = DB("uid.sqlite", tablename="uid_region") 92 | qid_db = DB("uid.sqlite", tablename="qid_uid") 93 | try: 94 | role_id, region_id, qid = handle_id(ev) 95 | except InfoError as e: 96 | await bot.send(ev, str(e), at_sender=True) 97 | return 98 | spider = GetInfo(role_id=role_id, server_id=region_id) 99 | try: 100 | _, data = await spider.fetch(spider.valkyrie) 101 | _, index_data = await spider.fetch(spider.index) 102 | except InfoError as e: 103 | await bot.send(ev, str(e), at_sender=True) 104 | return 105 | await bot.send(ev, MessageSegment.reply(ev.message_id) + "制图中,请稍后") 106 | region_db.set_region(role_id, region_id) 107 | qid_db.set_uid_by_qid(qid, role_id) 108 | index = Index(**index_data["data"]) 109 | dr = DrawCharacter(**data["data"]) 110 | im = await dr.draw_chara(index, qid) 111 | img = MessageSegment.image(im) 112 | await bot.send(ev, img, at_sender=True) 113 | return 114 | 115 | 116 | @sv.on_prefix(("bhf", "手账", "水晶手账")) 117 | async def show_finance(bot: HoshinoBot, ev: CQEvent): 118 | qid = ev.user_id 119 | msg = ev.message.extract_plain_text().strip() 120 | if msg.startswith("绑定"): 121 | try: 122 | await bot.delete_msg(message_id=ev.message_id) 123 | ret = "" 124 | except: 125 | ret = "请撤回!" 126 | await bot.send(ev, f"{ret}不支持在群内绑定,请添加bot好友后私聊绑定。", at_sender=True) 127 | return 128 | elif "?" in msg or "?" in msg: 129 | ret = NotBindError.msg2 if "2" in msg else NotBindError.msg 130 | await bot.send(ev, ret, at_sender=True) 131 | return 132 | else: 133 | try: 134 | spider = Finance(str(qid)) 135 | except InfoError as e: 136 | await bot.send(ev, f"{e}", at_sender=True) 137 | return 138 | fi = await spider.get_finance() 139 | fid = DrawFinance(**fi) 140 | im = fid.draw() 141 | await bot.send(ev, f"{MessageSegment.image(im)}") 142 | return 143 | 144 | 145 | @_bot.on_message("private") 146 | async def bindcookie(ev: CQEvent): 147 | msg = ev["raw_message"] 148 | sid = int(ev["self_id"]) 149 | qid = int(ev["sender"]["user_id"]) 150 | cmd = re.match(r"(bhf|手账|水晶手账)绑定", msg) 151 | if not cmd: 152 | return 153 | sv.logger.info( 154 | f"Private Message {ev.message_id} triggered {sys._getframe().f_code.co_name}" 155 | ) 156 | cookieraw: str = re.split(cmd.group(), msg)[1].strip() 157 | try: 158 | spider = Finance(qid=qid, cookieraw=cookieraw) 159 | except InfoError as e: 160 | await _bot.send_private_msg(user_id=qid, message=f"{e}", self_id=sid) 161 | return 162 | fi = await spider.get_finance() 163 | fid = DrawFinance(**fi) 164 | im = fid.draw() 165 | await _bot.send_private_msg( 166 | user_id=qid, message=MessageSegment.image(im), self_id=sid 167 | ) 168 | return 169 | -------------------------------------------------------------------------------- /assets/404.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/404.png -------------------------------------------------------------------------------- /assets/abyss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/abyss.png -------------------------------------------------------------------------------- /assets/abyss_greedy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/abyss_greedy.png -------------------------------------------------------------------------------- /assets/backgroud_godwar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/backgroud_godwar.png -------------------------------------------------------------------------------- /assets/backgroud_no_godwar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/backgroud_no_godwar.png -------------------------------------------------------------------------------- /assets/bf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/bf.png -------------------------------------------------------------------------------- /assets/chara.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/chara.png -------------------------------------------------------------------------------- /assets/equipment_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/equipment_0.png -------------------------------------------------------------------------------- /assets/equipment_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/equipment_2.png -------------------------------------------------------------------------------- /assets/equipment_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/equipment_3.png -------------------------------------------------------------------------------- /assets/equipment_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/equipment_4.png -------------------------------------------------------------------------------- /assets/equipment_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/equipment_5.png -------------------------------------------------------------------------------- /assets/equipment_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/equipment_6.png -------------------------------------------------------------------------------- /assets/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/example.png -------------------------------------------------------------------------------- /assets/example_finance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/example_finance.png -------------------------------------------------------------------------------- /assets/example_valk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/example_valk.png -------------------------------------------------------------------------------- /assets/finance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/finance.png -------------------------------------------------------------------------------- /assets/font/HYLingXinTiJ.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/font/HYLingXinTiJ.ttf -------------------------------------------------------------------------------- /assets/font/HYWenHei-65W.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/font/HYWenHei-65W.ttf -------------------------------------------------------------------------------- /assets/font/HYWenHei-85W.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/font/HYWenHei-85W.ttf -------------------------------------------------------------------------------- /assets/font/sarasa-ui-sc-semibold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/font/sarasa-ui-sc-semibold.ttf -------------------------------------------------------------------------------- /assets/header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/header.png -------------------------------------------------------------------------------- /assets/no-data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/no-data.png -------------------------------------------------------------------------------- /assets/no-data2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/no-data2.png -------------------------------------------------------------------------------- /assets/star/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/1.png -------------------------------------------------------------------------------- /assets/star/1_of_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/1_of_2.png -------------------------------------------------------------------------------- /assets/star/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/2.png -------------------------------------------------------------------------------- /assets/star/2_of_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/2_of_2.png -------------------------------------------------------------------------------- /assets/star/2_of_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/2_of_3.png -------------------------------------------------------------------------------- /assets/star/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/3.png -------------------------------------------------------------------------------- /assets/star/3_of_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/3_of_3.png -------------------------------------------------------------------------------- /assets/star/3_of_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/3_of_4.png -------------------------------------------------------------------------------- /assets/star/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/4.png -------------------------------------------------------------------------------- /assets/star/4_of_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/4_of_4.png -------------------------------------------------------------------------------- /assets/star/4_of_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/4_of_5.png -------------------------------------------------------------------------------- /assets/star/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/5.png -------------------------------------------------------------------------------- /assets/star/5_of_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/5_of_5.png -------------------------------------------------------------------------------- /assets/star/6_of_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/6_of_6.png -------------------------------------------------------------------------------- /assets/star/a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/a.png -------------------------------------------------------------------------------- /assets/star/b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/b.png -------------------------------------------------------------------------------- /assets/star/s.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/s.png -------------------------------------------------------------------------------- /assets/star/ss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/ss.png -------------------------------------------------------------------------------- /assets/star/sss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/sss.png -------------------------------------------------------------------------------- /assets/star/星.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/星.png -------------------------------------------------------------------------------- /assets/star/灰星.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/assets/star/灰星.png -------------------------------------------------------------------------------- /autosign/README.md: -------------------------------------------------------------------------------- 1 | 签到人不是bot好友时才会用到邮箱,如果确定用不到可以不填 2 | ## QQ邮箱 3 | - 设置 - 账户 - `POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务` 4 | - 开启`POP3/SMTP服务` 5 | - 生成授权码 6 | ![im](https://raw.githubusercontent.com/chingkingm/picgo/main/img/20220331112627.png) 7 | - 填到config.yaml -------------------------------------------------------------------------------- /autosign/__init__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | import os 4 | from datetime import datetime 5 | from email.header import Header 6 | from email.mime.text import MIMEText 7 | from email.utils import formataddr, parseaddr 8 | from smtplib import SMTP_SSL 9 | 10 | from genshinhelper import Honkai3rd 11 | from genshinhelper.exceptions import GenshinHelperException 12 | from hoshino import Service, priv 13 | from hoshino.config import SUPERUSERS 14 | from hoshino.typing import CQEvent, HoshinoBot, MessageSegment 15 | 16 | from ..modules.database import DB 17 | from ..modules.mytyping import config, result 18 | 19 | sv = Service("崩坏3米游社签到") 20 | _bot = sv.bot 21 | 22 | 23 | def autosign(hk3: Honkai3rd, qid: str): 24 | sign_data = load_data() 25 | today = datetime.today().day 26 | try: 27 | result_list = hk3.sign() 28 | except Exception as e: 29 | sign_data.update({qid: {"date": today, "status": False, "result": None}}) 30 | return f"{e}\n自动签到失败." 31 | ret_list = f"〓米游社崩坏3签到〓\n####{datetime.date(datetime.today())}####\n" 32 | for n, res in enumerate(result_list): 33 | res = result(**res) 34 | ret = f"🎉No.{n+1}\n{res.region_name}-{res.nickname}\n今日奖励:{res.reward_name}*{res.reward_cnt}\n本月累签:{res.total_sign_day}天\n签到结果:" 35 | if res.status == "OK": 36 | ret += f"OK✨" 37 | else: 38 | ret += f"舰长,你今天已经签到过了哦👻" 39 | ret += "\n###############\n" 40 | ret_list += ret 41 | sign_data.update({qid: {"date": today, "status": True, "result": ret_list}}) 42 | save_data(sign_data) 43 | return ret_list.strip() 44 | 45 | 46 | SIGN_PATH = os.path.join(os.path.dirname(__file__), "./sign_on.json") 47 | 48 | 49 | def load_data(): 50 | if not os.path.exists(SIGN_PATH): 51 | with open(SIGN_PATH, "w", encoding="utf8") as f: 52 | json.dump({}, f) 53 | return {} 54 | with open(SIGN_PATH, "r", encoding="utf8") as f: 55 | data: dict = json.load(f) 56 | return data 57 | 58 | 59 | def save_data(data): 60 | with open(SIGN_PATH, "w", encoding="utf8") as f: 61 | json.dump(data, f, ensure_ascii=False, indent=4) 62 | 63 | 64 | def check_cookie(qid: str): 65 | db = DB("uid.sqlite", tablename="qid_uid") 66 | cookie = db.get_cookie(qid) 67 | if not cookie: 68 | return f"自动签到需要绑定cookie,发送'bhf?'查看如何绑定." 69 | hk3 = Honkai3rd(cookie=cookie) 70 | try: 71 | role_info = hk3.roles_info 72 | except GenshinHelperException as e: 73 | return f"{e}\ncookie不可用,请重新绑定." 74 | if not role_info: 75 | return f"未找到崩坏3角色信息,请确认cookie对应账号是否已绑定崩坏3角色." 76 | return hk3 77 | 78 | 79 | @sv.on_rex(r"(开启|关闭|on|off)?\s?(?:崩坏?|bh|bbb|崩崩崩)(?:3|三)?自动签到") 80 | async def switch_autosign(bot: HoshinoBot, ev: CQEvent): 81 | """自动签到开关""" 82 | qid = str(ev.user_id) 83 | cmd: str = ev["match"].group(1) 84 | sign_data = load_data() 85 | if cmd in ["off", "关闭"]: 86 | if not qid in sign_data: 87 | return 88 | sign_data.pop(qid) 89 | save_data(sign_data) 90 | await bot.send(ev, "已关闭.", at_sender=True) 91 | return 92 | hk3 = check_cookie(qid) 93 | if isinstance(hk3, str): 94 | await bot.send(ev, hk3, at_sender=True) 95 | return 96 | result = autosign(hk3, qid) 97 | await send_notice(qid, result, bot) 98 | if cmd: 99 | await bot.send(ev, f"自动签到已开启.", at_sender=True) 100 | else: 101 | await bot.send(ev, f"签到完成,结果已通过私聊或邮件发送.", at_sender=True) 102 | 103 | 104 | def _format_addr(s): 105 | name, addr = parseaddr(s) 106 | return formataddr((Header(name, "utf8").encode(), addr)) 107 | 108 | 109 | async def send_notice(qid: str, context: str, bot: HoshinoBot = _bot): 110 | friend_list = await bot.get_friend_list() 111 | if qid in [str(friend.get("user_id")) for friend in friend_list]: 112 | await bot.send_private_msg(user_id=qid, message=MessageSegment.text(context)) 113 | return 114 | user = config.username 115 | password = config.password 116 | if not user or not password: 117 | await bot.send_private_msg( 118 | user_id=SUPERUSERS[0], message=MessageSegment.text(context) 119 | ) 120 | return 121 | msg = MIMEText(context, "plain", _charset="utf-8") 122 | msg["Subject"] = Header(f"签到结果", "utf8").encode() 123 | msg["From"] = _format_addr(f"Paimon <{user}>") 124 | msg["To"] = _format_addr(f"{qid} <{qid}@qq.com>") 125 | with SMTP_SSL(host="smtp.qq.com", port=465) as smtp: 126 | # smtp.set_debuglevel(1) 127 | smtp.login(user, password) 128 | smtp.sendmail(user, f"{qid}@qq.com", msg=msg.as_string()) 129 | 130 | 131 | @sv.scheduled_job("cron", hour="4-10", minute="10,40") 132 | async def schedule_sign(): 133 | today = datetime.today().day 134 | sign_data = load_data() 135 | cnt = 0 136 | sum = len(sign_data) 137 | for qid in sign_data: 138 | await asyncio.sleep(5) 139 | if sign_data[qid].get("date") != today or not sign_data[qid].get("status"): 140 | hk3 = check_cookie(qid) 141 | if isinstance(hk3, Honkai3rd): 142 | hk3 = autosign(hk3, qid) 143 | cnt += 1 144 | await send_notice(qid, hk3) 145 | return cnt, sum 146 | 147 | 148 | @sv.on_fullmatch("重载崩坏3自动签到") 149 | async def reload_sign(bot: HoshinoBot, ev: CQEvent): 150 | if not priv.check_priv(ev, priv.SUPERUSER): 151 | return 152 | await bot.send(ev, f"开始重执行。", at_sender=True) 153 | try: 154 | cnt, sum = await schedule_sign() 155 | except: 156 | res = await schedule_sign() 157 | await bot.send( 158 | ev, 159 | f"重执行完成,状态刷新{cnt}条,共{sum}条", 160 | at_sender=True, 161 | ) 162 | -------------------------------------------------------------------------------- /autosign/mysign.py: -------------------------------------------------------------------------------- 1 | import json 2 | from datetime import datetime 3 | from pathlib import Path 4 | 5 | from genshinhelper import Honkai3rd 6 | from genshinhelper.utils import _, nested_lookup, request 7 | 8 | 9 | class Honkai3rd_edit(Honkai3rd): 10 | def __init__(self, cookie: str = None): 11 | super().__init__(cookie) 12 | self.act_id = "e202207181446311" 13 | self.rewards_info_url = ( 14 | f"{self.api}/event/luna/info?lang=zh-cn&act_id={self.act_id}" 15 | + "&uid={}®ion={}" 16 | ) 17 | self.month_awards_url = ( 18 | f"{self.api}/event/luna/home?lang=zh-cn&act_id={self.act_id}" 19 | ) 20 | self._month_awards = [] 21 | 22 | @property 23 | def sign_info(self): 24 | if not self._sign_info: 25 | rewards_info = self.rewards_info 26 | for i in rewards_info: 27 | self._sign_info.append( 28 | {"total_sign_day": i["total_sign_day"], "is_sign": i["is_sign"]} 29 | ) 30 | return self._sign_info 31 | 32 | @property 33 | def rewards_info(self): 34 | if not self._rewards_info: 35 | roles_info = self.roles_info 36 | for i in roles_info: 37 | url = self.rewards_info_url.format(i["game_uid"], i["region"]) 38 | response = request( 39 | "get", url, headers=self.headers, cookies=self.cookie 40 | ).json() 41 | self._rewards_info.append( 42 | nested_lookup(response, "data", fetch_first=True) 43 | ) 44 | return self._rewards_info 45 | 46 | @property 47 | def month_awards(self): 48 | if not self._month_awards: 49 | url = self.month_awards_url 50 | response = request( 51 | "get", url, headers=self.headers, cookies=self.cookie 52 | ).json() 53 | self._month_awards = nested_lookup(response, "awards", fetch_first=False) 54 | return self._month_awards 55 | 56 | def get_month_awards(self): 57 | awards_path = Path(__file__).parent / Path("awards.json") 58 | today = datetime.now() 59 | day1 = today.replace(day=1, hour=0, minute=0) 60 | if not awards_path.exists() or awards_path.stat().st_mtime < day1.timestamp(): 61 | awards = self.month_awards 62 | with open(awards_path, "w", encoding="utf8") as file: 63 | json.dump(awards, file, indent=4, ensure_ascii=False) 64 | return awards 65 | with open(awards_path, "r", encoding="utf8") as file: 66 | return json.load(file) 67 | 68 | def sign_more(self): 69 | result = self.sign() 70 | month_awards = self.get_month_awards() 71 | for res in result: 72 | assert isinstance(res, dict) 73 | award = month_awards[0][res["total_sign_day"] - 1] 74 | res.update(award) 75 | return result 76 | def get_current_reward(self, total_sign_day: int, is_sign: bool = False): 77 | rewards_info = self.rewards_info 78 | if isinstance(rewards_info[0], list): 79 | rewards_info = rewards_info[0] 80 | total_sign_day = 0 81 | 82 | raw_current_reward = rewards_info[total_sign_day] 83 | return {'reward_' + k: v for k, v in raw_current_reward.items()} -------------------------------------------------------------------------------- /config_example.yaml: -------------------------------------------------------------------------------- 1 | # 用来存放数据库的文件夹 2 | cache_dir: ./data/ 3 | # 是否使用egenshin的cookie,只有查询水晶手账时使用 4 | is_egenshin: False 5 | # egenshin的uid.sqlite的绝对路径,例如C:\HoshinoBot\hoshino\modules\egenshin\data\uid.sqlite 6 | # 留空则默认为 somepath\hoshino\modules\egenshin\data\uid.sqlite 7 | egenshin_dir: 8 | # QQ邮箱用户名,选填 9 | username: 10 | # QQ邮箱授权码,选填 11 | password: 12 | # 必填 13 | cookies: 14 | - your cookies 15 | -------------------------------------------------------------------------------- /guess_voice/__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import random 4 | import re 5 | 6 | from hoshino import HoshinoBot, Service, priv 7 | from hoshino.typing import CQEvent, MessageSegment 8 | from hoshino.util import FreqLimiter 9 | 10 | from .game import GameSession 11 | 12 | _help = """ 13 | [崩坏3猜语音]:正常舰桥、战斗等语音 14 | [崩坏3猜语音2/困难]:简短的语气或拟声词 15 | """ 16 | FN = 30 17 | flmt = FreqLimiter(FN) 18 | sv = Service("崩坏3猜语音", bundle="崩坏3", help_=_help) 19 | 20 | 21 | def split_voice_by_chara(v_list: list): 22 | """对语音列表进行分类""" 23 | ret = { 24 | "normal": {}, # 正常语音 25 | "hard": {} # 语气&拟声词 26 | } 27 | for voice in v_list: 28 | op_dict = ret["hard"] if "拟声词" in voice["voice_path"] else ret["normal"] 29 | chara = re.split("-|\(", voice["voice_name"])[0].strip() 30 | if re.search(r"《|【", chara): 31 | continue 32 | if not op_dict.get(chara): 33 | op_dict[chara] = [] 34 | op_dict[chara].append(voice) 35 | return ret 36 | 37 | 38 | def gen_voice_list(origin_path=None): 39 | """递归生成语音列表""" 40 | voice_dir = os.path.join(os.path.dirname(__file__), "../assets/record") 41 | if origin_path is None: 42 | origin_path = voice_dir 43 | ret_list = [] 44 | for item in os.listdir(origin_path): 45 | item_path = os.path.join(origin_path, item) 46 | if os.path.isdir(item_path): 47 | ret_list.extend(gen_voice_list(item_path)) 48 | elif item.endswith("mp3"): 49 | voice_path = os.path.relpath(item_path, voice_dir) 50 | ret_list.append({"voice_name": item, "voice_path": voice_path}) 51 | else: 52 | continue 53 | return ret_list 54 | 55 | 56 | @sv.on_rex(r"^(崩坏?|bh|bbb|崩崩崩)(3|三)?猜语音") 57 | async def guess_voice(bot: HoshinoBot, ev: CQEvent): 58 | msg = str(ev.message.extract_plain_text().strip()) 59 | if re.search(r"2|困难", msg): 60 | difficulty = "hard" 61 | else: 62 | difficulty = "normal" 63 | game = GameSession(ev.group_id) 64 | ret = await game.start(difficulty=difficulty) 65 | await bot.send(ev, ret) 66 | 67 | 68 | @sv.on_message() 69 | async def check_answer(bot, ev: CQEvent): 70 | game = GameSession(ev.group_id) 71 | if not game.is_start: 72 | return 73 | msg = ev.message.extract_plain_text().strip() 74 | msg = msg.lower().replace(",", "和").replace(",", "和") 75 | await game.check_answer(msg, ev.user_id) 76 | 77 | 78 | @sv.on_rex(r"^(崩坏?|bh|bbb|崩崩崩)(3|三)?语音([^:]+)$") 79 | async def send_voice(bot: HoshinoBot, ev: CQEvent): 80 | msg = ev["match"].group(3) 81 | uid = ev.user_id 82 | if not flmt.check(uid): 83 | await bot.send( 84 | ev, 85 | f"{FN}s内只能获取一次语音,请{int(flmt.left_time(uid))}s后再试。", 86 | at_sender=True, 87 | ) 88 | return 89 | a_list = GameSession.__load__("answer.json") 90 | assert isinstance(a_list, dict) 91 | for k, v in a_list.items(): 92 | if msg in v: 93 | try: 94 | v_list = GameSession.__load__()["normal"][k] 95 | except KeyError: 96 | await bot.send(ev,f"语音列表未生成或有错误,请先发送‘更新崩坏3语音列表’来更新") 97 | voice = random.choice(v_list) 98 | voice_path = f"file:///{os.path.join(os.path.dirname(__file__),'../assets/record',voice['voice_path'])}" 99 | await bot.send(ev, MessageSegment.record(voice_path)) 100 | flmt.start_cd(uid) 101 | return 102 | await bot.send(ev, f"没找到【{msg}】的语音,请检查输入。", at_sender=True) 103 | 104 | 105 | @sv.on_rex(r"^(崩坏?|bh|bbb|崩崩崩)(3|三)?语音新增答案(\w+)[:|:](\w+)$") 106 | async def add_answer(bot: HoshinoBot, ev: CQEvent): 107 | if not priv.check_priv(ev, priv.SU): 108 | return 109 | origin = ev["match"].group(3) 110 | new = ev["match"].group(4) 111 | data = GameSession.__load__("answer.json") 112 | if origin not in data: 113 | await bot.send(ev,f"{origin}不存在。") 114 | return 115 | if new in data[origin]: 116 | await bot.send(ev,f"答案已存在。") 117 | return 118 | data[origin].append(new) 119 | with open( 120 | os.path.join(os.path.dirname(__file__), "answer.json"), "w", encoding="utf8" 121 | ) as f: 122 | json.dump(data, f, ensure_ascii=False, indent=4) 123 | await bot.send(ev, "添加完成。") 124 | 125 | 126 | @sv.on_rex(r"^更新(崩坏?|bh|bbb|崩崩崩)(3|三)?语音列表$") 127 | async def update_voice_list(bot: HoshinoBot, ev: CQEvent): 128 | if not priv.check_priv(ev, priv.SU): 129 | return 130 | data = gen_voice_list() 131 | data_dict = split_voice_by_chara(data) 132 | with open( 133 | os.path.join(os.path.dirname(__file__), "record.json"), "w", encoding="utf8" 134 | ) as f: 135 | json.dump(data_dict, f, indent=4, ensure_ascii=False) 136 | num_normal = sum(len(data_dict["normal"][v]) for v in data_dict["normal"]) 137 | num_hard = sum(len(data_dict["hard"][v]) for v in data_dict["hard"]) 138 | await bot.send( 139 | ev, f"崩坏3语音列表更新完成,当前共有语音{num_hard+num_normal}条,其中普通{num_normal}条,困难{num_hard}条" 140 | ) 141 | 142 | 143 | if __name__ == "__main__": 144 | data = gen_voice_list() 145 | with open( 146 | os.path.join(os.path.dirname(__file__), "record.json"), "w", encoding="utf8" 147 | ) as f: 148 | json.dump(split_voice_by_chara(data), f, indent=4, ensure_ascii=False) 149 | -------------------------------------------------------------------------------- /guess_voice/answer_template.json: -------------------------------------------------------------------------------- 1 | { 2 | "不灭星锚": [ 3 | "不灭星锚", 4 | "星锚", 5 | "星猫", 6 | "烧鹅", 7 | "火鹅", 8 | "火呆" 9 | ], 10 | "主角": [ 11 | "主角", 12 | "后崩主角", 13 | "我", 14 | "爷" 15 | ], 16 | "丽塔": [ 17 | "丽塔", 18 | "月魂", 19 | "冰箱", 20 | "冰箱的主人" 21 | ], 22 | "云墨丹心": [ 23 | "云墨丹心", 24 | "云墨" 25 | ], 26 | "仿犹大": [ 27 | "仿犹大" 28 | ], 29 | "克莱因": [ 30 | "克莱因" 31 | ], 32 | "八重樱": [ 33 | "八重樱", 34 | "嘤嘤嘤", 35 | "勿忘", 36 | "御神装·勿忘" 37 | ], 38 | "八重霞": [ 39 | "八重霞", 40 | "霞" 41 | ], 42 | "刻晴": [ 43 | "刻晴" 44 | ], 45 | "卡莲": [ 46 | "卡莲", 47 | "原罪猎人", 48 | "原罪", 49 | "今样", 50 | "圣仪装·今样" 51 | ], 52 | "卡萝尔": [ 53 | "卡萝尔", 54 | "卡罗尔" 55 | ], 56 | "双子": [ 57 | "双子", 58 | "双胞胎", 59 | "阿琳姐妹" 60 | ], 61 | "圣剑幽兰黛尔": [ 62 | "圣剑幽兰黛尔", 63 | "小幽" 64 | ], 65 | "天元骑英": [ 66 | "天元骑英", 67 | "天元", 68 | "骑鹅", 69 | "虚数鹅", 70 | "天鹅", 71 | "创鹅" 72 | ], 73 | "天穹游侠": [ 74 | "天穹游侠", 75 | "游侠" 76 | ], 77 | "失落迷迭": [ 78 | "失落迷迭", 79 | "迷迭" 80 | ], 81 | "姬子": [ 82 | "姬子", 83 | "真红", 84 | "真红骑士·月蚀", 85 | "真红骑士", 86 | "玫瑰", 87 | "血色玫瑰" 88 | ], 89 | "布洛妮娅": [ 90 | "布洛妮娅", 91 | "板鸭" 92 | ], 93 | "希儿": [ 94 | "希儿", 95 | "白希" 96 | ], 97 | "幽兰黛尔": [ 98 | "幽兰黛尔", 99 | "呆鹅", 100 | "荣光", 101 | "月魄", 102 | "辉骑士·月魄" 103 | ], 104 | "德丽莎": [ 105 | "德丽莎" 106 | ], 107 | "断罪影舞": [ 108 | "断罪影舞", 109 | "鹦鹉", 110 | "影舞" 111 | ], 112 | "明日香": [ 113 | "明日香", 114 | "香香" 115 | ], 116 | "暮光骑士": [ 117 | "暮光骑士", 118 | "增幅紫苑", 119 | "月煌", 120 | "处刑装紫苑", 121 | "德丽莎", 122 | "紫苑" 123 | ], 124 | "月下初拥": [ 125 | "月下初拥", 126 | "月下" 127 | ], 128 | "朔夜观星": [ 129 | "朔夜观星", 130 | "观星" 131 | ], 132 | "极地战刃": [ 133 | "极地战刃", 134 | "年轻姬子" 135 | ], 136 | "梅比乌斯": [ 137 | "梅比乌斯", 138 | "蛇", 139 | "蛇蛇", 140 | "无限·噬界之蛇", 141 | "无限噬界之蛇" 142 | ], 143 | "次生银翼": [ 144 | "次生银翼", 145 | "乳鸭", 146 | "奶鸭", 147 | "大鸭鸭" 148 | ], 149 | "派蒙": [ 150 | "派蒙", 151 | "应急食品" 152 | ], 153 | "渡鸦": [ 154 | "渡鸦", 155 | "午夜苦艾" 156 | ], 157 | "爱莉希雅": [ 158 | "爱莉希雅", 159 | "爱莉", 160 | "粉色妖精小姐" 161 | ], 162 | "爱酱": [ 163 | "爱酱" 164 | ], 165 | "特斯拉Zero": [ 166 | "特斯拉Zero", 167 | "小特", 168 | "特斯拉zero", 169 | "特斯拉" 170 | ], 171 | "狂热蓝调": [ 172 | "狂热蓝调", 173 | "德尔塔", 174 | "delta", 175 | "δ", 176 | "Δ" 177 | ], 178 | "理之律者": [ 179 | "理之律者", 180 | "车车", 181 | "理鸭", 182 | "理律" 183 | ], 184 | "理之律者&希儿": [ 185 | "理之律者&希儿", 186 | "理之律者和希儿", 187 | "车车和希儿", 188 | "理鸭和希儿", 189 | "理律和希儿" 190 | ], 191 | "琪亚娜": [ 192 | "琪亚娜", 193 | "月光", 194 | "白骑士·月光" 195 | ], 196 | "空之律者": [ 197 | "空之律者", 198 | "空律", 199 | "女王" 200 | ], 201 | "符华": [ 202 | "符华", 203 | "白夜", 204 | "白夜执事", 205 | "迅羽", 206 | "荀彧" 207 | ], 208 | "第六夜想曲": [ 209 | "第六夜想曲", 210 | "第六夜" 211 | ], 212 | "绯玉丸": [ 213 | "绯玉丸", 214 | "绯狱丸", 215 | "飞鱼丸" 216 | ], 217 | "缇米朵": [ 218 | "缇米朵", 219 | "小缇" 220 | ], 221 | "缭乱星棘": [ 222 | "缭乱星棘", 223 | "星塔", 224 | "火塔" 225 | ], 226 | "芽衣": [ 227 | "芽衣", 228 | "鬼铠", 229 | "雷电女王的鬼铠" 230 | ], 231 | "苍玄": [ 232 | "苍玄", 233 | "苍玄之书", 234 | "小祖宗" 235 | ], 236 | "若水": [ 237 | "若水" 238 | ], 239 | "莉莉娅": [ 240 | "莉莉娅", 241 | "蓝毛", 242 | "小蓝" 243 | ], 244 | "莱尔": [ 245 | "莱尔" 246 | ], 247 | "菲谢尔": [ 248 | "菲谢尔", 249 | "断罪皇女!!", 250 | "皇女", 251 | "断罪皇女!!", 252 | "断罪皇女" 253 | ], 254 | "菲谢尔&奥兹": [ 255 | "菲谢尔&奥兹", 256 | "菲谢尔和奥兹", 257 | "断罪皇女!!和奥兹", 258 | "皇女和奥兹", 259 | "断罪皇女!!和奥兹", 260 | "断罪皇女和奥兹", 261 | "菲谢尔奥兹", 262 | "皇女奥兹" 263 | ], 264 | "菲谢尔(奥兹)": [ 265 | "菲谢尔(奥兹)", 266 | "奥兹" 267 | ], 268 | "萝莎莉娅": [ 269 | "萝莎莉娅", 270 | "粉毛", 271 | "小粉" 272 | ], 273 | "薪炎之律者": [ 274 | "薪炎之律者", 275 | "薪炎", 276 | "火虫", 277 | "萤火虫", 278 | "炎律" 279 | ], 280 | "西琳": [ 281 | "西琳" 282 | ], 283 | "识之律者": [ 284 | "识之律者", 285 | "小识", 286 | "识宝", 287 | "识律" 288 | ], 289 | "贝拉": [ 290 | "贝拉" 291 | ], 292 | "赤鸢": [ 293 | "赤鸢", 294 | "老师" 295 | ], 296 | "迷城骇兔": [ 297 | "迷城骇兔", 298 | "骇兔" 299 | ], 300 | "镇魂歌": [ 301 | "镇魂歌", 302 | "晓月", 303 | "晓月镇魂歌" 304 | ], 305 | "雷之律者": [ 306 | "雷之律者", 307 | "雷律" 308 | ], 309 | "魇夜星渊": [ 310 | "魇夜星渊", 311 | "冰希", 312 | "奶昔", 313 | "奶希" 314 | ], 315 | "黑希儿": [ 316 | "黑希儿", 317 | "黑希" 318 | ] 319 | } -------------------------------------------------------------------------------- /guess_voice/game.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import random 4 | from datetime import datetime, timedelta 5 | from shutil import copy 6 | 7 | from apscheduler.triggers.date import DateTrigger 8 | from hoshino import get_bot 9 | from hoshino.typing import MessageSegment 10 | from nonebot import scheduler 11 | 12 | # from apscheduler.schedulers.asyncio import AsyncIOScheduler 13 | # scheduler = AsyncIOScheduler() 14 | game_record = {} 15 | bot = get_bot() 16 | 17 | 18 | class GameSession: 19 | @staticmethod 20 | def __load__(file: str = "record.json"): 21 | file = os.path.join(os.path.dirname(__file__), file) 22 | if not os.path.exists(file): 23 | if file.endswith("record.json"): 24 | with open(file, "w", encoding="utf8") as f: 25 | f.write("{}") 26 | elif file.endswith("answer.json"): 27 | copy( 28 | os.path.join(os.path.dirname(__file__), "answer_template.json"), 29 | file, 30 | ) 31 | with open(file, "r", encoding="utf8") as li: 32 | data = json.load(li) 33 | return data 34 | 35 | def __init__(self, gid: int) -> None: 36 | self.group_id = gid 37 | self.record = game_record.get(self.group_id, {}) 38 | self.job_id = f"{self.group_id}_bh3_guess_voice" 39 | self.voice_list = self.__load__() 40 | 41 | async def start(self, duration: int = 30, difficulty: str = "normal"): 42 | """difficulty: normal|hard""" 43 | if self.is_start: 44 | return f"游戏正在进行中" 45 | self.begin = datetime.now() 46 | self.end = self.begin + timedelta(seconds=duration) 47 | try: 48 | self.chara, vlist = random.choice(list(self.voice_list[difficulty].items())) 49 | except KeyError: 50 | return f"语音列表未生成或有错误,请先发送‘更新崩坏3语音列表’来更新" 51 | self.voice = random.choice(vlist) 52 | game_record.update( 53 | {self.group_id: {"chara": self.chara, "voice": self.voice, "ok": -1}} 54 | ) 55 | if scheduler.get_job(job_id=self.job_id): 56 | scheduler.remove_job(self.job_id) 57 | scheduler.add_job( 58 | self.stop, 59 | trigger=DateTrigger(self.end), 60 | id=self.job_id, 61 | misfire_grace_time=60, 62 | coalesce=True, 63 | max_instances=1, 64 | ) 65 | record_path = f"file:///{os.path.join(os.path.dirname(__file__),'../assets/record',self.voice['voice_path'])}" 66 | print(self.answer) 67 | await bot.send_group_msg( 68 | group_id=self.group_id, message=f"即将发送一段崩坏3语音,将在{duration}后公布答案。" 69 | ) 70 | return f"{MessageSegment.record(record_path)}" 71 | 72 | @property 73 | def answer(self) -> list: 74 | self.chara = game_record[self.group_id]["chara"] 75 | alist = self.__load__("answer.json") 76 | return alist[self.chara] 77 | 78 | @property 79 | def is_start(self): 80 | self.record = game_record.get(self.group_id, {}) 81 | return bool(self.record != {}) 82 | 83 | async def stop(self): 84 | self.record = game_record.get(self.group_id) 85 | ok_player = self.record["ok"] 86 | if ok_player < 0: 87 | ret_msg = "还没有人猜中呢" 88 | else: 89 | ret_msg = f"回答正确的人:{MessageSegment.at(ok_player)}" 90 | ret_msg = f"正确答案是:{self.chara}\n{ret_msg}" 91 | await bot.send_group_msg(group_id=self.group_id, message=ret_msg) 92 | game_record[self.group_id] = {} 93 | 94 | async def check_answer(self, ans: str, qid: int): 95 | self.record = game_record.get(self.group_id) 96 | if self.record["ok"] > 0: 97 | return 98 | if ans not in self.answer: 99 | return 100 | if scheduler.get_job(self.job_id): 101 | scheduler.remove_job(self.job_id) 102 | game_record[self.group_id]["ok"] = qid 103 | await self.stop() 104 | -------------------------------------------------------------------------------- /guess_voice/readme.md: -------------------------------------------------------------------------------- 1 | ## 重命名 2 | >语音素材共享【2022年1月27日】(5.5天元启星)\语音素材共享【主文件包】\布洛妮娅\战斗语音\布洛妮娅支援请求收到,布洛妮娅已到达目的地。.mp3 3 | 4 | 为 5 | >语音素材共享【2022年1月27日】(5.5天元启星)\语音素材共享【主文件包】\布洛妮娅\战斗语音\布洛妮娅-支援请求收到,布洛妮娅已到达目的地。.mp3 6 | 7 | ## record文件结构 8 | 无论是将完全解压后的文件夹原样放到assets/record还是把子文件夹甚至语音文件直接丢进去都是可以识别的 9 | 10 | 结构没有特殊要求,只要放到assets/record文件夹里即可 11 | -------------------------------------------------------------------------------- /modules/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chingkingm/honkai_mys/0ad700a15f13498e135867171d01fbdf10b90bec/modules/__init__.py -------------------------------------------------------------------------------- /modules/database.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from typing import Optional 4 | 5 | from sqlitedict import SqliteDict 6 | 7 | from .mytyping import config 8 | 9 | 10 | class DB(SqliteDict): 11 | cahce_dir = os.path.join(os.path.dirname(__file__), "../", config.cache_dir) 12 | 13 | def __init__( 14 | self, 15 | filename=None, 16 | tablename="unnamed", 17 | flag="c", 18 | autocommit=True, 19 | journal_mode="DELETE", 20 | encode=json.dumps, 21 | decode=json.loads, 22 | ) -> None: 23 | if not os.path.exists(self.cahce_dir): 24 | os.mkdir(self.cahce_dir) 25 | filename = os.path.join( 26 | os.path.dirname(__file__), "../", self.cahce_dir, filename 27 | ) 28 | super().__init__( 29 | filename=filename, 30 | tablename=tablename, 31 | flag=flag, 32 | autocommit=autocommit, 33 | journal_mode=journal_mode, 34 | encode=encode, 35 | decode=decode, 36 | ) 37 | 38 | def set_region(self, role_id: str, region: str) -> None: 39 | data = self.get(role_id, {}) 40 | data.update({"region": region}) 41 | self[role_id] = data 42 | 43 | def get_region(self, role_id: str) -> Optional[str]: 44 | if self.get(role_id): 45 | return self[role_id]["region"] 46 | else: 47 | return None 48 | 49 | def get_uid_by_qid(self, qid: str) -> str: 50 | """获取上次查询的uid""" 51 | return self[qid]["role_id"] 52 | 53 | def set_uid_by_qid(self, qid: str, uid: str) -> None: 54 | data = self.get(qid, {}) 55 | data.update({"role_id": uid}) 56 | self[qid] = data 57 | 58 | def get_cookie(self, qid: str) -> Optional[str]: 59 | try: 60 | cookie = self[qid]["cookie"] 61 | except KeyError: 62 | if config.is_egenshin: 63 | if config.egenshin_dir is None: 64 | config.egenshin_dir = os.path.join( 65 | os.path.dirname(__file__), "../../egenshin/data/uid.sqlite" 66 | ) 67 | edb = DB(config.egenshin_dir, tablename="unnamed") 68 | try: 69 | cookie = edb.get(qid)["cookie"] 70 | except: 71 | return None 72 | else: 73 | return None 74 | return cookie 75 | 76 | def set_cookie(self, qid: str, cookie: str) -> None: 77 | data = self.get(qid, {}) 78 | data.update({"cookie": cookie}) 79 | self[qid] = data 80 | -------------------------------------------------------------------------------- /modules/image_handle.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import math 3 | import os 4 | import re 5 | from io import BytesIO 6 | from math import cos, pi, sin 7 | from operator import attrgetter 8 | from typing import List, Tuple, Union 9 | 10 | from httpx import AsyncClient 11 | from PIL import Image, ImageChops, ImageDraw, ImageFont, UnidentifiedImageError 12 | 13 | from .mytyping import (AbyssReport, BattleFieldReport, Character, FinanceInfo, 14 | FullInfo, Index, _stigamata, _weapon) 15 | from .util import ItemTrans 16 | 17 | 18 | class myDraw(ImageDraw.ImageDraw): 19 | def __init__(self, im) -> None: 20 | super().__init__(im) 21 | 22 | @classmethod 23 | async def avatar( 24 | cls, 25 | bg: Image.Image, 26 | qid: str = None, 27 | avatar_url: str = None, 28 | center: Tuple[int, int] = [562, 267], 29 | ) -> Image.Image: 30 | """头像""" 31 | qava_url = "http://q1.qlogo.cn/g?b=qq&nk={qid}&s=140" 32 | if avatar_url is not None: 33 | try: 34 | no = re.search(r"\d{3,}", avatar_url).group() 35 | a_url = avatar_url.split(no)[0] + no + ".png" 36 | except: 37 | try: 38 | no = re.search(r"[a-zA-Z]{1,}\d{2}", avatar_url).group() 39 | a_url = avatar_url.split(no)[0] + no + ".png" 40 | except: 41 | a_url = "https://upload-bbs.mihoyo.com/game_record/honkai3rd/all/SpriteOutput/AvatarIcon/705.png" 42 | else: 43 | a_url = qava_url.format(qid=qid) 44 | pic_data = await cls.get_net_img(url=a_url) 45 | with Image.open( 46 | os.path.join(os.path.dirname(__file__), "../assets/404.png") 47 | ) as img_404: 48 | try: 49 | im_temp = Image.open(pic_data) 50 | except UnidentifiedImageError: 51 | im_temp = img_404 52 | if not ImageChops.difference(img_404, im_temp).getbbox(): 53 | pic_data = await cls.get_net_img(url=qava_url.format(qid=qid)) 54 | with Image.open(pic_data) as pic: 55 | pic = cls.ImgResize(pic, 256 / pic.width).convert("RGBA") 56 | with Image.new(mode="RGBA", size=bg.size, color="#ece5d8") as im: 57 | im.alpha_composite( 58 | pic, 59 | dest=( 60 | int(center[0] - 0.5 * pic.width), 61 | int(center[1] - 0.5 * pic.height), 62 | ), 63 | ) 64 | im.alpha_composite(bg) 65 | return im 66 | 67 | @staticmethod 68 | def get_font(font: str = "65", size: int = 36) -> ImageFont.FreeTypeFont: 69 | font = str(font) 70 | font_path_65 = os.path.join( 71 | os.path.dirname(__file__), f"../assets/font/HYWenHei-65W.ttf" 72 | ) 73 | font_path_85 = os.path.join( 74 | os.path.dirname(__file__), f"../assets/font/HYWenHei-85W.ttf" 75 | ) 76 | font_path_sara = os.path.join( 77 | os.path.dirname(__file__), f"../assets/font/sarasa-ui-sc-semibold.ttf" 78 | ) # hywh缺字 79 | font_path_lxj = os.path.join( 80 | os.path.dirname(__file__), "../assets/font/HYLingXinTiJ.ttf" 81 | ) 82 | if font == "65": 83 | font_path = font_path_65 84 | elif font == "85": 85 | font_path = font_path_85 86 | elif font == "s": 87 | font_path = font_path_sara 88 | elif font == "l": 89 | font_path = font_path_lxj 90 | return ImageFont.truetype(font_path, size) 91 | 92 | @staticmethod 93 | def radar( 94 | origin_image: Image.Image, 95 | data: List[float], 96 | center: Tuple[float, float], 97 | radius: float, 98 | ) -> Image.Image: 99 | """雷达图,求出各点坐标,调用ImageDraw.polygon""" 100 | # origin_image = bg 101 | # 新建工作图片 102 | im = Image.new("RGBA", size=origin_image.size, color=(255, 255, 255, 0)) 103 | dr = ImageDraw.Draw(im) 104 | zero_x, zero_y = center 105 | sides = len(data) 106 | angel = 2 * pi / sides 107 | angles = [angel * n for n in range(sides)] 108 | hypotenuse = [n * radius / 100 for n in data] 109 | coordinates = [] 110 | for i, hy in enumerate(hypotenuse): 111 | x = zero_x + hy * sin(angles[i]) 112 | y = zero_y - hy * cos(angles[i]) 113 | coordinates.append((x, y)) 114 | dr.polygon(xy=coordinates, fill=(0, 192, 255, 190)) 115 | size = 4 116 | for point in coordinates: 117 | x, y = point 118 | dr.ellipse( 119 | xy=(x - size, y - size, x + size, y + size), 120 | fill="white", 121 | outline=(0, 192, 255), 122 | ) 123 | # 粘贴到目标图片 124 | origin_image.alpha_composite(im) 125 | return origin_image 126 | 127 | @staticmethod 128 | async def get_net_img(url: str) -> Union[BytesIO, str]: 129 | async with AsyncClient() as aiorequests: 130 | if url.startswith("http://q1.qlogo.cn/"): 131 | resp = await aiorequests.get(url) 132 | return BytesIO(resp.content) 133 | image_type, img_name = url.split("/")[-2:] 134 | ASSETS_PATH = os.path.join(os.path.dirname(__file__), "../assets") 135 | image_type_path = os.path.join(ASSETS_PATH, image_type) 136 | if not os.path.exists(image_type_path): 137 | os.makedirs(image_type_path) 138 | else: 139 | ex_image = os.listdir(image_type_path) 140 | if img_name in ex_image: 141 | return os.path.join(image_type_path, img_name) 142 | resp = await aiorequests.get(url) 143 | data = resp.content 144 | with open(os.path.join(image_type_path, img_name), mode="wb") as im: 145 | im.write(data) 146 | im.close() 147 | return BytesIO(data) 148 | 149 | @staticmethod 150 | def ImgResize( 151 | im: Image.Image, coe: float = None, weight: int = None, height: int = None 152 | ) -> Image.Image: 153 | """等比例缩放""" 154 | if coe is not None: 155 | return im.resize((int(length * coe) for length in im.size)) 156 | elif weight is not None: 157 | coe = weight / im.size[0] 158 | return im.resize((int(weight), int(im.size[1] * coe))) 159 | elif height is not None: 160 | coe = height / im.size[1] 161 | return im.resize((int(im.size[0] * coe), int(height))) 162 | 163 | @staticmethod 164 | def ring(data: Tuple[int], radius: int = 120) -> Image.Image: 165 | """画环""" 166 | imsize = 300 167 | imsize_half = 0.5 * imsize 168 | with Image.new("RGBA", size=[imsize, imsize]) as im: 169 | dr = ImageDraw.Draw(im) 170 | degree_start = -90 171 | degree_radian = 0 172 | colors = ["#969cf2", "#fc9208", "#57d9ad", "#ffe148"] 173 | # 先画饼图 174 | for n, d in enumerate(data): 175 | dr.pieslice( 176 | [ 177 | imsize_half - radius, 178 | imsize_half - radius, 179 | imsize_half + radius, 180 | imsize_half + radius, 181 | ], 182 | start=degree_start, 183 | end=degree_start + d * 3.6, 184 | fill=colors[n], 185 | ) 186 | degree_start += d * 3.6 187 | degree_radian = degree_radian + d / 100 * 2 * pi 188 | dr.line( 189 | xy=[ 190 | imsize_half, 191 | imsize_half, 192 | imsize_half + sin(degree_radian) * radius, 193 | imsize_half - cos(degree_radian) * radius, 194 | ], 195 | fill="white", 196 | width=2, 197 | ) # 画分割线 198 | # 用圆遮住中间,形成环 199 | dr.ellipse( 200 | xy=( 201 | imsize_half - 0.5 * radius, 202 | imsize_half - 0.5 * radius, 203 | imsize_half + 0.5 * radius, 204 | imsize_half + 0.5 * radius, 205 | ), 206 | fill="white", 207 | ) 208 | return im 209 | 210 | @staticmethod 211 | def star(equip: Union[_stigamata, _weapon]) -> Image.Image: 212 | """画星星""" 213 | num_total = equip.max_rarity 214 | num_bright = equip.rarity 215 | im_name = f"{num_bright}_of_{num_total}.png" 216 | im_path = os.path.join(os.path.dirname(__file__), "../assets/star", im_name) 217 | if os.path.exists(im_path): 218 | return Image.open(im_path).convert("RGBA") 219 | starlist = [1] * num_bright 220 | num_dark = num_total - num_bright 221 | starlist.extend([0] * num_dark) 222 | star = Image.open( 223 | os.path.join(os.path.dirname(__file__), "../assets/star/星.png") 224 | ) 225 | star_dark = Image.open( 226 | os.path.join(os.path.dirname(__file__), "../assets/star/灰星.png") 227 | ) 228 | with Image.new(mode="RGBA", size=(216, 62), color=(0, 0, 0, 0)) as bg: 229 | indent = 31 230 | length = indent * num_total 231 | x = int(0.5 * (bg.size[0] - length)) 232 | y = 14 233 | for n, s in enumerate(starlist): 234 | if s: 235 | bg.alpha_composite(star, dest=(x + indent * n, y)) 236 | else: 237 | bg.alpha_composite(star_dark, dest=(x + indent * n, y)) 238 | bg.save(im_path, format="png") 239 | return bg 240 | 241 | 242 | def pic2b64(im: Image.Image, quality: int = 100) -> str: 243 | bio = BytesIO() 244 | im.save(bio, format="png", quality=quality) 245 | base64_str = base64.b64encode(bio.getvalue()).decode() 246 | im.close() 247 | return "base64://" + base64_str 248 | 249 | 250 | async def draw_abyss(aby: AbyssReport) -> Image.Image: 251 | if aby.type == "Greedy": 252 | bg_path = os.path.join(os.path.dirname(__file__), "../assets/abyss_greedy.png") 253 | else: 254 | bg_path = os.path.join(os.path.dirname(__file__), "../assets/abyss.png") 255 | with Image.open(bg_path) as im: 256 | dr = myDraw(im) 257 | with Image.new(mode="RGBA", size=im.size) as temp: 258 | for n, val in enumerate(aby.lineup): 259 | ava_bg = dr.ImgResize( 260 | Image.open( 261 | await dr.get_net_img(val.avatar_background_path) 262 | ).convert("RGBA"), 263 | 1.5, 264 | ) 265 | ava_icon = dr.ImgResize( 266 | Image.open(await dr.get_net_img(val.icon_path)).convert("RGBA"), 267 | 0.72, 268 | ) 269 | temp.alpha_composite(ava_bg, dest=(45 + n * 120, 108)) 270 | temp.alpha_composite(ava_icon, dest=(45 + n * 120, 109)) 271 | temp.alpha_composite(im) 272 | img_boss = dr.ImgResize( 273 | Image.open(await dr.get_net_img(aby.boss.avatar)), 1.26 274 | ) 275 | if aby.elf is not None: 276 | img_elf = Image.open(await dr.get_net_img(aby.elf.avatar)) 277 | img_elf = dr.ImgResize(img_elf, coe=0.74) 278 | img_elf_star = dr.ImgResize( 279 | Image.open(ItemTrans.star(aby.elf.star, 1)), 0.755 280 | ) 281 | temp.alpha_composite(img_elf, dest=(415, 110)) 282 | temp.alpha_composite(img_elf_star, dest=(408, 172)) 283 | for n, val in enumerate(aby.lineup): 284 | ava_star = dr.ImgResize(Image.open(ItemTrans.star(val.star)), 0.49) 285 | temp.alpha_composite(ava_star, dest=(23 + n * 120, 159)) 286 | temp.alpha_composite(img_boss, dest=(700, 76)) 287 | im = temp.copy() 288 | dr = myDraw(im) 289 | font_wh65 = myDraw.get_font(size=24) 290 | font_lxj = myDraw.get_font("l", 48) 291 | font_lxj_s = myDraw.get_font("l", 40) 292 | dr.text((39, 60), text=f"{aby.boss.name}", fill="white", font=font_wh65) 293 | if aby.type == "Greedy": 294 | if aby.floor == 10: 295 | dr.text( 296 | xy=(938, 28), 297 | text=f"{aby.floor}层{aby.score:,}", 298 | fill="#0f9ed8", 299 | font=font_lxj_s, 300 | anchor="mm", 301 | ) 302 | else: 303 | # TODO: 缺少数据,临时处理 304 | dr.text( 305 | xy=(938, 28), 306 | text=f"{aby.floor}层", 307 | fill="#0f9ed8", 308 | font=font_lxj, 309 | anchor="mm", 310 | ) 311 | else: 312 | dr.text( 313 | (865, 28), 314 | text=f"{aby.score:,}", 315 | fill="#0f9ed8", 316 | font=font_lxj, 317 | anchor="lm", 318 | ) 319 | if aby.reward_type: 320 | # 有reward_type表明是低级区深渊 321 | abylevel = aby.level 322 | timescond = aby.time_second 323 | dr.text( 324 | xy=(580, 28), 325 | text=f"{ItemTrans.oldAbyssLevelChange(aby.reward_type)}", 326 | fill="white", 327 | font=font_wh65, 328 | anchor="lm", 329 | ) 330 | else: 331 | abylevel = aby.level 332 | timescond = aby.updated_time_second 333 | dr.multiline_text( 334 | xy=(600, 153), 335 | text=f"段位: {ItemTrans.abyss_level(aby.settled_level)}\n排名: {str(aby.rank)}\n杯数: {aby.cup_number}({aby.settled_cup_number:+})", 336 | fill="white", 337 | font=font_wh65, 338 | anchor="lm", 339 | ) 340 | dr.text( 341 | (39, 15), 342 | text=f"{ItemTrans.area(aby.area)}·{ItemTrans.abyss_level(abylevel)}·{ItemTrans.abyss_type(aby.type)}", 343 | fill="white", 344 | font=font_wh65, 345 | ) 346 | dr.text( 347 | xy=(680, 90), 348 | text=f"结算时间:{timescond.astimezone().date()}", 349 | fill="#d4c18d", 350 | font=font_wh65, 351 | anchor="rb", 352 | ) 353 | return im 354 | 355 | 356 | async def draw_battlefield(bfs: BattleFieldReport) -> List[Image.Image]: 357 | ret: List[Image.Image] = [] 358 | for bf in bfs.battle_infos: 359 | with Image.open( 360 | os.path.join(os.path.dirname(__file__), "../assets/bf.png") 361 | ) as bg: 362 | dr = myDraw(bg) 363 | img_boss = Image.open(await dr.get_net_img(bf.boss.avatar)) 364 | bg.alpha_composite(img_boss, dest=(42, 0)) 365 | for n, val in enumerate(bf.lineup): 366 | img_val = dr.ImgResize( 367 | Image.open(await dr.get_net_img(val.background_path)), 0.77 368 | ) 369 | bg.alpha_composite(img_val, dest=(0, 166 + 104 * n)) 370 | img_star = dr.ImgResize(Image.open(ItemTrans.star(val.star)), 0.455) 371 | bg.alpha_composite(img_star, dest=(283, 222 + 104 * n)) 372 | if bf.elf is not None: 373 | img_elf = dr.ImgResize( 374 | Image.open(await dr.get_net_img(bf.elf.avatar)), 0.562 375 | ) 376 | bg.alpha_composite(img_elf, dest=(124, 485)) 377 | img_star = dr.ImgResize( 378 | Image.open(ItemTrans.star(bf.elf.star, 1)), 0.44 379 | ) 380 | bg.alpha_composite(img_star, dest=(195, 523)) 381 | dr.text( 382 | xy=(170, 133), 383 | text=f"{bf.score:,}", 384 | fill="#f1bd31", 385 | font=myDraw.get_font("l", 48), 386 | anchor="mm", 387 | ) 388 | ret.append(bg) 389 | return ret 390 | 391 | 392 | class DrawIndex(FullInfo): 393 | async def draw_card(self, qid: str = None) -> str: 394 | weekr = self.weeklyReport 395 | if self.index.preference.is_god_war_unlock: 396 | bg_path = os.path.join( 397 | os.path.dirname(__file__), f"../assets/backgroud_godwar.png" 398 | ) 399 | else: 400 | bg_path = os.path.join( 401 | os.path.dirname(__file__), f"../assets/backgroud_no_godwar.png" 402 | ) 403 | bg = Image.open(bg_path).convert("RGBA") 404 | bg = await myDraw.avatar(bg, avatar_url=self.index.role.AvatarUrl, qid=qid) 405 | if weekr.favorite_character is not None: 406 | img_fav = Image.open( 407 | await myDraw.get_net_img(weekr.favorite_character.large_background_path) 408 | ) 409 | bg.alpha_composite(img_fav, dest=(782, 367)) 410 | font = myDraw.get_font("s", 48) 411 | font_6536 = myDraw.get_font() 412 | font_8548 = myDraw.get_font("85", 48) 413 | font_6532 = myDraw.get_font(size=32) 414 | font_6524 = myDraw.get_font(size=24) 415 | draw = myDraw(bg) 416 | draw.text( 417 | (1100, 20), 418 | text=f"UID:{self.index.role.role_id}", 419 | fill="white", 420 | font=font_6536, 421 | anchor="rt", 422 | ) 423 | draw.text( 424 | xy=(562, 562), 425 | text=self.index.role.nickname, 426 | fill=(0, 0, 0), 427 | font=font, 428 | anchor="mm", 429 | ) 430 | draw.text( 431 | xy=(390, 675), 432 | text=str(self.index.role.level), 433 | fill=(133, 96, 61), 434 | font=font_8548, 435 | anchor="lm", 436 | ) 437 | draw.text( 438 | xy=(641, 677), 439 | text=ItemTrans.id2server(self.index.role.region), 440 | fill=(133, 96, 61), 441 | font=font_8548, 442 | anchor="mm", 443 | ) 444 | 445 | # 深渊 446 | if self.index.stats.old_abyss is not None: 447 | draw.text( 448 | xy=(232, 821), 449 | text="量子奇点", 450 | fill=(133, 96, 61), 451 | font=font_6536, 452 | anchor="mm", 453 | ) 454 | draw.text( 455 | xy=(232, 885), 456 | text=ItemTrans.abyss_level(self.index.stats.old_abyss.level_of_quantum), 457 | fill=(133, 96, 61), 458 | font=font_6532, 459 | anchor="mm", 460 | ) 461 | draw.line(xy=[(310, 790), (310, 917)], fill=(161, 154, 129), width=0) 462 | draw.text( 463 | xy=(410, 821), 464 | text="量子流形", 465 | fill=(133, 96, 61), 466 | font=font_6536, 467 | anchor="mm", 468 | ) 469 | draw.text( 470 | xy=(410, 885), 471 | text=ItemTrans.abyss_level(self.index.stats.old_abyss.level_of_greedy), 472 | fill=(133, 96, 61), 473 | font=font_6532, 474 | anchor="mm", 475 | ) 476 | else: 477 | draw.text( 478 | xy=(310, 821), 479 | text="超弦空间", 480 | fill=(133, 96, 61), 481 | font=font_6536, 482 | anchor="mm", 483 | ) 484 | draw.text( 485 | xy=(232, 885), 486 | text=ItemTrans.abyss_level(self.index.stats.new_abyss.level), 487 | fill=(133, 96, 61), 488 | font=font_8548, 489 | anchor="mm", 490 | ) 491 | draw.text( 492 | xy=(410, 885), 493 | text=f"{self.index.stats.new_abyss.cup_number}杯", 494 | fill=(133, 96, 61), 495 | font=font_6532, 496 | anchor="mm", 497 | ) 498 | # 战场 499 | draw.text( 500 | xy=(790, 821), 501 | text=ItemTrans.area(self.index.stats.battle_field_area), 502 | fill=(133, 96, 61), 503 | font=font_6536, 504 | anchor="mm", 505 | ) 506 | if self.index.stats.battle_field_score != 0: 507 | draw.text( 508 | xy=(697, 885), 509 | text=f"{self.index.stats.battle_field_score:,}", 510 | fill=(133, 96, 61), 511 | font=font_6536, 512 | anchor="mm", 513 | ) 514 | draw.text( 515 | xy=(880, 885), 516 | text=f"{self.index.stats.battle_field_ranking_percentage}%", 517 | fill=(133, 96, 61), 518 | font=font_8548, 519 | anchor="mm", 520 | ) 521 | else: 522 | draw.text( 523 | xy=(790, 885), 524 | text="无数据", 525 | fill=(133, 96, 61), 526 | font=font_6532, 527 | anchor="mm", 528 | ) 529 | # 数据总览 530 | draw.text( 531 | xy=(465, 1190), 532 | text=str(self.index.stats.active_day_number), 533 | fill=(133, 96, 61), 534 | font=font_8548, 535 | anchor="mm", 536 | ) 537 | draw.text( 538 | xy=(465, 1305), 539 | text=str(self.index.stats.armor_number), 540 | fill=(133, 96, 61), 541 | font=font_8548, 542 | anchor="mm", 543 | ) 544 | draw.text( 545 | xy=(465, 1420), 546 | text=str(self.index.stats.weapon_number), 547 | fill=(133, 96, 61), 548 | font=font_8548, 549 | anchor="mm", 550 | ) 551 | draw.text( 552 | xy=(1010, 1190), 553 | text=str(self.index.stats.suit_number), 554 | fill=(133, 96, 61), 555 | font=font_8548, 556 | anchor="mm", 557 | ) 558 | draw.text( 559 | xy=(1010, 1305), 560 | text=str(self.index.stats.sss_armor_number), 561 | fill=(133, 96, 61), 562 | font=font_8548, 563 | anchor="mm", 564 | ) 565 | draw.text( 566 | xy=(1010, 1420), 567 | text=str(self.index.stats.stigmata_number), 568 | fill=(133, 96, 61), 569 | font=font_8548, 570 | anchor="mm", 571 | ) 572 | # 往世乐土 573 | if self.index.preference.is_god_war_unlock: 574 | draw.text( 575 | xy=(307, 1645), 576 | text=str(self.index.stats.god_war_max_support_point), 577 | fill=(133, 96, 61), 578 | font=font_8548, 579 | anchor="mm", 580 | ) 581 | draw.text( 582 | xy=(809, 1645), 583 | text=str(self.index.stats.god_war_max_challenge_score), 584 | fill=(133, 96, 61), 585 | font=font_8548, 586 | anchor="mm", 587 | ) 588 | draw.text( 589 | xy=(307, 1789), 590 | text=str(self.index.stats.god_war_max_level_avatar_number), 591 | fill=(133, 96, 61), 592 | font=font_8548, 593 | anchor="mm", 594 | ) 595 | draw.text( 596 | xy=(809, 1789), 597 | text=str(self.index.stats.god_war_extra_item_number), 598 | fill=(133, 96, 61), 599 | font=font_8548, 600 | anchor="mm", 601 | ) 602 | # 舰长偏好 603 | data = [ 604 | self.index.preference.battle_field, 605 | self.index.preference.abyss, 606 | self.index.preference.god_war, 607 | self.index.preference.open_world, 608 | self.index.preference.community, 609 | self.index.preference.main_line, 610 | ] 611 | if self.index.preference.is_god_war_unlock: 612 | bg = draw.radar(bg, data=data, center=(237, 2246), radius=164) 613 | else: 614 | data.pop(2) 615 | bg = draw.radar(bg, data=data, center=(237, 2246), radius=177) 616 | draw = ImageDraw.Draw(bg) 617 | draw.text( 618 | xy=(845, 2176), 619 | text=str(self.index.preference.comprehensive_score), 620 | font=font_8548, 621 | fill=(133, 96, 61), 622 | anchor="mm", 623 | ) 624 | rating_image_path = ItemTrans.rate2png( 625 | self.index.preference.comprehensive_rating 626 | ) 627 | rating_image = Image.open(rating_image_path).convert("RGBA") 628 | bg.alpha_composite(rating_image, dest=(782, 2300)) 629 | # 深渊战报 630 | if self.newAbyssReport is not None: 631 | abyss = self.newAbyssReport 632 | else: 633 | abyss = self.latestOldAbyssReport 634 | abyss.reports.sort(key=attrgetter("time_second"), reverse=True) 635 | if len(abyss.reports) == 0: 636 | bg.alpha_composite( 637 | Image.open( 638 | os.path.join(os.path.dirname(__file__), "../assets/no-data.png") 639 | ), 640 | dest=(379, 2767), 641 | ) 642 | for n, reports in enumerate(abyss.reports): 643 | abyss_card = await draw_abyss(reports) 644 | bg.alpha_composite(abyss_card, dest=(48, 2622 + n * 230)) 645 | if n >= 2: 646 | break 647 | # 战场战报 648 | if self.battleFieldReport.reports: 649 | bfr = self.battleFieldReport.reports[0] 650 | ims = await draw_battlefield(bfr) 651 | for n, bfcard in enumerate(ims): 652 | bg.alpha_composite(bfcard, dest=(39 + 355 * n, 3542)) 653 | draw.text( 654 | xy=(562, 3506), 655 | text=f"{ItemTrans.area(bfr.area)}\t{bfr.ranking_percentage}%\t{bfr.score:,}", 656 | fill=(133, 96, 61), 657 | font=font_6536, 658 | anchor="mm", 659 | ) 660 | draw.text( 661 | xy=(1110, 3530), 662 | text=f"结算时间:{bfr.time_second.astimezone().date()}", 663 | fill="gray", 664 | font=font_6524, 665 | anchor="rb", 666 | ) 667 | else: 668 | bg.alpha_composite( 669 | Image.open( 670 | os.path.join(os.path.dirname(__file__), "../assets/no-data2.png") 671 | ), 672 | dest=(398, 3678), 673 | ) 674 | # bg.show() 675 | 676 | return pic2b64(bg, quality=100) 677 | 678 | 679 | def cal_dest(im: Image.Image, center: int) -> int: 680 | """计算粘贴位置""" 681 | size = im.size 682 | return int(center - 0.5 * size[0]) 683 | 684 | 685 | class DrawCharacter(Character): 686 | async def draw_chara(self, index: Index, qid: str = None) -> str: 687 | row_number = math.ceil(len(self.characters) / 3) 688 | card_chara = Image.new( 689 | mode="RGBA", size=(920, 20 + 320 * row_number), color=(236, 229, 216) 690 | ) 691 | for no, valkyrie in enumerate(self.characters): 692 | with Image.open( 693 | os.path.join(os.path.dirname(__file__), "../assets/chara.png") 694 | ) as bg: 695 | blank = Image.new(mode="RGBA", size=bg.size, color=(236, 229, 216)) 696 | md = myDraw(blank) 697 | img_backgroud = Image.open( 698 | await md.get_net_img( 699 | valkyrie.character.avatar.avatar_background_path 700 | ) 701 | ) 702 | img_backgroud = img_backgroud.resize((190, 153)) 703 | blank.alpha_composite(img_backgroud, dest=(46, 15)) 704 | img_avatar = Image.open( 705 | await md.get_net_img( 706 | valkyrie.character.avatar.half_length_icon_path 707 | ) 708 | ).resize((172, 148)) 709 | blank.alpha_composite(img_avatar, dest=(61, 19)) 710 | blank.alpha_composite(bg) 711 | img_star = Image.open( 712 | ItemTrans.star(valkyrie.character.avatar.star) 713 | ).resize((64, 54)) 714 | blank.alpha_composite(img_star, dest=(48, 148)) 715 | weapon = valkyrie.character.weapon 716 | bg_weapon = Image.open( 717 | os.path.join( 718 | os.path.dirname(__file__), 719 | f"../assets/equipment_{weapon.max_rarity}.png", 720 | ) 721 | ).resize((75, 75)) 722 | blank.alpha_composite(bg_weapon, dest=(215, 126)) 723 | img_weapon = Image.open(await md.get_net_img(weapon.icon)).resize( 724 | (72, 63) 725 | ) 726 | blank.alpha_composite(img_weapon, dest=(215, 132)) 727 | img_star = md.ImgResize(myDraw.star(weapon), height=27) 728 | blank.alpha_composite(img_star, dest=(cal_dest(img_star, 253), 182)) 729 | for n, sti in enumerate(valkyrie.character.stigmatas): 730 | if sti.id == 0: 731 | img_none = Image.open( 732 | os.path.join( 733 | os.path.dirname(__file__), "../assets/equipment_0.png" 734 | ) 735 | ).resize((75, 75)) 736 | blank.alpha_composite(img_none, dest=(35 + 76 * n, 223)) 737 | else: 738 | bg_sti = Image.open( 739 | os.path.join( 740 | os.path.dirname(__file__), 741 | f"../assets/equipment_{sti.max_rarity}.png", 742 | ) 743 | ).resize((75, 75)) 744 | blank.alpha_composite(bg_sti, dest=(35 + 76 * n, 223)) 745 | img_sti = Image.open(await md.get_net_img(sti.icon)).resize( 746 | (75, 65) 747 | ) 748 | blank.alpha_composite(img_sti, dest=(35 + 76 * n, 228)) 749 | img_star = md.ImgResize(myDraw.star(sti), height=29) 750 | blank.alpha_composite( 751 | img_star, dest=(cal_dest(img_star, 73 + 76 * n), 279) 752 | ) 753 | # font_lxj = ImageFont.truetype(os.path.join(os.path.dirname( 754 | # __file__), "assets/font/HYLingXinTiJ.ttf"), size=26) 755 | font_lxj = myDraw.get_font("l", 26) 756 | md.text( 757 | xy=(149, 176), 758 | text=f"Lv.{valkyrie.character.avatar.level}", 759 | fill="black", 760 | font=font_lxj, 761 | anchor="mt", 762 | ) 763 | col = math.floor(no / 3) 764 | row = no % 3 765 | card_chara.alpha_composite(blank, dest=(10 + 300 * row, 10 + 320 * col)) 766 | blank.close() 767 | # card_chara.show() 768 | img_header = Image.open( 769 | os.path.join(os.path.dirname(__file__), "../assets/header.png") 770 | ).convert("RGBA") 771 | img_header = await myDraw.avatar( 772 | img_header, qid=qid, avatar_url=index.role.AvatarUrl, center=(460, 218) 773 | ) 774 | dr = myDraw(img_header) 775 | dr.text( 776 | (900, 20), 777 | text=f"UID: {index.role.role_id}", 778 | fill="white", 779 | font=dr.get_font(size=30), 780 | anchor="rt", 781 | ) 782 | dr.text( 783 | xy=(460, 460), 784 | text=index.role.nickname, 785 | fill=(0, 0, 0), 786 | font=dr.get_font("s", 40), 787 | anchor="mm", 788 | ) 789 | dr.text( 790 | xy=(310, 552), 791 | text=str(index.role.level), 792 | fill=(133, 96, 61), 793 | font=dr.get_font(85, 40), 794 | anchor="lm", 795 | ) 796 | dr.text( 797 | xy=(524, 552), 798 | text=ItemTrans.id2server(index.role.region), 799 | fill=(133, 96, 61), 800 | font=dr.get_font(85, 40), 801 | anchor="mm", 802 | ) 803 | dr.text( 804 | xy=(368, 678), 805 | text=str(index.stats.armor_number), 806 | fill=(133, 96, 61), 807 | font=dr.get_font(85, 40), 808 | anchor="mm", 809 | ) 810 | dr.text( 811 | xy=(842, 678), 812 | text=str(index.stats.sss_armor_number), 813 | fill=(133, 96, 61), 814 | font=dr.get_font(85, 40), 815 | anchor="mm", 816 | ) 817 | with Image.new( 818 | "RGBA", 819 | (card_chara.size[0], card_chara.size[1] + img_header.size[1]), 820 | color=(236, 229, 216), 821 | ) as full_im: 822 | # im = await myDraw.avatar(full_im, qid=qid, avatar_url=index.role.AvatarUrl) 823 | full_im.alpha_composite(img_header) 824 | full_im.alpha_composite(card_chara, (0, img_header.size[1])) 825 | # im.show() 826 | return pic2b64(full_im, 100) 827 | 828 | 829 | class DrawFinance(FinanceInfo): 830 | def draw(self) -> str: 831 | with Image.open( 832 | os.path.join(os.path.dirname(__file__), "../assets/finance.png") 833 | ) as finance_bg: 834 | # 本月 835 | index = self.index 836 | dr = myDraw(finance_bg) 837 | font_6536 = myDraw.get_font() 838 | dr.text( 839 | xy=(375, 80), 840 | text=f"UID:{index.uid}", 841 | fill="black", 842 | font=font_6536, 843 | anchor="mm", 844 | ) 845 | dr.text( 846 | xy=(375, 164), 847 | text=f"舰长的{index.month}月手账", 848 | fill="black", 849 | font=font_6536, 850 | anchor="mm", 851 | ) 852 | dr.text( 853 | xy=(375, 245), 854 | text=f"截止至{index.date}", 855 | fill="black", 856 | font=font_6536, 857 | anchor="mm", 858 | ) 859 | dr.text( 860 | xy=(161, 435), 861 | text=f"{index.month_hcoin}", 862 | fill="black", 863 | font=font_6536, 864 | anchor="lm", 865 | ) 866 | dr.text( 867 | xy=(510, 435), 868 | text=f"{index.month_star:,}", 869 | fill="black", 870 | font=font_6536, 871 | anchor="lm", 872 | ) 873 | if index.day_hcoin != 0 or index.day_star != 0: 874 | dr.text( 875 | xy=(375, 550), 876 | text=f"舰长今日已经获取{index.day_hcoin}水晶,{index.day_star}星石.", 877 | fill="black", 878 | font=font_6536, 879 | anchor="mm", 880 | ) 881 | else: 882 | dr.text( 883 | xy=(375, 550), 884 | text=f"舰长今日还没有收入哦.", 885 | fill="black", 886 | font=font_6536, 887 | anchor="mm", 888 | ) 889 | # 上月 890 | lastmonth = self.getLastMonthInfo 891 | font_6524 = myDraw.get_font(size=24) 892 | dr.text( 893 | xy=(375, 747), 894 | text=f"舰长的{lastmonth.month}月手账", 895 | fill="black", 896 | font=font_6536, 897 | anchor="mm", 898 | ) 899 | dr.text( 900 | xy=(375, 841), 901 | text=f"{lastmonth.month_start.date()}至{lastmonth.month_end.date()}", 902 | fill="black", 903 | font=font_6536, 904 | anchor="mm", 905 | ) 906 | dr.text( 907 | xy=(135, 1189), 908 | text=f"{lastmonth.month_hcoin:,}", 909 | fill="black", 910 | font=font_6524, 911 | anchor="lm", 912 | ) 913 | dr.text( 914 | xy=(403, 1189), 915 | text=f"{lastmonth.month_star:,}", 916 | fill="black", 917 | font=font_6524, 918 | anchor="lm", 919 | ) 920 | data = [] 921 | for n, src in enumerate(lastmonth.group_by): 922 | data.append(src.percent) 923 | dr.text( 924 | xy=(400, 940 + n * 49), 925 | text=f"{src.name}", 926 | fill="black", 927 | font=font_6524, 928 | anchor="lm", 929 | ) 930 | dr.text( 931 | xy=(665, 940 + n * 49), 932 | text=f"{src.percent}%", 933 | fill="black", 934 | font=font_6524, 935 | anchor="rm", 936 | ) 937 | ring = dr.ring(data) 938 | finance_bg.alpha_composite(ring, dest=(37, 861)) 939 | return pic2b64(finance_bg) 940 | -------------------------------------------------------------------------------- /modules/mytyping.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=no-name-in-module 2 | # pylint: disable=no-self-argument 3 | import os 4 | import yaml 5 | 6 | from datetime import datetime, date 7 | from pydantic import BaseModel 8 | from typing import List, Optional, Union 9 | 10 | 11 | class Config(BaseModel): 12 | cookies: List[str] 13 | is_egenshin: bool 14 | egenshin_dir: Optional[str] 15 | cache_dir: str 16 | username: Optional[str] 17 | password: Optional[str] 18 | 19 | @staticmethod 20 | def load_config() -> dict: 21 | with open( 22 | os.path.join(os.path.dirname(__file__),"../", "config.yaml"), 23 | mode="r", 24 | encoding="utf8", 25 | ) as f: 26 | CONFIG = yaml.load(f, Loader=yaml.FullLoader) 27 | f.close() 28 | return CONFIG 29 | 30 | 31 | config = Config(**Config.load_config()) 32 | COOKIES = config.cookies[0] 33 | 34 | 35 | class _favorite_character(BaseModel): 36 | id: str 37 | name: str 38 | star: int 39 | avatar_background_path: str 40 | icon_path: str 41 | background_path: str 42 | large_background_path: str 43 | 44 | 45 | class WeeklyReport(BaseModel): 46 | favorite_character: Union[_favorite_character, None] 47 | gold_income: int 48 | gold_expenditure: int 49 | active_day_number: int 50 | online_hours: int 51 | expended_physical_power: int 52 | main_line_expended_physical_power_percentage: int 53 | 54 | 55 | class _role(BaseModel): 56 | AvatarUrl: str 57 | nickname: str 58 | region: str 59 | level: int 60 | role_id: str 61 | 62 | 63 | class _abyss(BaseModel): 64 | level: Optional[int] 65 | cup_number: Optional[int] 66 | level_of_quantum: Optional[str] 67 | level_of_ow: Optional[str] 68 | level_of_greedy: Optional[str] 69 | 70 | 71 | class _stats(BaseModel): 72 | active_day_number: int 73 | suit_number: int 74 | stigmata_number: int 75 | armor_number: int 76 | sss_armor_number: int 77 | battle_field_ranking_percentage: str 78 | new_abyss: Optional[_abyss] 79 | old_abyss: Optional[_abyss] 80 | weapon_number: int 81 | god_war_max_punish_level: int 82 | god_war_extra_item_number: int 83 | god_war_max_challenge_score: int 84 | god_war_max_challenge_level: int 85 | god_war_max_level_avatar_number: int 86 | god_war_max_support_point: int 87 | battle_field_area: int 88 | battle_field_score: int 89 | abyss_score: int 90 | battle_field_rank: int 91 | 92 | 93 | class _preference(BaseModel): 94 | abyss: int 95 | main_line: int 96 | battle_field: int 97 | open_world: int 98 | community: int 99 | comprehensive_score: int 100 | comprehensive_rating: str 101 | god_war: int 102 | is_god_war_unlock: bool 103 | 104 | 105 | class Index(BaseModel): 106 | role: _role 107 | stats: _stats 108 | preference: _preference 109 | 110 | 111 | class _boss(BaseModel): 112 | id: str 113 | name: str 114 | avatar: str 115 | 116 | 117 | class _avatar(BaseModel): 118 | """角色,不含武器圣痕""" 119 | 120 | id: str 121 | name: str 122 | star: int 123 | avatar_background_path: str 124 | icon_path: str 125 | background_path: str 126 | large_background_path: str 127 | figure_path: str 128 | level: int 129 | oblique_avatar_background_path: str 130 | half_length_icon_path: str 131 | image_path: str 132 | 133 | 134 | class _elf(BaseModel): 135 | id: int 136 | name: str 137 | avatar: str 138 | rarity: int 139 | star: int 140 | 141 | 142 | class AbyssReport(BaseModel): 143 | score: int 144 | updated_time_second: Optional[datetime] 145 | time_second: Optional[datetime] 146 | area: Optional[int] 147 | boss: _boss 148 | lineup: List[_avatar] 149 | rank: Optional[int] 150 | settled_cup_number: Optional[int] 151 | cup_number: Optional[int] 152 | elf: Optional[_elf] 153 | level: Union[int, str] # 段位 154 | settled_level: Optional[int] # 终极区深渊结算后段位 155 | reward_type: Optional[str] # 低级深渊升降级 156 | type: Optional[str] # 量子奇点|量子流形 157 | floor: Optional[int] # 量子流形层数,量子奇点为0 158 | 159 | 160 | class Abyss(BaseModel): 161 | reports: List[AbyssReport] 162 | 163 | 164 | class BattleFieldInfo(BaseModel): 165 | elf: Union[_elf, None] 166 | lineup: List[_avatar] 167 | boss: _boss 168 | score: int 169 | 170 | 171 | class BattleFieldReport(BaseModel): 172 | score: int 173 | rank: int 174 | ranking_percentage: str 175 | area: int 176 | battle_infos: List[BattleFieldInfo] 177 | time_second: datetime 178 | 179 | 180 | class BattleField(BaseModel): 181 | reports: List[BattleFieldReport] 182 | 183 | 184 | class godWarBuff(BaseModel): 185 | icon: str 186 | number: int 187 | id: int 188 | 189 | 190 | class godWarCondition(BaseModel): 191 | name: str 192 | desc: str 193 | difficulty: int 194 | 195 | 196 | class godWarRecord(BaseModel): 197 | settle_time_second: datetime 198 | score: int 199 | punish_level: int 200 | level: int 201 | buffs: List[godWarBuff] 202 | conditions: List[godWarCondition] 203 | main_avatar: _avatar 204 | support_avatars: List[_avatar] 205 | elf: Union[_elf, None] 206 | extra_item_icon: str 207 | 208 | 209 | class godWarCollection(BaseModel): 210 | type: str 211 | collected_number: int 212 | total_number: int 213 | 214 | 215 | class godWarSummary(BaseModel): 216 | max_level_avatar_number: int 217 | max_support_point: int 218 | extra_item_number: int 219 | max_punish_level: int 220 | max_challenge_score: int 221 | avatar_numbers: int 222 | max_challenge_level: int 223 | 224 | 225 | class godWarAvatar(BaseModel): 226 | avatar: _avatar 227 | level: int 228 | challenge_success_times: int 229 | max_challenge_score: int 230 | max_punish_level: int 231 | max_challenge_level: int 232 | 233 | 234 | class _godWar(BaseModel): 235 | records: List[godWarRecord] 236 | collections: List[godWarCollection] 237 | summary: godWarSummary 238 | avatar_transcript: List[godWarAvatar] 239 | 240 | 241 | class _weapon(BaseModel): 242 | id: int 243 | name: str 244 | max_rarity: int 245 | rarity: int 246 | icon: str 247 | 248 | 249 | class _stigamata(BaseModel): 250 | id: int 251 | name: str 252 | max_rarity: int 253 | rarity: int 254 | icon: str 255 | 256 | 257 | class Chara_chara(BaseModel): 258 | avatar: _avatar 259 | weapon: _weapon 260 | stigmatas: List[_stigamata] 261 | 262 | 263 | class Chara(BaseModel): 264 | character: Chara_chara 265 | is_chosen: bool 266 | 267 | 268 | class Character(BaseModel): 269 | characters: List[Chara] 270 | 271 | 272 | class FullInfo(BaseModel): 273 | """all in one""" 274 | 275 | godWar: Optional[_godWar] 276 | characters: Optional[Character] 277 | index: Index 278 | newAbyssReport: Optional[Abyss] 279 | latestOldAbyssReport: Optional[Abyss] 280 | weeklyReport: WeeklyReport 281 | battleFieldReport: BattleField 282 | 283 | 284 | # 手账部分 285 | class sourcepercent(BaseModel): 286 | action_id: int 287 | num: int 288 | name: str 289 | percent: int 290 | 291 | 292 | class LastMonthInfo(BaseModel): 293 | group_by: List[sourcepercent] 294 | month_star: int 295 | month_hcoin: int 296 | last_month_star: int 297 | last_month_hcoin: int 298 | star_rate: int 299 | hcoin_rate: int 300 | month_start: datetime 301 | month_end: datetime 302 | month: int 303 | last_month: int 304 | uid: str 305 | month_level: int 306 | 307 | 308 | class findex(BaseModel): 309 | uid: str 310 | date: date 311 | month: int 312 | month_hcoin: int 313 | month_star: int 314 | month_level: int 315 | day_hcoin: int 316 | day_star: int 317 | last_hcoin: int 318 | last_star: int 319 | 320 | 321 | class finance_record(BaseModel): 322 | action_id: int 323 | time: datetime 324 | add_num: int 325 | action: str 326 | 327 | 328 | class FinanceRecord(BaseModel): 329 | """水晶星石通用""" 330 | page: int 331 | month: int 332 | list: List[finance_record] 333 | 334 | 335 | class FinanceInfo(BaseModel): 336 | getLastMonthInfo: LastMonthInfo 337 | index: findex 338 | getHcoinRecords: FinanceRecord 339 | getStarRecords: FinanceRecord 340 | 341 | 342 | class result(BaseModel): 343 | """签到用""" 344 | region:str 345 | game_uid:str 346 | nickname:str 347 | level:int 348 | region_name:str 349 | total_sign_day:int 350 | is_sign:bool 351 | reward_icon:str 352 | reward_name:str 353 | reward_cnt:int 354 | # reward_total_sign_day:int 355 | # reward_today:str 356 | # icon:str 357 | # name:str 358 | # cnt:int 359 | # reward_sign_cnt_missed:int 360 | today:str 361 | status:str 362 | addons:str 363 | sign_response:Optional[dict] 364 | end:str -------------------------------------------------------------------------------- /modules/query.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import datetime 3 | import hashlib 4 | import json 5 | import os 6 | import random 7 | import re 8 | import time 9 | from http.cookies import SimpleCookie 10 | from operator import itemgetter 11 | from typing import Tuple 12 | 13 | import httpx 14 | 15 | from .database import DB 16 | from .mytyping import config 17 | from .util import InfoError, NotBindError, cache 18 | 19 | COOKIES = config.cookies[0] 20 | 21 | 22 | class MysApi(object): 23 | """用于生成api""" 24 | 25 | BASE = "https://api-takumi-record.mihoyo.com/game_record/app/honkai3rd/api" 26 | API = { 27 | "往事乐土": f"{BASE}/godWar?server={{serverid}}&role_id={{roleid}}", 28 | "我的女武神": f"{BASE}/characters?server={{serverid}}&role_id={{roleid}}", 29 | "数据总览": f"{BASE}/index?server={{serverid}}&role_id={{roleid}}", 30 | "深渊战报_超弦空间": f"{BASE}/newAbyssReport?server={{serverid}}&role_id={{roleid}}", 31 | "深渊战报_量子奇点": f"{BASE}/oldAbyssReport?server={{serverid}}&role_id={{roleid}}&abyss_type=1", 32 | "深渊战报_迪拉克之海": f"{BASE}/oldAbyssReport?server={{serverid}}&role_id={{roleid}}&abyss_type=2", 33 | "深渊战报_latest": f"{BASE}/latestOldAbyssReport?server={{serverid}}&role_id={{roleid}}", 34 | "一周成绩单": f"{BASE}/weeklyReport?server={{serverid}}&role_id={{roleid}}", 35 | "战场战报": f"{BASE}/battleFieldReport?server={{serverid}}&role_id={{roleid}}", 36 | "常用工具": f"{BASE}/tools", 37 | "获取自己角色": "https://api-takumi-record.mihoyo.com/binding/api/getUserGameRolesByCookie", 38 | "获取他人角色": f"https://api-takumi-record.mihoyo.com/game_record/app/card/wapi/getGameRecordCard?uid={{mysuid}}", 39 | "上月手账": f"https://api.mihoyo.com/bh3-weekly_finance/api/getLastMonthInfo?game_biz=bh3_cn&bind_uid={{roleid}}&bind_region={{serverid}}", 40 | "本月手账": f"https://api.mihoyo.com/bh3-weekly_finance/api/index?game_biz=bh3_cn&bind_uid={{roleid}}&bind_region={{serverid}}", 41 | "水晶明细": f"https://api.mihoyo.com/bh3-weekly_finance/api/getHcoinRecords?page=1&limit=20&game_biz=bh3_cn&bind_uid={{roleid}}&bind_region={{serverid}}", 42 | "星石明细": f"https://api.mihoyo.com/bh3-weekly_finance/api/getStarRecords?page=1&limit=20&game_biz=bh3_cn&bind_uid={{roleid}}&bind_region={{serverid}}", 43 | } 44 | 45 | def __init__(self, server_id, role_id, mysid=None) -> None: 46 | super().__init__() 47 | self.server = server_id 48 | self.uid = role_id 49 | if mysid is not None: 50 | try: 51 | self.mid = str(int(mysid)) 52 | self.getrole = self.generate("获取他人角色", self.mid) 53 | except ValueError: 54 | raise ValueError(f"{mysid}\n米游社ID格式不对") 55 | self.godWar = self.generate("往事乐土") 56 | self.valkyrie = self.generate("我的女武神") 57 | self.index = self.generate("数据总览") 58 | self.newAbyss = self.generate("深渊战报_超弦空间") 59 | self.oldAbyss_quantum = self.generate("深渊战报_量子奇点") 60 | self.oldAbyss_dirac = self.generate("深渊战报_迪拉克之海") 61 | self.oldAbyss_lastest = self.generate("深渊战报_latest") 62 | self.weekly = self.generate("一周成绩单") 63 | self.battleField = self.generate("战场战报") 64 | self.getself = self.generate("获取自己角色") 65 | self._for_iter = [ 66 | self.godWar, 67 | self.valkyrie, 68 | self.index, 69 | self.newAbyss, 70 | self.oldAbyss_lastest, 71 | self.weekly, 72 | self.battleField, 73 | ] 74 | 75 | def generate(self, typename: str, *ids) -> str: 76 | """typename:URL类型;ids:3种id""" 77 | # todo: change *ids to details 78 | url_origin = self.API[typename] 79 | if len(ids) == 2: 80 | sid = ids[0] 81 | rid = ids[1] 82 | mid = "" 83 | elif len(ids) == 1: 84 | sid = "" 85 | rid = "" 86 | mid = ids[0] 87 | else: 88 | sid = self.server 89 | rid = self.uid 90 | mid = "" 91 | return url_origin.format(serverid=sid, roleid=rid, mysuid=mid) 92 | 93 | def __iter__(self): 94 | return iter(self._for_iter) 95 | 96 | 97 | class GetInfo(MysApi): 98 | """继承自MysApi,用于获取信息""" 99 | 100 | MHY_VERSION = "2.11.1" 101 | 102 | def __init__( 103 | self, mysid: str = None, server_id: str = None, role_id: str = None 104 | ) -> None: 105 | """若传入mysid则server_id及role_id不生效.""" 106 | if mysid is not None: 107 | try: 108 | mid = str(int(mysid)) 109 | except ValueError: 110 | raise InfoError(f"{mysid}米游社id格式错误.") 111 | server_id, role_id = self.mys2role(self.generate("获取他人角色", mid)) 112 | super().__init__(server_id, role_id, mysid) 113 | 114 | @classmethod 115 | def md5(cls, text): 116 | md5 = hashlib.md5() 117 | md5.update(text.encode()) 118 | return md5.hexdigest() 119 | 120 | @classmethod 121 | def DSGet(cls, q="", b=None): 122 | if b: 123 | br = json.dumps(b) 124 | else: 125 | br = "" 126 | s = "xV8v4Qu54lUKrEYFZkJhB8cuOh9Asafs" 127 | t = str(int(time.time())) 128 | r = str(random.randint(100000, 200000)) 129 | c = cls.md5("salt=" + s + "&t=" + t + "&r=" + r + "&b=" + br + "&q=" + q) 130 | return t + "," + r + "," + c 131 | 132 | async def all(self, api: MysApi = None) -> dict: 133 | """获取所有信息,接受传入MysApi对象""" 134 | if api is None: 135 | api = self 136 | if isinstance(api, MysApi): 137 | info = {} 138 | for url in api: 139 | item, data = await self.fetch(url) 140 | # if item in info: 141 | # item += "_greedy" # 处理2种深渊数据覆盖问题 142 | info.update({item: data["data"]}) 143 | return info 144 | 145 | async def part(self, api: MysApi = None): 146 | """不查询角色,乐土等,以减少开销""" 147 | if api is None: 148 | api = self 149 | info = {} 150 | for url in api: 151 | if "characters" in url or "godWar" in url: 152 | continue 153 | else: 154 | item, data = await self.fetch(url) 155 | # if item in info: 156 | # item += "_greedy" # 处理2种深渊数据覆盖问题 157 | info.update({item: data["data"]}) 158 | return info 159 | 160 | @classmethod 161 | def gen_header(cls, ds: str, cookie: str): 162 | headers = { 163 | "DS": cls.DSGet(ds), 164 | "x-rpc-app_version": cls.MHY_VERSION, 165 | "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1", 166 | "x-rpc-client_type": "5", 167 | "Referer": "https://webstatic.mihoyo.com/", 168 | "Cookie": cookie, 169 | } 170 | return headers 171 | 172 | @staticmethod 173 | @cache(ttl=datetime.timedelta(minutes=10), arg_key="url") 174 | async def fetch(url, cookie=None) -> Tuple[str, dict]: 175 | """查询,单项数据""" 176 | cookie = cookie if cookie is not None else COOKIES 177 | try: 178 | server, uid = [temp[1:] for temp in re.findall(r"=[a-z0-9]{4,}", url)] 179 | headers = GetInfo.gen_header("role_id=" + uid + "&server=" + server, cookie) 180 | item = re.search(r"/\w+\?", url).group()[1:-1] 181 | except ValueError: 182 | # raise ValueError(f"{url}\napi格式不对") 183 | headers = GetInfo.gen_header("", cookie) 184 | item = url.split("/")[-1] 185 | """高级区及以下的深渊查询api不可用,使用latest代替""" 186 | async with httpx.AsyncClient() as aiorequests: 187 | req = await aiorequests.get( 188 | url=url, 189 | headers=headers, 190 | ) 191 | data = json.loads(req.text) 192 | # print(data) 193 | retcode = data["retcode"] 194 | if retcode == 1008: 195 | raise InfoError("uid与服务器不匹配") 196 | elif retcode == 10102: 197 | raise InfoError(f"账号数据非公开,请前往米游社修改.") 198 | elif retcode == 10001: 199 | raise InfoError("登录失效,请重新登录.") 200 | elif retcode == 0 or retcode == -1: 201 | # 0:正常获取;-1:等级与深渊不匹配 202 | if item == "index" and "api-takumi" in url: 203 | data["data"]["role"].update({"role_id": uid}) # index添加role_id 204 | return item, data 205 | else: 206 | raise InfoError(f"{data}") 207 | 208 | @classmethod 209 | def mys2role(cls, url) -> Tuple[str, str]: 210 | """通过米游社id查询游戏角色""" 211 | try: 212 | mid = re.search(r"\?\w+=\d+", url).group()[1:] 213 | except ValueError: 214 | raise ValueError(f"api格式不对") 215 | item = re.search(r"/\w+\?", url).group()[1:-1] 216 | req = httpx.get(url=url, headers=cls.gen_header(mid, COOKIES)) 217 | data = json.loads(req.text) 218 | for game in data["data"]["list"]: 219 | if game["game_id"] == 1: 220 | rid = game["game_role_id"] # 游戏id 221 | region = game["region"] # 渠道代码 222 | region_name = game["region_name"] 223 | return region, rid 224 | raise IndexError(f"该用户没有崩坏3角色.") 225 | 226 | 227 | FINANCE_CACHE = {} 228 | 229 | 230 | class Finance(GetInfo): 231 | def get_role(self, all: bool = False): 232 | url = "https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie" 233 | if not all: 234 | url = url + "?game_biz=bh3_cn" 235 | resp = httpx.get(url=url, headers=self.gen_header("", self.cookie.strip())) 236 | retcode = resp.json()["retcode"] 237 | if retcode != 0: 238 | raise InfoError(f"{resp.json()['message']}") 239 | else: 240 | data = resp.json()["data"]["list"] 241 | if data: 242 | data.sort(key=itemgetter("level"), reverse=True) 243 | data = data[0] 244 | else: 245 | raise InfoError(f"{resp.text}\n当前绑定的账号没有崩坏3游戏信息") 246 | server_id = data["region"] 247 | role_id = data["game_uid"] 248 | FINANCE_CACHE.update( 249 | {self.account_id: {"server_id": server_id, "role_id": role_id}} 250 | ) 251 | return server_id, role_id 252 | 253 | def __init__(self, qid: str, cookieraw: str = None) -> None: 254 | """初始化传入qid,调取数据库查找cookie.""" 255 | self.db = DB("uid.sqlite", "qid_uid") 256 | if cookieraw is not None: 257 | cookietemp = SimpleCookie() 258 | cookietemp.load( 259 | dict(zip(["account_id", "cookie_token"], cookieraw.split(","))) 260 | ) 261 | self.cookie = cookietemp.output(header="", sep=";").strip() 262 | else: 263 | cookie = self.db.get_cookie(qid) 264 | if cookie is None: 265 | raise InfoError(f"尚未绑定\n{NotBindError.msg}") 266 | self.cookie = cookie 267 | self.account_id = SimpleCookie(self.cookie)["account_id"].value 268 | if self.account_id in FINANCE_CACHE: 269 | server_id = FINANCE_CACHE[self.account_id]["server_id"] 270 | role_id = FINANCE_CACHE[self.account_id]["role_id"] 271 | else: 272 | server_id, role_id = self.get_role() 273 | if "cookie" not in locals(): 274 | self.db.set_cookie(qid, self.cookie) 275 | super().__init__(server_id=server_id, role_id=role_id) 276 | self.lastfinance = self.generate("上月手账") 277 | self.thisfinance = self.generate("本月手账") 278 | self.hcoin = self.generate("水晶明细") 279 | self.starstone = self.generate("星石明细") 280 | self.finance = [self.lastfinance, self.thisfinance, self.hcoin, self.starstone] 281 | 282 | async def get_finance(self): 283 | financedata = {} 284 | for url in self.finance: 285 | item, data = await self.fetch(url, self.cookie) 286 | financedata.update({item: data["data"]}) 287 | return financedata 288 | -------------------------------------------------------------------------------- /modules/util.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import functools 3 | import inspect 4 | import json 5 | import os 6 | 7 | from .mytyping import config 8 | 9 | # 一些egenshin的轮子,感谢艾琳佬 10 | 11 | 12 | def cache(ttl=datetime.timedelta(hours=1), **kwargs): 13 | def wrap(func): 14 | cache_data = {} 15 | 16 | @functools.wraps(func) 17 | async def wrapped(*args, **kw): 18 | nonlocal cache_data 19 | bound = inspect.signature(func).bind(*args, **kw) 20 | bound.apply_defaults() 21 | ins_key = "|".join(["%s_%s" % (k, v) for k, v in bound.arguments.items()]) 22 | default_data = {"time": None, "value": None} 23 | data = cache_data.get(ins_key, default_data) 24 | 25 | now = datetime.datetime.now() 26 | if not data["time"] or now - data["time"] > ttl: 27 | try: 28 | data["value"] = await func(*args, **kw) 29 | data["time"] = now 30 | cache_data[ins_key] = data 31 | except Exception as e: 32 | raise e 33 | 34 | return data["value"] 35 | 36 | return wrapped 37 | 38 | return wrap 39 | 40 | 41 | class NotBindError(Exception): 42 | msg = """ 43 | * 这个插件需要获取账号cookie, 外泄有可能导致您的账号遭受损失, 请注意相关事项再进行绑定, 造成一切损失由用户自行承担 44 | * 修改密码可以直接使其失效 45 | 46 | 1. 打开米游社(https://bbs.mihoyo.com/ys/) 47 | 2. 登录游戏账号 48 | 3. F12打开控制台 49 | 4. 输入以下代码运行 50 | javascript:(()=>{_=(n)=>{for(i in(r=document.cookie.split(";"))){var arr=r[i].split("=");if(arr[0].trim()==n)return arr[1];}};c=_("cookie_token")||alert('请重新登录');m=_("account_id")+","+c;c&&confirm('确定复制到剪切板?:'+m)&©(m)})(); 51 | 5. 复制提示的内容, 私聊发给机器人 52 | 私聊格式为 53 | bhf绑定0000000,xxxxxxxxxxxx 54 | 55 | 其中0000000,xxxxxxxxxxxx是复制的内容 56 | 57 | 如果你想查看另外个方法可以发送 bhf?2 58 | * 同时兼容手机端""" 59 | msg2 = """ 60 | 如果你是PC端,浏览器需要安装tampermonkey插件(https://www.tampermonkey.net/) 61 | 如果你是手机端,可以下载油猴浏览器(http://www.youhouzi.cn/),并且在右下角打开菜单 [打开电脑模式] ,之后在[脚本管理]->[启用脚本功能] 62 | 63 | 然后打开链接安装脚本 https://greasyfork.org/scripts/435553-%E7%B1%B3%E6%B8%B8%E7%A4%BEcookie/code/%E7%B1%B3%E6%B8%B8%E7%A4%BEcookie.user.js 64 | 65 | 就可以访问米游社进行登录了 66 | 提示复制的内容可以直接私聊发给机器人 67 | 68 | 私聊格式为 69 | 70 | bhf绑定0000000,xxxxxxxxxxxx 71 | 72 | 其中0000000,xxxxxxxxxxxx是复制的内容 73 | """ 74 | 75 | 76 | class InfoError(Exception): 77 | def __init__(self, errorinfo) -> None: 78 | super().__init__(errorinfo) 79 | self.errorinfo = errorinfo 80 | 81 | def __str__(self) -> str: 82 | return self.errorinfo 83 | 84 | def __repr__(self) -> str: 85 | return str(self.errorinfo) 86 | 87 | 88 | class CookieNotBindError(InfoError): 89 | def __repr__(self) -> str: 90 | if config.is_egenshin: 91 | pass 92 | return super().__repr__() 93 | 94 | 95 | class ItemTrans(object): 96 | """ 97 | - 数字/字母 -> 文字 98 | - 文字 -> server_id""" 99 | 100 | def __init__(self) -> None: 101 | super().__init__() 102 | 103 | @staticmethod 104 | def area(no): 105 | """分组""" 106 | if no is None: 107 | no = 0 108 | level = ["初级区", "中级区", "高级区", "终极区"] 109 | return level[no - 1] 110 | 111 | @staticmethod 112 | def abyss_type(_type): 113 | if _type is None: 114 | return "超弦空间" 115 | t = {"OW": "迪拉克之海", "Quantum": "量子奇点", "Greedy": "量子流形"} 116 | return t[_type] 117 | 118 | @staticmethod 119 | def oldAbyssLevelChange(reward_type): 120 | """老深渊段位变化""" 121 | reward = {"Degrade": "降级", "Upgrade": "晋级", "Relegation": "保级"} 122 | return reward[reward_type] 123 | 124 | @staticmethod 125 | def abyss_level(no): 126 | """通用""" 127 | if isinstance(no, str) and no.startswith("Unknown"): 128 | return f"无数据" 129 | level = { 130 | 0: "未战斗", 131 | 1: "禁忌", 132 | 2: "原罪Ⅰ", 133 | 3: "原罪Ⅱ", 134 | 4: "原罪Ⅲ", 135 | 5: "苦痛Ⅰ", 136 | 6: "苦痛Ⅱ", 137 | 7: "苦痛Ⅲ", 138 | 8: "红莲", 139 | 9: "寂灭", 140 | "A": "红莲", 141 | "B": "苦痛", 142 | "C": "原罪", 143 | "D": "禁忌", 144 | } 145 | return level[no] 146 | 147 | @staticmethod 148 | def server2id(no: str): 149 | """渠道名转渠道代码""" 150 | no = no.lower().strip() 151 | if no.endswith("服"): 152 | no = no[:-1] 153 | with open( 154 | os.path.join(os.path.dirname(__file__), "../region.json"), 155 | "r", 156 | encoding="utf8", 157 | ) as f: 158 | region = json.load(f) 159 | f.close() 160 | for server_id, alias in region.items(): 161 | if no in alias["alias"] or no == alias["name"]: 162 | return server_id 163 | raise InfoError(f"找不到渠道{no}的数据,可以尝试输入账号所在的服务器,如安卓3服") 164 | 165 | @staticmethod 166 | def id2server(region_id): 167 | """渠道代码转渠道名""" 168 | with open( 169 | os.path.join(os.path.dirname(__file__), "../region.json"), 170 | "r", 171 | encoding="utf8", 172 | ) as f: 173 | region = json.load(f) 174 | f.close() 175 | return region[region_id]["name"] 176 | 177 | @staticmethod 178 | def rate2png(rate): 179 | """综合评价 -> 图片地址""" 180 | BASE = os.path.join(os.path.dirname(__file__), "../assets/star") 181 | rating_png = {"C": "a.png", "B": "s.png", "A": "ss.png", "S": "sss.png"} 182 | return os.path.join(BASE, rating_png[rate]) 183 | 184 | @staticmethod 185 | def star(_st: int, is_elf: bool = False): 186 | """星级图片""" 187 | base = os.path.join(os.path.dirname(__file__), "../assets/star") 188 | if is_elf: 189 | num = [1, 2, 2, 3, 3, 3, 4][_st - 1] 190 | 191 | else: 192 | num = ["b", "a", "s", "ss", "sss"][_st - 1] 193 | return os.path.join(base, f"{num}.png") 194 | -------------------------------------------------------------------------------- /region.json: -------------------------------------------------------------------------------- 1 | { 2 | "android01": { 3 | "name": "官", 4 | "alias": [ 5 | "安卓1", 6 | "安卓一", 7 | "官", 8 | "国", 9 | "安卓国", 10 | "安卓官" 11 | ] 12 | }, 13 | "bb01": { 14 | "name": "B", 15 | "alias": [ 16 | "安卓2", 17 | "安卓二", 18 | "b", 19 | "bilibili", 20 | "bili", 21 | "哔哩哔哩", 22 | "哔哩", 23 | "逼站", 24 | "b站", 25 | "哔" 26 | ] 27 | }, 28 | "hun01": { 29 | "name": "安卓3", 30 | "alias": [ 31 | "安卓三", 32 | "华为", 33 | "vivo", 34 | "oppo", 35 | "渠道1", 36 | "渠道一" 37 | ] 38 | }, 39 | "hun02": { 40 | "name": "安卓4", 41 | "alias": [ 42 | "小米", 43 | "360", 44 | "豌豆荚", 45 | "九游", 46 | "渠道2", 47 | "渠道二", 48 | "安卓四" 49 | ] 50 | }, 51 | "pc01": { 52 | "name": "桌面", 53 | "alias": [ 54 | "桌面", 55 | "全平台" 56 | ] 57 | }, 58 | "yyb01": { 59 | "name": "宝", 60 | "alias": [ 61 | "应用宝", 62 | "宝" 63 | ] 64 | }, 65 | "ios01": { 66 | "name": "iOS", 67 | "alias": [ 68 | "ios", 69 | "苹果", 70 | "果", 71 | "apple" 72 | ] 73 | } 74 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow<9.2.0 2 | pydantic 3 | PyYAML 4 | httpx 5 | sqlitedict 6 | genshinhelper>=2.1.1 7 | --------------------------------------------------------------------------------