├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .vscode ├── extensions.json └── settings.json ├── LICENSE ├── README.md ├── nonebot_plugin_bilifan ├── __init__.py ├── login │ └── __init__.py ├── main.py ├── src │ ├── __init__.py │ ├── api.py │ └── user.py ├── users.yaml └── utils.py └── pyproject.toml /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | push: 13 | branches: [ main ] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | deploy: 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - name: Set up Python 26 | uses: actions/setup-python@v3 27 | with: 28 | python-version: '3.x' 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install build 33 | - name: Build package 34 | run: python -m build 35 | - name: Publish package 36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | 41 | -------------------------------------------------------------------------------- /.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 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 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 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_install_hook_types: [pre-commit, prepare-commit-msg] 2 | ci: 3 | autofix_commit_msg: ':rotating_light: auto fix by pre-commit hooks' 4 | autofix_prs: true 5 | autoupdate_branch: main 6 | autoupdate_schedule: monthly 7 | autoupdate_commit_msg: ':arrow_up: auto update by pre-commit hooks' 8 | 9 | repos: 10 | - repo: https://github.com/astral-sh/ruff-pre-commit 11 | rev: v0.6.9 12 | hooks: 13 | - id: ruff 14 | args: [--fix, --exit-non-zero-on-fix] 15 | 16 | # - repo: https://github.com/RobertCraigie/pyright-python 17 | # rev: v1.1.318 18 | # hooks: 19 | # - id: pyright 20 | 21 | - repo: https://github.com/psf/black 22 | rev: 24.8.0 23 | hooks: 24 | - id: black 25 | stages: [pre-commit] 26 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-python.python", 4 | "ms-python.vscode-pylance", 5 | "ms-python.isort", 6 | "ms-python.black-formatter" 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.languageServer": "Pylance", 3 | "python.analysis.typeCheckingMode": "basic", 4 | "editor.formatOnSave": true, 5 | "[python]": { 6 | "editor.defaultFormatter": "ms-python.black-formatter", 7 | "editor.formatOnSave": true, 8 | "editor.codeActionsOnSave": { 9 | "source.organizeImports": "explicit" 10 | } 11 | }, 12 | "isort.args": [ 13 | "--profile", 14 | "black" 15 | ], 16 | "python.formatting.provider": "black" 17 | } -------------------------------------------------------------------------------- /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 | 2 |
3 | AgnesDigitalLogo 4 |
5 |

NoneBotPluginText

6 |
7 | 8 |
9 | 10 | # nonebot_plugin_bilifan 11 | 12 | _✨ 自动 b 站粉丝牌 ✨_ 13 | 14 | 15 | GitHub stars 16 | 17 | 18 | GitHub issues 19 | 20 | 21 | QQ Chat Group 22 | 23 | 24 | pypi 25 | 26 | python 27 | NoneBot 28 |
29 | 30 | ## 最新说明~~叔叔不要麻辣~~ 31 | 32 | - 2025.6.2 本次更新配置文件有变更,需要手动同步最新配置 33 | - 已修复二维码获取 sk 失败的问题 34 | - alconna 支持替换 saa 支持 35 | 36 | ## 配置说明 37 | 38 | 启动一次插件,在 bot 路径下,"data/bilifan"文件夹内,按需求修改"users.yaml"文件 39 | 运行跨平台使用,支持 alconna 下所有适配器 40 | 41 | ## 指令 42 | 43 | - b站登录 - 返回 b 站二维码,扫码登录,绑定 qq 号 44 | - 删除登录信息 - 删除登录信息和绑定 45 | - 开始刷牌子 - 开始执行命令 46 | - 自动刷牌子 - 添加或取消定时任务 47 | - 取消自动刷牌子 - 取消定时任务 48 | - 删除全部的定时任务 - [超管]删除全部的定时任务 49 | - b站删除配置 - [超管]删除全部配置文件=初始化 50 | 51 | 52 | 53 | ## 🙈 其他 54 | 55 | - 本项目仅供学习使用,请勿用于商业用途,喜欢该项目可以 Star 或者提供 PR 56 | - [爱发电](https://afdian.net/a/agnes_digital) 57 | - [GPL-3.0 License](https://github.com/Agnes4m/nonebot_plugin_bilifan/blob/main/LICENSE) ©[@Agnes4m](https://github.com/Agnes4m) 58 | 59 | ## 🌐 感谢 60 | 61 | - [新 B 站粉丝牌助手 - XiaoMiku01](https://github.com/XiaoMiku01/fansMedalHelper) - 源代码来自于他 62 | - [新 B 站粉丝牌助手 - cyb233](https://github.com/cyb233/fansMedalHelper) - 改进代码来自于他 63 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/__init__.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | from pathlib import Path 3 | from typing import List 4 | 5 | # import aiohttp 6 | from nonebot import get_driver, on_command, require 7 | from nonebot.adapters import Event 8 | from nonebot.log import logger 9 | from nonebot.matcher import Matcher 10 | from nonebot.permission import SUPERUSER 11 | from nonebot.plugin import PluginMetadata, inherit_supported_adapters 12 | 13 | from .login import draw_QR, get_tv_qrcode_url_and_auth_code, verify_login 14 | from .main import mains, read_yaml 15 | from .src import BiliUser # noqa: F401 16 | from .utils import auto_cup, load_config, save_config 17 | 18 | try: 19 | require("nonebot_plugin_apscheduler") 20 | from nonebot_plugin_apscheduler import scheduler 21 | except BaseException: 22 | scheduler = None 23 | require("nonebot_plugin_alconna") 24 | from nonebot_plugin_alconna import UniMessage # noqa: E402 25 | 26 | logger.opt(colors=True).info( 27 | ( 28 | "已检测到软依赖nonebot_plugin_apscheduler, 开启定时任务功能" 29 | if scheduler 30 | else "未检测到软依赖nonebot_plugin_apscheduler禁用定时任务功能" 31 | ), 32 | ) 33 | 34 | 35 | driver = get_driver() 36 | __version__ = "0.4.4" 37 | __plugin_meta__ = PluginMetadata( 38 | name="bilifan", 39 | description="b站粉丝牌~", 40 | usage="发送 开始刷牌子 即可", 41 | type="application", 42 | homepage="https://github.com/Agnes4m/nonebot_plugin_bilifan", 43 | supported_adapters=inherit_supported_adapters("nonebot_plugin_alconna"), 44 | extra={ 45 | "version": __version__, 46 | "author": "Agnes4m ", 47 | }, 48 | ) 49 | 50 | login_in = on_command("blogin", aliases={"b站登录"}, block=False) 51 | login_del = on_command("blogin_del", aliases={"删除登录信息"}, block=False) 52 | fan_once = on_command("bfan", aliases={"开始刷牌子", "开始粉丝牌"}, block=False) 53 | fan_auto = on_command( 54 | "addfan", 55 | aliases={"自动刷牌子", "自动粉丝牌"}, 56 | priority=40, 57 | block=False, 58 | ) 59 | del_only = on_command("bdel", aliases={"取消自动刷牌子", "取消自动粉丝牌"}, block=False) 60 | del_all = on_command( 61 | "bdel_all", 62 | aliases={"删除全部定时任务"}, 63 | block=False, 64 | permission=SUPERUSER, 65 | ) 66 | del_config = on_command( 67 | "bdel_config", 68 | aliases={"b站删除配置"}, 69 | block=False, 70 | permission=SUPERUSER, 71 | ) 72 | 73 | 74 | @login_in.handle() 75 | async def _(matcher: Matcher, event: Event): 76 | try: 77 | login_url, auth_code = await get_tv_qrcode_url_and_auth_code() 78 | except Exception as e: 79 | print(e) 80 | await matcher.finish("已超时,请稍后重试!") 81 | data_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}") 82 | data_path.mkdir(parents=True, exist_ok=True) 83 | data = await draw_QR(login_url) 84 | forward_msg = "本功能会调用并保存b站登录信息的cookie,请确保你在信任本机器人主人的情况下登录,如果出现财产损失,本作者对此不负责任" 85 | try: 86 | # if isinstance(event, GroupEvent): 87 | # await bot.call_api( 88 | # "send_group_forward_msg", group_id=event.group_id, messages=forward_msg 89 | # ) 90 | # else: 91 | await UniMessage.text(forward_msg).send() 92 | await UniMessage.image(raw=data).send() 93 | except Exception: 94 | logger.warning("二维码可能被风控,发送链接") 95 | await matcher.send("将此链接复制到手机B站打开:" + login_url) 96 | while True: 97 | a = await verify_login(auth_code, data_path) 98 | if a: 99 | await matcher.send(f"登录成功!\nqq:{event.get_user_id()}\n{a}") 100 | break 101 | await matcher.finish("登录失败!") 102 | 103 | 104 | @login_del.handle() 105 | async def _(matcher: Matcher, event: Event): 106 | config = load_config() 107 | msg_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}/login_info.txt") 108 | if msg_path.is_file() and event.get_user_id() in config: 109 | del config[event.get_user_id()] 110 | save_config(config) 111 | logger.info(f"已删除{event.get_user_id()}的定时任务") 112 | try: 113 | data_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}") 114 | shutil.rmtree(data_path) 115 | await matcher.finish(f"已删除{event.get_user_id()}的所有登录信息") 116 | except (FileNotFoundError, SystemExit): 117 | await matcher.finish("你尚未登录,无法删除登录信息") 118 | 119 | 120 | @fan_once.handle() 121 | async def _(matcher: Matcher, event: Event): 122 | data_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}") 123 | data_path.mkdir(parents=True, exist_ok=True) 124 | msg_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}/login_info.txt") 125 | try: 126 | if msg_path.is_file(): 127 | logger.info(msg_path) 128 | users = await read_yaml(Path().joinpath("data/bilifan")) 129 | watchinglive: int = users.get("WATCHINGLIVE", None) 130 | await matcher.send(f"开始执行,预计将在粉丝牌数量*{watchinglive}分钟后完成~") 131 | else: 132 | logger.info(msg_path) 133 | await matcher.finish("你尚未登录,请输入【b站登录】") 134 | messageList: List[str] = await mains(msg_path.parent) 135 | message_str = "\n".join(messageList) 136 | await matcher.finish(message_str) 137 | except (FileNotFoundError, SystemExit): 138 | await matcher.finish("你尚未登录,请输入【b站登录】") 139 | 140 | 141 | @fan_auto.handle() 142 | async def _(matcher: Matcher, event: Event): 143 | config = load_config() 144 | group_id = event.get_session_id() 145 | 146 | msg_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}/login_info.txt") 147 | if msg_path.is_file(): 148 | if event.get_user_id() in config: 149 | users = await read_yaml(Path().joinpath("data/bilifan")) 150 | cron = users.get("CRON", None) 151 | try: 152 | fields = cron.split(" ") 153 | await matcher.finish( 154 | f"{event.get_user_id()}的定时任务已存在,将在每天{fields[1]}时{fields[0]}分后开始执行~", 155 | ) 156 | except AttributeError: 157 | await matcher.finish("定时格式不正确,请删除定时任务后重新设置") 158 | else: 159 | config[event.get_user_id()] = group_id 160 | save_config(config) 161 | users = await read_yaml(Path().joinpath("data/bilifan")) 162 | cron = users.get("CRON", None) 163 | try: 164 | fields = cron.split(" ") 165 | await matcher.finish( 166 | f"已增加{event.get_user_id()}的定时任务,将在每天{fields[1]}时{fields[0]}分后开始执行~", 167 | ) 168 | except AttributeError: 169 | await matcher.finish("定时格式不正确,无法设置定时任务") 170 | else: 171 | await matcher.finish("你尚未登录,请输入【b站登录】") 172 | 173 | 174 | @del_only.handle() 175 | async def _(matcher: Matcher, event: Event): 176 | config = load_config() 177 | msg_path = Path().joinpath(f"data/bilifan/{event.get_user_id()}/login_info.txt") 178 | if msg_path.is_file(): 179 | if event.get_user_id() in config: 180 | del config[event.get_user_id()] 181 | save_config(config) 182 | await matcher.finish(f"已删除{event.get_user_id()}的定时任务") 183 | else: 184 | await matcher.finish(f"{event.get_user_id()}未设置定时任务") 185 | 186 | 187 | @del_all.handle() 188 | async def _(matcher: Matcher): 189 | msg_path = Path().joinpath("data/bilifan/config.yaml") 190 | msg_path.unlink() 191 | await matcher.finish("已删除全部定时刷牌子任务") 192 | 193 | 194 | @driver.on_bot_connect 195 | async def _(): 196 | users = await read_yaml(Path().joinpath("data/bilifan")) 197 | cron = users.get("CRON", None) 198 | try: 199 | fields = cron.split(" ") 200 | except AttributeError: 201 | logger.error("定时格式不正确,不启用定时功能") 202 | return 203 | if scheduler is None: 204 | logger.error("定时格式不正确,不启用定时功能") 205 | return 206 | try: 207 | logger.info(f"定时任务已配置,将在每天{fields[1]}时{fields[0]}分后自动执行~") 208 | scheduler.add_job( 209 | auto_cup, 210 | "cron", 211 | hour=fields[1], 212 | minute=fields[0], 213 | id="auto_cup", 214 | ) 215 | except Exception: 216 | logger.warning("定时任务已存在") 217 | 218 | 219 | @del_config.handle() 220 | async def _(matcher: Matcher, event: Event): 221 | """删除配置文件""" 222 | folder_path = Path().joinpath("data/bilifan") 223 | if folder_path.exists(): 224 | # 删除文件夹及其所有内容 225 | shutil.rmtree(folder_path) 226 | print(f"已删除文件夹: {folder_path}") 227 | else: 228 | print(f"文件夹不存在: {folder_path}") 229 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/login/__init__.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import hashlib 3 | import shutil 4 | import time 5 | import urllib.parse as urlparse 6 | from io import BytesIO 7 | from pathlib import Path 8 | 9 | import aiohttp 10 | import anyio 11 | import qrcode 12 | import yaml 13 | from nonebot.log import logger 14 | 15 | csrf = "" 16 | access_key = "" 17 | base_path = Path().joinpath("data/bilifan") 18 | 19 | 20 | async def is_login(session, cookies): 21 | api = "https://api.bilibili.com/x/web-interface/nav" 22 | headers = { 23 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69", 24 | } 25 | async with session.get(api, headers=headers, cookies=cookies) as resp: 26 | data = await resp.json() 27 | return data["code"] == 0, data["data"]["uname"] 28 | 29 | 30 | async def get_tv_qrcode_url_and_auth_code(): 31 | api = "https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code" 32 | data = { 33 | "local_id": "0", 34 | "ts": str(int(time.time())), 35 | } 36 | await signature(data) 37 | async with aiohttp.ClientSession() as session: 38 | async with session.post( 39 | api, 40 | data=await map_to_string(data), 41 | cookies={}, 42 | headers={ 43 | "Host": "passport.bilibili.com", 44 | "Content-Type": "application/x-www-form-urlencoded", 45 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69", 46 | }, 47 | ) as resp: 48 | if resp.status != 200: 49 | raise Exception("Failed to connect to server") 50 | resp_data = await resp.json() 51 | code = resp_data["code"] 52 | if code == 0: 53 | login_url = resp_data["data"]["url"] 54 | login_key = resp_data["data"]["auth_code"] 55 | return login_url, login_key 56 | raise Exception("get_tv_qrcode_url_and_auth_code error") 57 | 58 | 59 | async def verify_login(login_key: str, data_path: Path): 60 | api = "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll" 61 | data = { 62 | "auth_code": login_key, 63 | "local_id": "0", 64 | "ts": str(int(time.time())), 65 | } 66 | await signature(data) 67 | while True: 68 | async with aiohttp.ClientSession() as session: 69 | async with session.post( 70 | api, 71 | data=await map_to_string(data), 72 | cookies={}, 73 | headers={ 74 | "Host": "passport.bilibili.com", 75 | "Content-Type": "application/x-www-form-urlencoded", 76 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69", 77 | }, 78 | ) as resp: 79 | if resp.status != 200: 80 | raise Exception("Failed to connect to server") 81 | response_dict = await resp.json() 82 | code = response_dict["code"] 83 | try: 84 | access_key = response_dict["data"]["access_token"] 85 | except Exception: 86 | access_key = "" 87 | await asyncio.sleep(3) 88 | 89 | if code == 0: 90 | logger.success("登录成功") 91 | filename = "login_info.txt" 92 | data_path.mkdir(parents=True, exist_ok=True) 93 | with (data_path / filename).open(mode="w", encoding="utf-8") as f: 94 | f.write(access_key) 95 | if not Path(data_path / "users.yaml").is_file(): 96 | logger.info("初始化配置文件") 97 | shutil.copy2( 98 | Path().joinpath("data/bilifan/users.yaml"), 99 | data_path / "users.yaml", 100 | ) 101 | config = yaml.safe_load( 102 | await anyio.Path(data_path / "users.yaml").read_text("u8"), 103 | ) 104 | # with Path(data_path / "users.yaml").open( 105 | # "r", encoding="utf-8" 106 | # ) as f: 107 | # config = yaml.safe_load(f) 108 | 109 | config["USERS"][0]["access_key"] = access_key 110 | yaml_string = yaml.dump( 111 | config, 112 | allow_unicode=True, 113 | default_flow_style=False, 114 | ) 115 | await anyio.Path(data_path / "users.yaml").write_text(yaml_string, "u8") 116 | 117 | # with Path(data_path / "users.yaml").open( 118 | # "w", encoding="utf-8" 119 | # ) as f: # noqa: ASYNC101 120 | # yaml.dump(config, f, allow_unicode=True, default_flow_style=False) 121 | return "access_key已保存" 122 | await asyncio.sleep(3) 123 | 124 | 125 | appkey = "4409e2ce8ffd12b8" 126 | appsec = "59b43e04ad6965f34319062b478f83dd" 127 | 128 | 129 | async def signature(params: dict): # noqa: RUF029 130 | keys = list(params.keys()) 131 | params["appkey"] = appkey 132 | keys.append("appkey") 133 | keys.sort() 134 | query = "&".join([k + "=" + urlparse.quote(params[k]) for k in keys]) 135 | query += appsec 136 | hash_ = hashlib.md5(query.encode("utf-8")) 137 | params["sign"] = hash_.hexdigest() 138 | 139 | 140 | async def map_to_string(params: dict) -> str: # noqa: RUF029 141 | return "&".join([k + "=" + v for k, v in params.items()]) 142 | 143 | 144 | async def draw_QR(login_url: str): # noqa: N802, RUF029 145 | "绘制二维码" 146 | qr = qrcode.QRCode(version=1, box_size=10, border=4) # type: ignore 147 | qr.add_data(login_url) 148 | qr.make(fit=True) 149 | img = qr.make_image(fill_color="black", back_color="white") 150 | buffered = BytesIO() 151 | img.save(buffered, format="PNG") 152 | return buffered.getvalue() 153 | # img.save("qrcode.png") 154 | 155 | 156 | # async def loginBili(): 157 | 158 | 159 | # login_url, auth_code = await get_tv_qrcode_url_and_auth_code() 160 | # qrcode_terminal.draw(login_url) 161 | # print("或将此链接复制到手机B站打开:", login_url) 162 | # while True: 163 | # if await verify_login(auth_code): 164 | # print("登录成功!") 165 | # break 166 | # else: 167 | # time.sleep(3) 168 | # print("等待扫码登录中...") 169 | 170 | 171 | # async def main(): 172 | # loginBili() 173 | # input() 174 | 175 | # if __name__ == "__main__": 176 | # main() 177 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/main.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import itertools 3 | import json 4 | import os 5 | import sys 6 | import warnings 7 | from pathlib import Path 8 | 9 | from nonebot.log import logger 10 | 11 | from .src import BiliUser 12 | 13 | local_path = Path(__file__).parent 14 | 15 | 16 | log_file = os.path.join(os.path.dirname(__file__), "log/bilifan_{time:YYYY-MM-DD}.log") 17 | log_format = "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} - {message}" 18 | 19 | logger.remove() 20 | logger.add(sys.stdout, format=log_format, backtrace=True, diagnose=True, level="INFO") 21 | 22 | warnings.filterwarnings( 23 | "ignore", 24 | message="The localize method is no longer necessary, as this time zone supports the fold attribute", 25 | ) 26 | 27 | base_path = Path().joinpath("data/bilifan") 28 | base_path.mkdir(parents=True, exist_ok=True) 29 | logger.info(base_path) 30 | 31 | global users 32 | 33 | 34 | async def read_yaml(msg_path: Path): 35 | global config, users 36 | try: 37 | if os.environ.get("USERS"): 38 | users = json.loads(os.environ.get("USERS")) # type: ignore 39 | else: 40 | import anyio 41 | import yaml 42 | 43 | users = yaml.load( 44 | await anyio.Path(msg_path / "users.yaml").read_text("u8"), 45 | Loader=yaml.FullLoader, 46 | ) 47 | # with Path(msg_path / "users.yaml").open( 48 | # "r", encoding="utf-8", 49 | # ) as f: 50 | # users = yaml.load(f, Loader=yaml.FullLoader) 51 | if users.get("WRITE_LOG_FILE"): 52 | logger.add( 53 | log_file if users["WRITE_LOG_FILE"] is True else users["WRITE_LOG_FILE"], 54 | format=log_format, 55 | backtrace=True, 56 | diagnose=True, 57 | rotation="00:00", 58 | retention="30 days", 59 | level="DEBUG", 60 | ) 61 | assert users["ASYNC"] in [0, 1], "ASYNC参数错误" 62 | assert users["LIKE_CD"] >= 0, "LIKE_CD参数错误" 63 | # assert users['SHARE_CD'] >= 0, "SHARE_CD参数错误" 64 | assert users["DANMAKU_CD"] >= 0, "DANMAKU_CD参数错误" 65 | try: 66 | assert users["DANMAKU_NUM"] >= 0, "DANMAKU_NUM参数错误" 67 | except Exception: 68 | pass 69 | assert users["DANMAKU_CHECK_LIGHT"] in [0, 1], "DANMAKU_CHECK_LIGHT参数错误" 70 | assert users["DANMAKU_CHECK_LEVEL"] in [0, 1], "DANMAKU_CHECK_LEVEL参数错误" 71 | assert users["WATCHINGLIVE"] >= 0, "WATCHINGLIVE参数错误" 72 | assert users["WEARMEDAL"] in [0, 1], "WEARMEDAL参数错误" 73 | config = { 74 | "ASYNC": users["ASYNC"], 75 | "LIKE_CD": users["LIKE_CD"], 76 | # "SHARE_CD": users['SHARE_CD'], 77 | "DANMAKU_CD": users["DANMAKU_CD"], 78 | "DANMAKU_NUM": users["DANMAKU_NUM"], 79 | "DANMAKU_CHECK_LIGHT": users["DANMAKU_CHECK_LIGHT"], 80 | "DANMAKU_CHECK_LEVEL": users["DANMAKU_CHECK_LEVEL"], 81 | "WATCHINGLIVE": users["WATCHINGLIVE"], 82 | "WEARMEDAL": users["WEARMEDAL"], 83 | "SIGNINGROUP": users.get("SIGNINGROUP", 2), 84 | "LEVEN": users.get("LEVEN", 20), 85 | "WHACHASYNER": users.get("WHACHASYNER", 1), 86 | "STOPWATCHINGTIME": None, 87 | } 88 | stoptime = users.get("STOPWATCHINGTIME", None) 89 | if stoptime: 90 | import time 91 | 92 | now = int(time.time()) 93 | if isinstance(stoptime, int): 94 | delay = now + int(stoptime) 95 | else: 96 | delay = int( 97 | time.mktime( 98 | time.strptime( 99 | f'{time.strftime("%Y-%m-%d", time.localtime(now))} {stoptime}', 100 | "%Y-%m-%d %H:%M:%S", 101 | ) 102 | ) 103 | ) 104 | delay = delay if delay > now else delay + 86400 105 | config["STOPWATCHINGTIME"] = delay 106 | logger.info( 107 | f"本轮任务将在 {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(config['STOPWATCHINGTIME']))} 结束" 108 | ) 109 | except Exception as e: 110 | logger.error(f"读取配置文件失败,请检查配置文件格式是否正确: {e}") 111 | exit(1) 112 | return users 113 | 114 | 115 | @logger.catch 116 | async def mains(msg_path): 117 | await read_yaml(msg_path) 118 | init_tasks = [] 119 | start_tasks = [] 120 | catch_msg = [] 121 | 122 | for user in users["USERS"]: 123 | if user["access_key"]: 124 | bili_user = BiliUser( 125 | user["access_key"], 126 | user.get("white_uid", ""), 127 | user.get("banned_uid", ""), 128 | config, 129 | ) 130 | init_tasks.append(bili_user.init()) 131 | start_tasks.append(bili_user.start()) 132 | catch_msg.append(bili_user.sendmsg()) 133 | 134 | try: 135 | await asyncio.gather(*init_tasks) 136 | await asyncio.gather(*start_tasks) 137 | except Exception as e: 138 | logger.exception(e) 139 | message_list = [f"任务执行失败: {e}"] 140 | else: 141 | message_list = [] 142 | 143 | try: 144 | catch_msg_results = await asyncio.gather(*catch_msg) 145 | except Exception as e: 146 | logger.exception(e) 147 | message_list.append(f"发送消息失败: {e}") 148 | else: 149 | message_list += list(itertools.chain.from_iterable(catch_msg_results)) 150 | 151 | [logger.info(message) for message in message_list] 152 | return message_list 153 | 154 | 155 | def run(*args, **kwargs): # noqa: ARG001 156 | loop = asyncio.new_event_loop() 157 | asyncio.set_event_loop(loop) 158 | loop.run_until_complete(mains(Path().joinpath("data/bilifan"))) 159 | logger.info("任务结束,等待下一次执行。") 160 | 161 | 162 | # if __name__ == '__main__': 163 | # cron = users.get('CRON', None) 164 | # cron = users.get('CRON', None) 165 | 166 | # if cron: 167 | # from apscheduler.schedulers.blocking import BlockingScheduler 168 | # from apscheduler.triggers.cron import CronTrigger 169 | # if cron: 170 | # from apscheduler.schedulers.blocking import BlockingScheduler 171 | # from apscheduler.triggers.cron import CronTrigger 172 | 173 | # logger.info(f'使用内置定时器 {cron},开启定时任务,等待时间到达后执行。') 174 | # schedulers = BlockingScheduler() 175 | # schedulers.add_job(run, CronTrigger.from_crontab(cron), misfire_grace_time=3600) 176 | # schedulers.start() 177 | # elif "--auto" in sys.argv: 178 | # from apscheduler.schedulers.blocking import BlockingScheduler 179 | # from apscheduler.triggers.interval import IntervalTrigger 180 | # import datetime 181 | # logger.info(f'使用内置定时器 {cron},开启定时任务,等待时间到达后执行。') 182 | # schedulers = BlockingScheduler() 183 | # schedulers.add_job(run, CronTrigger.from_crontab(cron), misfire_grace_time=3600) 184 | # schedulers.start() 185 | # elif "--auto" in sys.argv: 186 | # from apscheduler.schedulers.blocking import BlockingScheduler 187 | # from apscheduler.triggers.interval import IntervalTrigger 188 | # import datetime 189 | 190 | # logger.info('使用自动守护模式,每隔 24 小时运行一次。') 191 | # scheduler = BlockingScheduler(timezone='Asia/Shanghai') 192 | # scheduler.add_job( 193 | # run, 194 | # IntervalTrigger(hours=24), 195 | # next_run_time=datetime.datetime.now(), 196 | # misfire_grace_time=3600, 197 | # ) 198 | # scheduler.start() 199 | # else: 200 | # logger.info('未配置定时器,开启单次任务。') 201 | # loop = asyncio.new_event_loop() 202 | # asyncio.set_event_loop(loop) 203 | # loop.run_until_complete(main()) 204 | # logger.info("任务结束") 205 | 206 | # logger.info('使用自动守护模式,每隔 24 小时运行一次。') 207 | # scheduler = BlockingScheduler(timezone='Asia/Shanghai') 208 | # scheduler.add_job( 209 | # run, 210 | # IntervalTrigger(hours=24), 211 | # next_run_time=datetime.datetime.now(), 212 | # misfire_grace_time=3600, 213 | # ) 214 | # scheduler.start() 215 | # else: 216 | # logger.info('未配置定时器,开启单次任务。') 217 | # loop = asyncio.new_event_loop() 218 | # asyncio.set_event_loop(loop) 219 | # loop.run_until_complete(main()) 220 | # logger.info("任务结束") 221 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/src/__init__.py: -------------------------------------------------------------------------------- 1 | from .api import BiliApi # noqa: F401 2 | from .user import BiliUser # noqa: F401 3 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/src/api.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import hashlib 3 | import json 4 | import random 5 | import time 6 | from hashlib import md5 7 | from typing import Union 8 | from urllib.parse import urlencode, urlparse 9 | 10 | from aiohttp import ClientSession 11 | from nonebot.log import logger 12 | 13 | # sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 14 | 15 | 16 | class Crypto: 17 | APPKEY = "4409e2ce8ffd12b8" 18 | APPSECRET = "59b43e04ad6965f34319062b478f83dd" 19 | 20 | @staticmethod 21 | def md5(data: Union[str, bytes]) -> str: 22 | """generates md5 hex dump of `str` or `bytes`""" 23 | if isinstance(data, str): 24 | return md5(data.encode()).hexdigest() 25 | return md5(data).hexdigest() 26 | 27 | @staticmethod 28 | def sign(data: Union[str, dict]) -> str: 29 | """salted sign funtion for `dict`(converts to qs then parse) & `str`""" 30 | if isinstance(data, dict): 31 | _str = urlencode(data) 32 | elif not isinstance(data, str): 33 | raise TypeError 34 | return Crypto.md5(_str + Crypto.APPSECRET) # type: ignore 35 | 36 | 37 | class SingableDict(dict): 38 | @property 39 | def sorted(self): 40 | """returns a alphabetically sorted version of `self`""" 41 | return dict(sorted(self.items())) 42 | 43 | @property 44 | def signed(self): 45 | """returns our sorted self with calculated `sign` as a new key-value pair at the end""" 46 | _sorted = self.sorted 47 | return {**_sorted, "sign": Crypto.sign(_sorted)} 48 | 49 | 50 | def retry(tries=3, interval=1): 51 | def decorate(func): 52 | async def wrapper(*args, **kwargs): 53 | count = 0 54 | func.isRetryable = False 55 | log = logger.bind(user=f"{args[0].u.name}") 56 | while True: 57 | try: 58 | result = await func(*args, **kwargs) 59 | except Exception as e: 60 | count += 1 61 | if isinstance(e, BiliApiError): 62 | if e.code == 1011040: 63 | raise e 64 | elif e.code == 10030: 65 | await asyncio.sleep(10) 66 | elif e.code == -504: 67 | pass 68 | else: 69 | raise e 70 | if count > tries: 71 | log.error(f"API {urlparse(args[1]).path} 调用出现异常: {str(e)}") 72 | raise e 73 | else: 74 | # log.error(f"API {urlparse(args[1]).path} 调用出现异常: {str(e)},重试中,第{count}次重试") 75 | await asyncio.sleep(interval) 76 | func.isRetryable = True 77 | else: 78 | if func.isRetryable: 79 | pass 80 | # log.success(f"重试成功") 81 | return result 82 | 83 | return wrapper 84 | 85 | return decorate 86 | 87 | 88 | def client_sign(data: dict): 89 | _str = json.dumps(data, separators=(",", ":")) 90 | for n in ["sha512", "sha3_512", "sha384", "sha3_384", "blake2b"]: 91 | _str = hashlib.new(n, _str.encode("utf-8")).hexdigest() 92 | return _str 93 | 94 | 95 | def randomString(length: int = 16) -> str: 96 | return "".join( 97 | random.sample( 98 | "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 99 | length, 100 | ), 101 | ) 102 | 103 | 104 | class BiliApiError(Exception): 105 | def __init__(self, code: int, msg: str): 106 | self.code = code 107 | self.msg = msg 108 | 109 | def __str__(self): 110 | return self.msg 111 | 112 | 113 | class BiliApi: 114 | headers = { 115 | "User-Agent": "Mozilla/5.0 BiliDroid/6.73.1 (bbcallen@gmail.com) os/android model/Mi 10 Pro mobi_app/android build/6731100 channel/xiaomi innerVer/6731110 osVer/12 network/2", 116 | } 117 | from .user import BiliUser 118 | 119 | def __init__(self, u: BiliUser, s: ClientSession): 120 | self.u = u 121 | self.session = s 122 | 123 | def __check_response(self, resp: dict) -> dict: 124 | logger.trace(resp) 125 | if resp["code"] != 0 or ("mode_info" in resp["data"] and resp["message"] != ""): 126 | logger.warning(BiliApiError(resp["code"], resp["message"])) 127 | return resp["data"] 128 | 129 | @retry() 130 | async def __get(self, *args, **kwargs): 131 | async with self.session.get(*args, **kwargs) as resp: 132 | return self.__check_response(await resp.json()) 133 | 134 | @retry() 135 | async def __post(self, *args, **kwargs): 136 | async with self.session.post(*args, **kwargs) as resp: 137 | return self.__check_response(await resp.json()) 138 | 139 | async def getFansMedalandRoomID(self) -> dict: # type: ignore 140 | """ 141 | 获取用户粉丝勋章和直播间ID 142 | """ 143 | url = "https://api.live.bilibili.com/xlive/app-ucenter/v1/fansMedal/panel" 144 | params = { 145 | "access_key": self.u.access_key, 146 | "actionKey": "appkey", 147 | "appkey": Crypto.APPKEY, 148 | "ts": int(time.time()), 149 | "page": 1, 150 | "page_size": 50, 151 | } 152 | first_flag = True 153 | while True: 154 | data = await self.__get( 155 | url, 156 | params=SingableDict(params).signed, 157 | headers=self.headers, 158 | ) 159 | if first_flag and data["special_list"]: 160 | for item in data["special_list"]: 161 | # 强制把正在佩戴的牌子加入任务列表 162 | # 8月15日删除 163 | # item["medal"]["today_feed"] = 0 164 | yield item # type: ignore 165 | self.u.wearedMedal = data["special_list"][0] # type: ignore 166 | first_flag = False 167 | for item in data["list"]: 168 | yield item # type: ignore 169 | if not data["list"]: 170 | break 171 | params["page"] += 1 172 | 173 | async def likeInteract(self, room_id: int): 174 | """ 175 | 点赞直播间 176 | """ 177 | url = "https://api.live.bilibili.com/xlive/web-ucenter/v1/interact/likeInteract" 178 | data = { 179 | "access_key": self.u.access_key, 180 | "actionKey": "appkey", 181 | "appkey": Crypto.APPKEY, 182 | "click_time": 1, 183 | "roomid": room_id, 184 | } 185 | self.headers.update( 186 | { 187 | "Content-Type": "application/x-www-form-urlencoded", 188 | }, 189 | ) 190 | # for _ in range(3): 191 | await self.__post( 192 | url, 193 | data=SingableDict(data).signed, 194 | headers=self.headers, 195 | ) 196 | # await asyncio.sleep(self.u.config['LIKE_CD'] if not self.u.config['ASYNC'] else 2) 197 | 198 | async def likeInteractV3(self, room_id: int, up_id: int, self_uid: int): 199 | """ 200 | 点赞直播间V3 201 | """ 202 | url = "https://api.live.bilibili.com/xlive/app-ucenter/v1/like_info_v3/like/likeReportV3" 203 | data = { 204 | "access_key": self.u.access_key, 205 | "actionKey": "appkey", 206 | "appkey": Crypto.APPKEY, 207 | "click_time": 1, 208 | "room_id": room_id, 209 | "anchor_id": up_id, 210 | "uid": self_uid, 211 | } 212 | self.headers.update( 213 | { 214 | "Content-Type": "application/x-www-form-urlencoded", 215 | }, 216 | ) 217 | # for _ in range(3): 218 | await self.__post( 219 | url, 220 | data=SingableDict(data).signed, 221 | headers=self.headers, 222 | ) 223 | 224 | async def shareRoom(self, room_id: int): 225 | """ 226 | 分享直播间 227 | """ 228 | url = "https://api.live.bilibili.com/xlive/app-room/v1/index/TrigerInteract" 229 | data = { 230 | "access_key": self.u.access_key, 231 | "actionKey": "appkey", 232 | "appkey": Crypto.APPKEY, 233 | "ts": int(time.time()), 234 | "interact_type": 3, 235 | "roomid": room_id, 236 | } 237 | self.headers.update( 238 | { 239 | "Content-Type": "application/x-www-form-urlencoded", 240 | }, 241 | ) 242 | # for _ in range(5): 243 | await self.__post( 244 | url, 245 | data=SingableDict(data).signed, 246 | headers=self.headers, 247 | ) 248 | # await asyncio.sleep(self.u.config['SHARE_CD'] if not self.u.config['ASYNC'] else 5) 249 | 250 | async def sendDanmaku(self, room_id: int) -> str: 251 | """ 252 | 发送弹幕 253 | """ 254 | url = "https://api.live.bilibili.com/xlive/app-room/v1/dM/sendmsg" 255 | danmakus = [ 256 | "(⌒▽⌒).", 257 | "( ̄▽ ̄).", 258 | "(=・ω・=).", 259 | "(`・ω・´).", 260 | "(〜 ̄△ ̄)〜.", 261 | "(・∀・).", 262 | "(°∀°)ノ.", 263 | "( ̄3 ̄).", 264 | "╮( ̄▽ ̄)╭.", 265 | "_(:3」∠)_.", 266 | "(^・ω・^ ).", 267 | "(● ̄(エ) ̄●).", 268 | "ε=ε=(ノ≧∇≦)ノ.", 269 | "⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄.", 270 | "←◡←.", 271 | ] 272 | params = { 273 | "access_key": self.u.access_key, 274 | "actionKey": "appkey", 275 | "appkey": Crypto.APPKEY, 276 | "ts": int(time.time()), 277 | } 278 | data = { 279 | "cid": room_id, 280 | "msg": random.choice(danmakus), 281 | "rnd": int(time.time()), 282 | "color": "16777215", 283 | "fontsize": "25", 284 | } 285 | self.headers.update( 286 | { 287 | "Content-Type": "application/x-www-form-urlencoded", 288 | }, 289 | ) 290 | try: 291 | resp = await self.__post( 292 | url, 293 | params=SingableDict(params).signed, 294 | data=data, 295 | headers=self.headers, 296 | ) 297 | except BiliApiError as e: 298 | if e.code == 0: 299 | await asyncio.sleep(self.u.config["DANMAKU_CD"]) 300 | params.update( 301 | { 302 | "ts": int(time.time()), 303 | }, 304 | ) 305 | data.update( 306 | { 307 | "msg": "111", 308 | }, 309 | ) 310 | resp = await self.__post( 311 | url, 312 | params=SingableDict(params).signed, 313 | data=data, 314 | headers=self.headers.update( 315 | { 316 | "Content-Type": "application/x-www-form-urlencoded", 317 | }, 318 | ), 319 | ) 320 | return json.loads(resp["mode_info"]["extra"])["content"] 321 | raise e 322 | return json.loads(resp["mode_info"]["extra"])["content"] 323 | 324 | async def loginVerift(self): 325 | """ 326 | 登录验证 327 | """ 328 | url = "https://app.bilibili.com/x/v2/account/mine" 329 | params = { 330 | "access_key": self.u.access_key, 331 | "actionKey": "appkey", 332 | "appkey": Crypto.APPKEY, 333 | "ts": int(time.time()), 334 | } 335 | return await self.__get( 336 | url, 337 | params=SingableDict(params).signed, 338 | headers=self.headers, 339 | ) 340 | 341 | async def doSign(self): 342 | """ 343 | 直播区签到 344 | """ 345 | url = "https://api.live.bilibili.com/rc/v1/Sign/doSign" 346 | params = { 347 | "access_key": self.u.access_key, 348 | "actionKey": "appkey", 349 | "appkey": Crypto.APPKEY, 350 | "ts": int(time.time()), 351 | } 352 | return await self.__get( 353 | url, 354 | params=SingableDict(params).signed, 355 | headers=self.headers, 356 | ) 357 | 358 | async def getUserInfo(self): 359 | """ 360 | 用户直播等级 361 | """ 362 | url = "https://api.live.bilibili.com/xlive/app-ucenter/v1/user/get_user_info" 363 | params = { 364 | "access_key": self.u.access_key, 365 | "actionKey": "appkey", 366 | "appkey": Crypto.APPKEY, 367 | "ts": int(time.time()), 368 | } 369 | return await self.__get( 370 | url, 371 | params=SingableDict(params).signed, 372 | headers=self.headers, 373 | ) 374 | 375 | async def getMedalsInfoByUid(self, uid: int): 376 | """ 377 | 用户勋章信息 378 | """ 379 | url = "https://api.live.bilibili.com/xlive/app-ucenter/v1/fansMedal/fans_medal_info" 380 | params = { 381 | "access_key": self.u.access_key, 382 | "actionKey": "appkey", 383 | "appkey": Crypto.APPKEY, 384 | "ts": int(time.time()), 385 | "target_id": uid, 386 | } 387 | return await self.__get( 388 | url, 389 | params=SingableDict(params).signed, 390 | headers=self.headers, 391 | ) 392 | 393 | # async def entryRoom(self, room_id: int, up_id: int): 394 | # data = { 395 | # "access_key": self.u.access_key, 396 | # "actionKey": "appkey", 397 | # "appkey": Crypto.APPKEY, 398 | # "ts": int(time.time()), 399 | # 'platform': 'android', 400 | # 'uuid': self.u.uuids[0], 401 | # 'buvid': randomString(37).upper(), 402 | # 'seq_id': '1', 403 | # 'room_id': f'{room_id}', 404 | # 'parent_id': '6', 405 | # 'area_id': '283', 406 | # 'timestamp': f'{int(time.time())-60}', 407 | # 'secret_key': 'axoaadsffcazxksectbbb', 408 | # 'watch_time': '60', 409 | # 'up_id': f'{up_id}', 410 | # 'up_level': '40', 411 | # 'jump_from': '30000', 412 | # 'gu_id': randomString(43).lower(), 413 | # 'visit_id': randomString(32).lower(), 414 | # 'click_id': self.u.uuids[1], 415 | # 'heart_beat': '[]', 416 | # 'client_ts': f'{int(time.time())}' 417 | # } 418 | # url = "http://live-trace.bilibili.com/xlive/data-interface/v1/heartbeat/mobileEntry" 419 | # return await self.__post(url, data=SingableDict(data).signed, headers=self.headers.update({ 420 | # "Content-Type": "application/x-www-form-urlencoded", 421 | # })) 422 | 423 | async def heartbeat(self, room_id: int, up_id: int): 424 | url = "https://live-trace.bilibili.com/xlive/data-interface/v1/heartbeat/mobileHeartBeat" 425 | today_timestamp = int( 426 | time.mktime( 427 | time.strptime( 428 | f"{time.strftime('%Y-%m-%d', time.localtime(time.time()))} 00:00:00", 429 | "%Y-%m-%d %H:%M:%S", 430 | ) 431 | ) 432 | ) 433 | now_timestamp = int(time.time()) 434 | timestamp = ( 435 | now_timestamp - 60 436 | if now_timestamp - 60 > today_timestamp 437 | else today_timestamp 438 | ) 439 | data = { 440 | "platform": "android", 441 | "uuid": self.u.uuids[0], 442 | "buvid": randomString(37).upper(), 443 | "seq_id": "1", 444 | "room_id": f"{room_id}", 445 | "parent_id": "6", 446 | "area_id": "283", 447 | "timestamp": f"{timestamp}", 448 | "secret_key": "axoaadsffcazxksectbbb", 449 | "watch_time": f"{now_timestamp - timestamp}", 450 | "up_id": f"{up_id}", 451 | "up_level": "40", 452 | "jump_from": "30000", 453 | "gu_id": randomString(43).lower(), 454 | "play_type": "0", 455 | "play_url": "", 456 | "s_time": "0", 457 | "data_behavior_id": "", 458 | "data_source_id": "", 459 | "up_session": f"l:one:live:record:{room_id}:{int(time.time()) - 88888}", 460 | "visit_id": randomString(32).lower(), 461 | "watch_status": "%7B%22pk_id%22%3A0%2C%22screen_status%22%3A1%7D", 462 | "click_id": self.u.uuids[1], 463 | "session_id": "", 464 | "player_type": "0", 465 | "client_ts": f"{now_timestamp}", 466 | } 467 | data.update( 468 | { 469 | "client_sign": client_sign(data), 470 | "access_key": self.u.access_key, 471 | "actionKey": "appkey", 472 | "appkey": Crypto.APPKEY, 473 | "ts": int(time.time()), 474 | }, # type: ignore 475 | ) # type: ignore 476 | self.headers.update( 477 | { 478 | "Content-Type": "application/x-www-form-urlencoded", 479 | }, 480 | ) 481 | return await self.__post( 482 | url, 483 | data=SingableDict(data).signed, 484 | headers=self.headers, 485 | ) 486 | 487 | async def wearMedal(self, medal_id: int): 488 | """ 489 | 佩戴粉丝牌 490 | """ 491 | url = "https://api.live.bilibili.com/xlive/app-ucenter/v1/fansMedal/wear" 492 | data = { 493 | "access_key": self.u.access_key, 494 | "actionKey": "appkey", 495 | "appkey": Crypto.APPKEY, 496 | "ts": int(time.time()), 497 | "medal_id": medal_id, 498 | "platform": "android", 499 | "type": "1", 500 | "version": "0", 501 | } 502 | self.headers.update( 503 | { 504 | "Content-Type": "application/x-www-form-urlencoded", 505 | } 506 | ) 507 | return await self.__post( 508 | url, data=SingableDict(data).signed, headers=self.headers 509 | ) 510 | 511 | async def getGroups(self): 512 | url = "https://api.vc.bilibili.com/link_group/v1/member/my_groups?build=0&mobi_app=web" 513 | params = { 514 | "access_key": self.u.access_key, 515 | "actionKey": "appkey", 516 | "appkey": Crypto.APPKEY, 517 | "ts": int(time.time()), 518 | } 519 | list_msg = await self.__get( 520 | url, 521 | params=SingableDict(params).signed, 522 | headers=self.headers, 523 | ) 524 | if list_msg: 525 | list_m = list_msg["list"] 526 | for group in list_m: 527 | yield group 528 | 529 | async def signInGroups(self, group_id: int, owner_id: int): 530 | url = "https://api.vc.bilibili.com/link_setting/v1/link_setting/sign_in" 531 | params = { 532 | "access_key": self.u.access_key, 533 | "actionKey": "appkey", 534 | "appkey": Crypto.APPKEY, 535 | "ts": int(time.time()), 536 | "group_id": group_id, 537 | "owner_id": owner_id, 538 | } 539 | return await self.__get( 540 | url, 541 | params=SingableDict(params).signed, 542 | headers=self.headers, 543 | ) 544 | 545 | async def getOneBattery(self): 546 | url = "https://api.live.bilibili.com/xlive/app-ucenter/v1/userTask/UserTaskReceiveRewards" 547 | data = { 548 | "access_key": self.u.access_key, 549 | "actionKey": "appkey", 550 | "appkey": Crypto.APPKEY, 551 | "ts": int(time.time()), 552 | } 553 | return await self.__post( 554 | url, 555 | data=SingableDict(data).signed, 556 | headers=self.headers, 557 | ) 558 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/src/user.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import time 3 | import uuid 4 | from datetime import datetime, timedelta 5 | 6 | from aiohttp import ClientSession, ClientTimeout 7 | from loguru import logger 8 | from nonebot.log import logger as log 9 | 10 | global user 11 | 12 | 13 | class BiliUser: 14 | def __init__( 15 | self, 16 | access_token: str, 17 | whiteUIDs: str = "", 18 | bannedUIDs: str = "", 19 | config: dict = {}, # noqa: B006 20 | ): 21 | from .api import BiliApi 22 | 23 | self.mid, self.name = 0, "" 24 | self.access_key = access_token # 登录凭证 25 | try: 26 | self.whiteList = [ 27 | int(x if x else 0) for x in str(whiteUIDs).split(",") 28 | ] # 白名单UID 29 | self.bannedList = [ 30 | int(x if x else 0) for x in str(bannedUIDs).split(",") 31 | ] # 黑名单 32 | except ValueError: 33 | raise ValueError("白名单或黑名单格式错误") # noqa: B904 34 | 35 | self.config = config 36 | self.medals = [] # 用户所有勋章 37 | self.medalsNeedDo = [] # 用户所有勋章,等级小于20的 未满1500的 38 | 39 | self.session = ClientSession(timeout=ClientTimeout(total=3)) 40 | self.api = BiliApi(self, self.session) 41 | 42 | self.retryTimes = 0 # 任务重试次数 43 | self.maxRetryTimes = 10 # 最大重试次数 44 | self.message = [] 45 | self.errmsg = ["错误日志:"] 46 | self.uuids = [str(uuid.uuid4()) for _ in range(2)] 47 | 48 | async def loginVerify(self) -> bool: 49 | """ 50 | 登录验证 51 | """ 52 | loginInfo = await self.api.loginVerift() 53 | self.mid, self.name = loginInfo["mid"], loginInfo["name"] 54 | self.log = logger.info(f"b站名称:{self.name}") 55 | if loginInfo["mid"] == 0: 56 | self.isLogin = False 57 | return False 58 | userInfo = await self.api.getUserInfo() 59 | if userInfo["medal"]: 60 | medalInfo = await self.api.getMedalsInfoByUid(userInfo["medal"]["target_id"]) 61 | if medalInfo["has_fans_medal"]: 62 | self.initialMedal = medalInfo["my_fans_medal"] 63 | self.log = logger.success(str(loginInfo["mid"]) + " 登录成功") 64 | self.isLogin = True 65 | return True 66 | 67 | async def doSign(self): 68 | try: 69 | signInfo = await self.api.doSign() 70 | log.success( 71 | "签到成功,本月签到次数: {}/{}".format( 72 | signInfo["hadSignDays"], 73 | signInfo["allDays"], 74 | ), 75 | ) 76 | self.message.append( 77 | f"【{self.name}】 签到成功,本月签到次数: {signInfo['hadSignDays']}/{signInfo['allDays']}", 78 | ) 79 | except Exception as e: 80 | log.error(e) 81 | self.errmsg.append(f"【{self.name}】" + str(e)) 82 | userInfo = await self.api.getUserInfo() 83 | log.info( 84 | "当前用户UL等级: {} ,还差 {} 经验升级".format( 85 | userInfo["exp"]["user_level"], 86 | userInfo["exp"]["unext"], 87 | ), 88 | ) 89 | self.message.append( 90 | f"【{self.name}】 UL等级: {userInfo['exp']['user_level']} ,还差 {userInfo['exp']['unext']} 经验升级", 91 | ) 92 | 93 | async def getMedals(self): 94 | """ 95 | 获取用户勋章 96 | """ 97 | self.medals.clear() 98 | self.medalsNeedDo.clear() 99 | async for medal in self.api.getFansMedalandRoomID(): # type: ignore 100 | if self.whiteList == [0]: 101 | if medal["medal"]["target_id"] in self.bannedList: 102 | log.warning( 103 | f"{medal['anchor_info']['nick_name']} 在黑名单中,已过滤", 104 | ) 105 | continue 106 | self.medals.append(medal) if medal["room_info"]["room_id"] != 0 else ... 107 | else: 108 | if medal["medal"]["target_id"] in self.whiteList: 109 | ( 110 | self.medals.append(medal) 111 | if medal["room_info"]["room_id"] != 0 112 | else ... 113 | ) 114 | log.success( 115 | f"{medal['anchor_info']['nick_name']} 在白名单中,加入任务", 116 | ) 117 | [ 118 | self.medalsNeedDo.append(medal) 119 | for medal in self.medals 120 | if medal["medal"]["level"] < self.config["LEVEN"] 121 | and medal["medal"]["today_feed"] < 200 122 | ] 123 | 124 | async def like_v3(self, failedMedals: list = []): # noqa: B006 125 | if self.config["LIKE_CD"] == 0: 126 | log.info("点赞任务已关闭") 127 | return 128 | try: 129 | if not failedMedals: 130 | failedMedals = self.medals 131 | if not self.config["ASYNC"]: 132 | log.info("同步点赞任务开始....") 133 | for index, medal in enumerate(failedMedals): 134 | i = 0 135 | for i in range(30): 136 | tasks = [] 137 | ( 138 | tasks.append( 139 | self.api.likeInteractV3( 140 | medal["room_info"]["room_id"], 141 | medal["medal"]["target_id"], 142 | self.mid, 143 | ) 144 | ) 145 | if self.config["LIKE_CD"] 146 | else ... 147 | ) 148 | await asyncio.gather(*tasks) 149 | await asyncio.sleep(self.config["LIKE_CD"]) 150 | log.success( 151 | f"{medal['anchor_info']['nick_name']} 点赞{i+1}次成功 {index+1}/{len(self.medals)}", 152 | ) 153 | else: 154 | log.info("异步点赞任务开始....") 155 | for i in range(35): 156 | allTasks = [] 157 | medal = {} 158 | for medal in failedMedals: 159 | ( 160 | allTasks.append( 161 | self.api.likeInteractV3( 162 | medal["room_info"]["room_id"], 163 | medal["medal"]["target_id"], 164 | self.mid, 165 | ) 166 | ) 167 | if self.config["LIKE_CD"] 168 | else ... 169 | ) 170 | await asyncio.gather(*allTasks) 171 | log.success( 172 | f"{medal['anchor_info']['nick_name']} 异步点赞{i+1}次成功", 173 | ) 174 | await asyncio.sleep(self.config["LIKE_CD"]) 175 | 176 | await asyncio.sleep(10) 177 | log.success("点赞任务完成") 178 | # finallyMedals = [ 179 | # medal 180 | # for medal in self.medals 181 | # if medal["medal"]["today_feed"] >= 100 182 | # ] 183 | # msg = "20级以下牌子共 {} 个,完成点赞任务 {} 个".format( 184 | # len(self.medals), 185 | # len(finallyMedals), 186 | # ) 187 | # log.info(msg) 188 | except Exception: 189 | log.exception("点赞任务异常") 190 | self.errmsg.append(f"【{self.name}】 点赞任务异常,请检查日志") 191 | 192 | async def sendDanmaku(self): 193 | """ 194 | 每日弹幕打卡 195 | """ 196 | if not self.config["DANMAKU_CD"]: 197 | log.info("弹幕任务关闭") 198 | return 199 | # 计算实际执行的长度 200 | filtered_medals = [ 201 | medal 202 | for medal in self.medals 203 | if not ( 204 | self.config["DANMAKU_CHECK_LIGHT"] and medal["medal"]["is_lighted"] == 1 205 | ) 206 | and not ( 207 | not self.config["DANMAKU_CHECK_LEVEL"] 208 | and medal["medal"]["level"] > self.config["LEVEN"] 209 | ) 210 | ] 211 | filtered_medals_length = len(filtered_medals) 212 | log.info( 213 | "弹幕打卡任务开始....(预计 {} 秒完成)".format( 214 | filtered_medals_length 215 | * self.config["DANMAKU_CD"] 216 | * self.config["DANMAKU_NUM"] 217 | ), 218 | ) 219 | n = 0 220 | successnum = 0 221 | for medal in self.medals: 222 | n += 1 223 | if self.config["DANMAKU_CHECK_LIGHT"] and medal["medal"]["is_lighted"] == 1: 224 | log.info( 225 | "{} 房间已点亮,跳过".format(medal["anchor_info"]["nick_name"]), 226 | ) 227 | continue 228 | if ( 229 | not self.config["DANMAKU_CHECK_LEVEL"] 230 | and medal["medal"]["level"] > self.config["LEVEN"] 231 | ): 232 | log.info( 233 | "{} 房间已满级,跳过".format(medal["anchor_info"]["nick_name"]), 234 | ) 235 | continue 236 | ( 237 | (await self.api.wearMedal(medal["medal"]["medal_id"])) 238 | if self.config["WEARMEDAL"] 239 | else ... 240 | ) 241 | for i in range(self.config["DANMAKU_NUM"]): 242 | try: 243 | danmaku = await self.api.sendDanmaku(medal["room_info"]["room_id"]) 244 | log.info( 245 | "{} 房间弹幕打卡({}/{})成功: {} ({}/{})".format( 246 | medal["anchor_info"]["nick_name"], 247 | i + 1, 248 | self.config["DANMAKU_NUM"], 249 | danmaku, 250 | n, 251 | len(self.medals), 252 | ), 253 | ) 254 | except Exception as e: 255 | log.error( 256 | "{} 房间弹幕打卡({}/{})失败: {}".format( 257 | medal["anchor_info"]["nick_name"], 258 | i, 259 | self.config["DANMAKU_NUM"], 260 | e, 261 | ), 262 | ) 263 | self.errmsg.append( 264 | f"【{self.name}】 {medal['anchor_info']['nick_name']} 房间弹幕打卡失败: {str(e)}" 265 | ) 266 | finally: 267 | await asyncio.sleep(self.config["DANMAKU_CD"]) 268 | successnum += 1 269 | 270 | if hasattr(self, "initialMedal"): 271 | ( 272 | (await self.api.wearMedal(self.initialMedal["medal_id"])) 273 | if self.config["WEARMEDAL"] 274 | else ... 275 | ) 276 | log.success("弹幕打卡任务完成") 277 | self.message.append( 278 | f"【{self.name}】 弹幕打卡任务完成 {successnum}/{filtered_medals_length}/{len(self.medals)}" 279 | ) 280 | 281 | async def init(self): 282 | if not await self.loginVerify(): 283 | log.error(f"登录失败 可能是 access_key:{self.access_key} 过期 , 请重新获取") 284 | self.errmsg.append("登录失败 可能是登录已过期 , 请发送【b站登录】重新登录") 285 | await self.session.close() 286 | else: 287 | # await self.doSign() 288 | await self.getMedals() 289 | 290 | async def start(self): 291 | if self.isLogin: 292 | tasks = [] 293 | if self.medalsNeedDo: 294 | log.info(f"共有 {len(self.medalsNeedDo)} 个牌子未满 1500 亲密度") 295 | tasks.append(self.like_v3()) 296 | tasks.append(self.watchinglive()) 297 | else: 298 | log.info("所有牌子已满 1500 亲密度") 299 | tasks.append(self.sendDanmaku()) 300 | tasks.append(self.signInGroups()) 301 | await asyncio.gather(*tasks) 302 | 303 | async def sendmsg(self): 304 | if not self.isLogin: 305 | await self.session.close() 306 | return self.message + self.errmsg 307 | await self.getMedals() 308 | nameList1, nameList2, nameList3, nameList4 = [], [], [], [] 309 | for medal in self.medals: 310 | if medal["medal"]["level"] >= self.config["LEVEN"]: 311 | continue 312 | today_feed = medal["medal"]["today_feed"] 313 | nick_name = medal["anchor_info"]["nick_name"] 314 | if today_feed >= 1500: 315 | nameList1.append(nick_name) 316 | elif 1200 < today_feed <= 1500: 317 | nameList2.append(nick_name) 318 | elif 300 < today_feed <= 1200: 319 | nameList3.append(nick_name) 320 | elif today_feed <= 300: 321 | nameList4.append(nick_name) 322 | self.message.append(f"【{self.name}】 今日亲密度获取情况如下(20级以下):") 323 | 324 | for l, n in zip( # noqa: E741 325 | [nameList1, nameList2, nameList3, nameList4], 326 | ["【1500】", "【1200至1500】", "【300至1200】", "【300以下】"], 327 | ): 328 | if len(l) > 0: 329 | self.message.append( 330 | f"{n}{' '.join(l[:5])}{'等' if len(l) > 5 else ''} {len(l)}个" 331 | ) 332 | 333 | if hasattr(self, "initialMedal"): 334 | initialMedalInfo = await self.api.getMedalsInfoByUid( 335 | self.initialMedal["target_id"] 336 | ) 337 | if initialMedalInfo["has_fans_medal"]: 338 | initialMedal = initialMedalInfo["my_fans_medal"] 339 | self.message.append( 340 | f"【当前佩戴】「{initialMedal['medal_name']}」({initialMedal['target_name']}) {initialMedal['level']} 级 " 341 | ) 342 | if ( 343 | initialMedal["level"] < self.config["LEVEN"] 344 | and initialMedal["today_feed"] != 0 345 | ): 346 | need = initialMedal["next_intimacy"] - initialMedal["intimacy"] 347 | need_days = need // 1500 + 1 348 | end_date = datetime.now() + timedelta(days=need_days) 349 | self.message.append( 350 | f"今日已获取亲密度 {initialMedal['today_feed']} (B站结算有延迟,请耐心等待)" 351 | ) 352 | self.message.append( 353 | f"距离下一级还需 {need} 亲密度 预计需要 {need_days} 天 ({end_date.strftime('%Y-%m-%d')},以每日 1500 亲密度计算)" 354 | ) 355 | await self.session.close() 356 | return self.message + self.errmsg + ["---"] 357 | 358 | async def watchinglive(self): 359 | if not self.config["WATCHINGLIVE"]: 360 | log.info("每日观看直播任务关闭") 361 | return 362 | HEART_MAX = self.config["WATCHINGLIVE"] 363 | log.info(f"每日{HEART_MAX}分钟任务开始") 364 | n = 0 365 | for medal in self.medalsNeedDo: 366 | n += 1 367 | for heartNum in range(1, HEART_MAX + 1): 368 | if self.config["STOPWATCHINGTIME"]: 369 | if int(time.time()) >= self.config["STOPWATCHINGTIME"]: 370 | self.log.log("INFO", "已到设置的时间,自动停止直播任务") 371 | return 372 | tasks = [] 373 | tasks.append( 374 | self.api.heartbeat( 375 | medal["room_info"]["room_id"], medal["medal"]["target_id"] 376 | ) 377 | ) 378 | await asyncio.gather(*tasks) 379 | if heartNum % 5 == 0: 380 | log.info( 381 | f"{medal['anchor_info']['nick_name']} 第{heartNum}次心跳包已发送({n}/{len(self.medalsNeedDo)})", 382 | ) 383 | await asyncio.sleep(60) 384 | log.success(f"每日{HEART_MAX}分钟任务完成") 385 | 386 | async def signInGroups(self): 387 | if not self.config["SIGNINGROUP"]: 388 | log.info("应援团签到任务关闭") 389 | return 390 | log.info("应援团签到任务开始") 391 | try: 392 | n = 0 393 | async for group in self.api.getGroups(): 394 | if group["owner_uid"] == self.mid: 395 | continue 396 | try: 397 | await self.api.signInGroups(group["group_id"], group["owner_uid"]) 398 | except Exception as e: 399 | log.error(group["group_name"] + " 签到失败") 400 | self.errmsg.append(f"应援团签到失败: {e}") 401 | continue 402 | log.debug(group["group_name"] + " 签到成功") 403 | await asyncio.sleep(self.config["SIGNINGROUP"]) 404 | n += 1 405 | if n: 406 | log.success(f"应援团签到任务完成 {n}/{n}") 407 | self.message.append(f" 应援团签到任务完成 {n}/{n}") 408 | else: 409 | log.warning("没有加入应援团") 410 | except Exception as e: 411 | log.exception(e) 412 | log.error("应援团签到任务失败: " + str(e)) 413 | self.errmsg.append("应援团签到任务失败: " + str(e)) 414 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/users.yaml: -------------------------------------------------------------------------------- 1 | USERS: 2 | - access_key: # 注意冒号后的空格 否则会读取失败 英文冒号 3 | white_uid: 0 # 白名单用户ID, 可以是多个用户ID, 以逗号分隔,填写后只会打卡这些用户,黑名单失效,不用就填0 4 | banned_uid: 0 # 黑名单UID 同上,填了后将不会打卡,点赞,分享 用英文逗号分隔 不填则不限制,两个都填0则不限制,打卡所有直播间 5 | - access_key: 6 | white_uid: 0 7 | banned_uid: 0 8 | # 注意对齐 9 | # 多用户以上格式添加 10 | # 井号后为注释 井号前后必须有空格!井号前后必须有空格!井号前后必须有空格! 11 | # 冒号后面也要有空格!冒号前面也要有空格!冒号前面也要有空格! 12 | # 英文冒号,英文逗号!英文逗号!英文逗号! 13 | WRITE_LOG_FILE: False 14 | # 是否写入日志文件 15 | # 填写True时使用默认目录(运行目录log文件夹下) 16 | # 填写绝对路径时写入指定log文件位置 17 | # 不填或填写False则不写入日志文件 18 | 19 | CRON: # 0 0 * * * 20 | # 这里是 cron 表达式, 第一个参数是分钟, 第二个参数是小时 21 | # 例如每天凌晨0点0分执行一次为 0 0 * * * 22 | # 如果不填,则不使用内置定时器,填写正确后要保持该进程一直运行 23 | STOPWATCHINGTIME: # '00:00:00' 或 86400 24 | # 可用于当单次任务运行总时间大于一定时间(尤指直播),可能影响下次任务时,不填写不生效 25 | # 本设置项前仅对直播有效 26 | # 支持 'HH:mm:ss' 格式 和 秒格式 27 | # 'HH:mm:ss' 格式:从现在起下次到这个时间(即24小时内),注意要加引号(单双不限) 28 | # 秒格式:从现在起到多少秒(如86400为一天) 29 | 30 | #########以下为自定义配置######### 31 | ASYNC: 0 # 异步执行,默认同步执行,设置为1则异步执行,开启异步后,将不支持设置点赞CD时间 32 | 33 | LIKE_CD: 3 # 点赞间隔时间,单位秒,默认3秒,仅为同步时生效,设置为0则不点赞 34 | 35 | DANMAKU_CD: 6 # 弹幕间隔时间,单位秒,默认6秒,设置为0则不发弹幕打卡,只能同步打卡 36 | 37 | DANMAKU_NUM: 1 # 设置弹幕发送数量,快速解决B站调整点亮规则 38 | 39 | DANMAKU_CHECK_LIGHT: 0 # 是否仅未点亮的粉丝牌发送弹幕,默认关闭,设置为1则开启 40 | 41 | DANMAKU_CHECK_LEVEL: 1 # 发送弹幕是否包含20级以上粉丝牌,默认开启,设置为0则关闭 42 | 43 | WATCHINGLIVE: 25 # 每日每直播间观看时长,单位 min ,设置为0则关闭, 默认 25 分钟 44 | # 总观看时长为未满20级牌子数*每直播间观看时长 45 | 46 | WEARMEDAL: 0 # 是否弹幕打卡时自动带上当前房间的粉丝牌,避免房间有粉丝牌等级禁言,默认关闭,设置为1则开启 47 | 48 | WHACHASYNER: 1 # 是否异步观看直播间,默认异步观看,设置为0则依次同步观看。 49 | # 说明: 50 | # 由于2024年8月不允许同时观看计算了,异步观看只能从所有直播间随机选择一个进行计算 51 | # 也就是说,例如你观看60分钟,那60分钟将随机分配到所有的牌子对应直播间上。 52 | # 如果设置为0,则不异步观看,只是依次同步观看,如果设置20分钟时间,那么总时间是数量*20分钟 53 | 54 | SIGNINGROUP: 0 # 应援团签到CD时间,单位秒,默认2秒,设置为0则不签到 55 | # 说明: 56 | # 本项目中的异步执行指的是:同时点赞或者分享所有直播间,速度非常快,但缺点就是可能会被B站吞掉亲密度,所以建议粉丝牌较少的用户开启异步执行 57 | 58 | LEVEN: 20 # 牌子停止打卡等级,默认20级 59 | -------------------------------------------------------------------------------- /nonebot_plugin_bilifan/utils.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import shutil 3 | from pathlib import Path 4 | 5 | import yaml 6 | from nonebot import get_bot 7 | 8 | # from nonebot.adapters import Bot 9 | from nonebot.log import logger 10 | 11 | from .main import mains 12 | 13 | config_dir = Path("data/bilifan") 14 | config_dir.mkdir(parents=True, exist_ok=True) 15 | CONFIG_PATH = config_dir / "config.yaml" 16 | if not Path().joinpath("data/bilifan/users.yaml").is_file(): 17 | logger.info("初始化配置文件") 18 | shutil.copy2( 19 | Path(__file__).parent.joinpath("users.yaml"), 20 | Path().joinpath("data/bilifan/users.yaml"), 21 | ) 22 | if not CONFIG_PATH.exists(): 23 | # 创建一个空YAML文件 24 | with CONFIG_PATH.open("w") as f: 25 | yaml.dump({}, f) 26 | 27 | 28 | def load_config(): 29 | if not CONFIG_PATH.exists(): 30 | CONFIG_PATH.touch() 31 | return {} 32 | 33 | with CONFIG_PATH.open("r", encoding="utf-8") as f: 34 | return yaml.safe_load(f) or {} 35 | 36 | 37 | def save_config(data): 38 | with CONFIG_PATH.open("w", encoding="utf-8") as f: 39 | yaml.safe_dump(data, f, allow_unicode=True, default_flow_style=False) 40 | 41 | 42 | async def auto_cup(): 43 | config = load_config() 44 | count: dict = {} 45 | tasks = [] 46 | 47 | for user_id, group_id in config.items(): # noqa: B007 48 | msg_path = Path(f"data/bilifan/{user_id}/login_info.txt") 49 | if msg_path.is_file(): 50 | task = asyncio.create_task(mains(msg_path.parent)) 51 | tasks.append((user_id, group_id, task)) 52 | else: 53 | logger.warning(f"{user_id}尚未登录,已忽略") 54 | 55 | messageList = [] 56 | for user_id, group_id, task in tasks: 57 | message = await task 58 | messageList.append((user_id, group_id, message)) 59 | 60 | for user_id, group_id, message in messageList: 61 | messageStr = "\n".join(message) 62 | logger.info(f"{user_id}用户自动刷牌子任务执行完成,{messageStr}") 63 | if group_id.startswith("group"): 64 | group_num = group_id.split("_")[1] 65 | if group_num in count: 66 | count[group_num] += 1 67 | else: 68 | count[group_num] = 1 69 | elif user_id != group_id: 70 | if group_id in count: 71 | count[group_id] += 1 72 | else: 73 | count[group_id] = 1 74 | await get_bot().send_private_msg(user_id=user_id, message=messageStr) 75 | 76 | for group_num, num in count.items(): 77 | logger.info(f"{group_num}群组自动刷牌子任务执行完成,共{num}个") 78 | await get_bot().send_group_msg( 79 | group_id=group_num, 80 | message=f"本群今日已完成{num}个自动刷牌子任务", 81 | ) 82 | 83 | 84 | def render_forward_msg(msg_list: list, uid=2711142767, name="宁宁"): 85 | try: 86 | uid = get_bot().self_id 87 | name = next(iter(get_bot().config.nickname)) 88 | except Exception as e: 89 | logger.warning(f"获取bot信息错误\n{e}") 90 | forward_msg = [] 91 | for msg in msg_list: 92 | forward_msg.append( 93 | { 94 | "type": "node", 95 | "data": {"name": str(name), "uin": str(uid), "content": msg}, 96 | }, 97 | ) 98 | return forward_msg 99 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "nonebot_plugin_bilifan" 3 | version = "0.4.4" 4 | description = "刷站粉丝牌子的机器人插件" 5 | authors = ["Agnes_Digital "] 6 | license = "GPLv3" 7 | readme = "README.md" 8 | homepage = "https://github.com/Agnes4m/nonebot_plugin_bilifan" 9 | repository = "https://github.com/Agnes4m/nonebot_plugin_bilifan" 10 | keywords = ["bilibili", "nonebot2", "plugin"] 11 | classifiers = [ 12 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 13 | "Programming Language :: Python", 14 | "Programming Language :: Python :: 3", 15 | "Programming Language :: Python :: 3.9", 16 | "Programming Language :: Python :: 3.10", 17 | "Programming Language :: Python :: 3.11", 18 | "Programming Language :: Python :: 3.12", 19 | "Operating System :: OS Independent", 20 | ] 21 | include = [ 22 | "LICENSE","README.md" 23 | ] 24 | 25 | [tool.poetry.dependencies] 26 | python = "^3.9" 27 | nonebot2 = "^2.1.0" 28 | nonebot-adapter-onebot = ">=2.2.5" 29 | nonebot_plugin_apscheduler = ">=0.3.0" 30 | nonebot_plugin_alconna = ">=0.50.0" 31 | pillow = ">=10.0.0" 32 | aiohttp-socks = "^0.8.0" 33 | pyyaml = "^6.0" 34 | qrcode = "^7.4.2" 35 | anyio = ">=4.6.2" 36 | 37 | [build-system] 38 | requires = ["poetry-core>=1.0.0"] 39 | build-backend = "poetry.core.masonry.api" 40 | 41 | 42 | [tool.black] 43 | line-length = 89 44 | target-version = ["py310", "py311", "py312"] 45 | include = '\.pyi?$' 46 | # skip-string-normalization = true 47 | 48 | [tool.ruff.format] 49 | docstring-code-format = true 50 | line-ending = "lf" 51 | 52 | [tool.ruff.lint.isort] 53 | combine-as-imports = true 54 | detect-same-package = true 55 | extra-standard-library = ["typing_extensions"] 56 | split-on-trailing-comma = true --------------------------------------------------------------------------------