├── .gitignore ├── LICENSE ├── README.md ├── nonebot └── adapters │ └── mirai2 │ ├── __init__.py │ ├── adapter.py │ ├── bot.py │ ├── bot.pyi │ ├── config.py │ ├── event │ ├── __init__.py │ ├── base.py │ ├── message.py │ ├── meta.py │ ├── notice.py │ └── request.py │ ├── exception.py │ ├── log.py │ ├── message.py │ ├── permission.py │ └── utils.py └── pyproject.toml /.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 | 131 | # poetry 132 | poetry.lock -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nonebot2_adapter_MiraiApiHttp2 2 | 3 | # _✨ Mirai_Api_Http 2.x 协议适配 ✨_ 4 | 5 | **依赖于 nonebot2.0.0b1** 6 | 7 | ## 使用方法 8 | 请看本仓库的 [wiki](https://github.com/ieew/nonebot_adapter_mirai2/wiki) 9 | 10 | ## 社群 11 | 12 | - qq频道: [点击链接加入讨论子频道【mirai2适配器】](https://qun.qq.com/qqweb/qunpro/share?_wv=3&_wwv=128&inviteCode=1iFUvf&appChannel=share&businessType=7&from=246610&biz=ka "不知道这链接能存活多久,暂时先挂着看看") 13 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/__init__.py: -------------------------------------------------------------------------------- 1 | from .bot import Bot 2 | from .event import Event, MessageEvent, GroupMessage, FriendMessage, TempMessage # noqa 3 | from .adapter import Adapter 4 | from .message import MessageChain, MessageSegment, MessageType 5 | from .permission import ( 6 | UserPermission, 7 | GROUP_MEMBER, 8 | GROUP_ADMIN, 9 | GROUP_ADMINS, 10 | GROUP_OWNER, 11 | GROUP_OWNER_SUPERUSER, 12 | SUPERUSER 13 | ) 14 | 15 | __all__ = [ 16 | "Bot", "Event", "Adapter", "MessageChain", "MessageSegment", "MessageType" 17 | "MessageEvent", "GroupMessage", "FriendMessage", "TempMessage", 18 | "UserPermission", "GROUP_MEMBER", "GROUP_ADMIN", "GROUP_ADMINS", 19 | "GROUP_OWNER", "GROUP_OWNER_SUPERUSER", "SUPERUSER" 20 | ] 21 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/adapter.py: -------------------------------------------------------------------------------- 1 | import json 2 | import asyncio 3 | import contextlib 4 | from typing import Any, Dict, List, Optional, Literal, cast 5 | 6 | from nonebot.utils import escape_tag 7 | from nonebot.adapters import Adapter as BaseAdapter 8 | from nonebot.exception import ActionFailed, WebSocketClosed 9 | from nonebot.drivers import ( 10 | URL, 11 | Driver, 12 | Request, 13 | WebSocket, 14 | ReverseDriver, 15 | ForwardDriver, 16 | WebSocketServerSetup 17 | ) 18 | 19 | from . import log 20 | from .bot import Bot 21 | from .config import Config 22 | from .event import Event 23 | from .utils import ( 24 | SyncIDStore, 25 | process_event, 26 | snake_to_camel, 27 | MiraiDataclassEncoder 28 | ) 29 | 30 | class Adapter(BaseAdapter): 31 | 32 | def __init__(self, driver: Driver, **kwargs: Any): 33 | super().__init__(driver, **kwargs) 34 | self.mirai_config: Config = Config(**self.config.dict()) 35 | self.connections: Dict[str, WebSocket] = {} 36 | self.tasks: List["asyncio.Task"] = [] 37 | self.setup() 38 | 39 | @classmethod 40 | def get_name(cls): 41 | return "mirai2" 42 | 43 | def setup(self) -> None: 44 | if isinstance(self.driver, ReverseDriver): 45 | self.setup_websocket_server( 46 | WebSocketServerSetup( 47 | URL("/mirai2/ws"), self.get_name(), self._handle_ws_server 48 | ) 49 | ) 50 | 51 | if isinstance(self.driver, ForwardDriver) and self.mirai_config.mirai_forward: 52 | if not all([ 53 | isinstance(self.mirai_config.verify_key, str), 54 | isinstance(self.mirai_config.mirai_host, str), 55 | isinstance(self.mirai_config.mirai_port, int), 56 | isinstance(self.mirai_config.mirai_qq, list), 57 | ]): 58 | raise ValueError("请检查环境变量中的 Verify_key, Mirai_host, Mirai_port, Mirai_qq 是否异常") 59 | self.driver.on_startup(self._start_ws_client) 60 | self.driver.on_shutdown(self._stop_ws_client) 61 | 62 | async def _handle_ws_server(self, websocket: WebSocket): 63 | access_token = self.mirai_config.mirai_access_token 64 | if access_token is not None: 65 | if access_token != websocket.request.headers.get("access_token", ""): 66 | await websocket.close(code=1000, reason="access_token error") 67 | return 68 | 69 | await websocket.accept() 70 | 71 | await websocket.send(json.dumps({"syncId": "-1", "command": "botList", "content": {}})) 72 | bot_list = json.loads(await websocket.receive()).get("data", {}).get("data", []) 73 | 74 | qqid = websocket.request.headers.get("qq") 75 | if int(qqid) not in bot_list: 76 | await websocket.close(code=1000, reason=f"账号 {qqid} 未在客户端登录") 77 | return 78 | 79 | await websocket.send(json.dumps({ 80 | "syncId": "-1", "command": "verify", "content": { 81 | "verifyKey": self.mirai_config.verify_key, 82 | "sessionKey": None, 83 | "qq": qqid 84 | } 85 | })) 86 | code = json.loads(await websocket.receive()).get("data", {}) 87 | if code.get("code"): 88 | log.error(f"{qqid}, {code}") 89 | return 90 | 91 | bot = Bot(self, qqid) 92 | self.bot_connect(bot) 93 | self.connections[qqid] = websocket 94 | log.info(f"({bot.self_id}) connection ...") 95 | 96 | try: 97 | while True: 98 | data = await websocket.receive() 99 | json_data = json.loads(data) 100 | if json_data.get("data"): 101 | self._event_handle(bot, json_data) 102 | except WebSocketClosed as e: 103 | qqid = ", ".join(self.connections) 104 | log.warning(f"WebSocket for Bot {escape_tag(qqid)} closed by peer") 105 | except Exception as e: 106 | log.error(f"Error while process data from websocket " 107 | f"for bot {escape_tag(bot.self_id)}.", e) 108 | finally: 109 | with contextlib.suppress(Exception): 110 | await websocket.close() 111 | self.connections.pop(qqid, None) 112 | self.bot_disconnect(bot=bot) 113 | 114 | async def _start_ws_client(self): 115 | for qq in self.mirai_config.mirai_qq: 116 | try: 117 | ws_url = URL(f"ws://{self.mirai_config.mirai_host}:{self.mirai_config.mirai_port}/all") 118 | self.tasks.append(asyncio.create_task(self._ws_client(qq, ws_url))) 119 | except Exception as e: 120 | log.error(f"Bad url {escape_tag(str(ws_url))} " 121 | "in mirai2 forward websocket config", 122 | e) 123 | 124 | async def _stop_ws_client(self): 125 | for task in self.tasks: 126 | if not task.done(): 127 | task.cancel() 128 | 129 | async def _ws_client(self, qq: str, url: URL): 130 | headers = { 131 | "verifyKey": self.mirai_config.verify_key, 132 | "qq": qq 133 | } 134 | request = Request( 135 | "GET", 136 | url=url, 137 | headers=headers, 138 | timeout=3 139 | ) 140 | 141 | while True: 142 | try: 143 | async with self.websocket(request) as ws: 144 | log.debug(f"WebSocket Connection to {escape_tag(str(url))} established") 145 | try: 146 | bot = Bot(self, qq) 147 | self.connections[qq] = ws 148 | self.bot_connect(bot) 149 | log.info(f"Bot {escape_tag(qq)} connected") 150 | 151 | data = json.loads(await ws.receive()).get("data", {}) 152 | if data.get("code") > 0: 153 | log.warning(f'{json_data["data"]["msg"]}: {qq}') 154 | return 155 | 156 | while True: 157 | data = await ws.receive() 158 | json_data = json.loads(data) 159 | self._event_handle(bot, json_data) 160 | except WebSocketClosed as e: 161 | log.error("WebSocket Closed", e) 162 | except Exception as e: 163 | log.error("Error while process data from websocket" 164 | f"{escape_tag(str(url))}. Trying to reconnect...", 165 | e 166 | ) 167 | finally: 168 | self.connections.pop(qq, None) 169 | self.bot_disconnect(bot) 170 | except Exception as e: 171 | log.error("Error while setup websocket to " 172 | f"{escape_tag(str(url))}. Trying to reconnect...", 173 | e 174 | ) 175 | await asyncio.sleep(3) 176 | 177 | def _event_handle(self, bot: Bot, event: Dict): 178 | if int(event.get("syncId") or "0") >= 0: 179 | SyncIDStore.add_response(event) 180 | return 181 | asyncio.create_task(process_event( 182 | bot, 183 | event=Event.new({ 184 | **event["data"], 185 | "self_id": bot.self_id 186 | }) 187 | )) 188 | 189 | async def _call_api(self, bot: Bot, api: str, 190 | subcommand: Optional[Literal['get', 'update']] = None, **data: Any) -> Any: 191 | sync_id = SyncIDStore.get_id() 192 | api = snake_to_camel(api) 193 | data = {snake_to_camel(k): v for k, v in data.items()} 194 | body = { 195 | 'syncId': sync_id, 196 | 'command': api, 197 | 'subcommand': subcommand, 198 | 'content': { 199 | **data, 200 | } 201 | } 202 | 203 | await cast(WebSocket, self.connections[str(bot.self_id)]).send( 204 | json.dumps( 205 | body, 206 | cls=MiraiDataclassEncoder 207 | ) 208 | ) 209 | 210 | result: Dict[str, Any] = await SyncIDStore.fetch_response( 211 | sync_id, timeout=self.config.api_timeout) 212 | 213 | if ('data') not in result or (result['data']).get('code') not in (None, 0): 214 | raise ActionFailed( 215 | f'{self.get_name()} | {result.get("data") or result}' 216 | ) 217 | 218 | return result['data'] 219 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/bot.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Optional, Union 2 | from nonebot.typing import overrides 3 | 4 | from nonebot.adapters import Bot as BaseBot 5 | 6 | from .event.message import FriendMessage, GroupMessage, TempMessage 7 | 8 | from .event import Event 9 | from .message import MessageChain, MessageSegment 10 | 11 | 12 | class Bot(BaseBot): 13 | 14 | @overrides(BaseBot) 15 | async def send( 16 | self, 17 | event: Event, 18 | message: Union[str, MessageChain, MessageSegment], 19 | at_sender: Optional[bool] = False, 20 | quote: Optional[int] = None, 21 | **kwargs, 22 | ) -> Any: 23 | """ 24 | :说明: 25 | 26 | 根据 ``event`` 向触发事件的主体发送信息 27 | 28 | :参数: 29 | 30 | * ``event: Event``: Event对象 31 | * ``message: Union[MessageChain, MessageSegment, str]``: 要发送的消息 32 | * ``at_sender: bool``: 是否 @ 事件主体 33 | """ 34 | if not isinstance(message, MessageChain): 35 | message = MessageChain(message) 36 | if isinstance(event, FriendMessage): 37 | return await self.send_friend_message(target=event.sender.id, 38 | message_chain=message, 39 | quote=quote) 40 | elif isinstance(event, GroupMessage): 41 | if at_sender: 42 | message = MessageSegment.at(event.sender.id) + message 43 | return await self.send_group_message(group=event.sender.group.id, 44 | message_chain=message, 45 | quote=quote) 46 | elif isinstance(event, TempMessage): 47 | return await self.send_temp_message(qq=event.sender.id, 48 | group=event.sender.group.id, 49 | message_chain=message, 50 | quote=quote) 51 | else: 52 | raise ValueError(f'Unsupported event type {event!r}.') 53 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/bot.pyi: -------------------------------------------------------------------------------- 1 | from typing import Literal, Union, Optional, overload 2 | 3 | from nonebot.adapters import Bot as BaseBot 4 | 5 | from .event import Event 6 | from .message import MessageChain, MessageSegment 7 | 8 | 9 | class Bot(BaseBot): 10 | r""" 11 | mirai-api-http 协议 Bot 适配。 12 | 13 | \:\:\: warning 14 | API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 15 | 16 | 部分字段可能与文档在符号上不一致 17 | \:\:\: 18 | 19 | """ 20 | 21 | _type = 'mirai' 22 | 23 | async def send( 24 | self, *, 25 | event: Event, 26 | message: Union[MessageChain, MessageSegment, str], 27 | at_sender: Optional[bool] = False, 28 | quote: Optional[int] = None 29 | ): 30 | """ 31 | :说明: 32 | 33 | 根据 ``event`` 向触发事件的主体发送信息 34 | 35 | :参数: 36 | 37 | * ``event: Event``: Event对象 38 | * ``message: Union[MessageChain, MessageSegment, str]``: 要发送的消息 39 | * ``at_sender: bool``: 是否 @ 事件主体 40 | """ 41 | ... 42 | 43 | async def about(self): 44 | """ 45 | :说明: 46 | 47 | 获取插件信息 48 | 49 | :参数: 50 | 51 | * 无 52 | """ 53 | ... 54 | 55 | async def message_from_id(self, *, id: int): 56 | """ 57 | :说明: 58 | 59 | 获取消息 id 的内容 60 | 61 | :参数: 62 | 63 | * ``id: int`` 消息 id 64 | """ 65 | ... 66 | 67 | async def friend_list(self): 68 | """ 69 | :说明: 70 | 71 | 获取好友列表 72 | 73 | :参数: 74 | 75 | * 无 76 | """ 77 | ... 78 | 79 | async def group_list(self): 80 | """ 81 | :说明: 82 | 83 | 获取群列表 84 | 85 | :参数: 86 | 87 | * 无 88 | """ 89 | ... 90 | 91 | async def member_list(self, *, target: int): 92 | """ 93 | :说明: 94 | 95 | 获取群 target 的成员列表 96 | 97 | :参数: 98 | 99 | * ``target: int`` 群 id 100 | """ 101 | ... 102 | 103 | async def bot_pro_file(self): 104 | """ 105 | :说明: 106 | 107 | 获取Bot资料 108 | 109 | :参数: 110 | 111 | * 无 112 | """ 113 | ... 114 | 115 | async def friend_pro_file(self, *, target: int): 116 | """ 117 | :说明: 118 | 119 | 获取好友 target 的资料 120 | 121 | :参数: 122 | 123 | * ``target: int`` 好友 id 124 | """ 125 | ... 126 | 127 | async def member_profile(self, *, target: int, member_id: int): 128 | """ 129 | :说明: 130 | 131 | 获取群 target 中的成员 member_id 的资料 132 | 133 | :参数: 134 | 135 | * ``target: int`` 群 id 136 | * ``member_id`` 成员 id 137 | """ 138 | ... 139 | 140 | async def send_friend_message( 141 | self, *, 142 | target: int, 143 | message_chain: MessageChain, 144 | quote: Optional[int] 145 | ): 146 | """ 147 | :说明: 148 | 149 | 发送好友消息 150 | 151 | :必填: 152 | 153 | * ``target: int`` 好友 id 154 | * ``message_chain: MessageChain`` 消息内容: (MessageChain("xxxx")) 155 | 156 | :选填: 157 | 158 | * ``quote: int`` 需引用消息的 id 159 | """ 160 | ... 161 | 162 | async def send_group_message( 163 | self, *, 164 | target: int, 165 | message_chain: MessageChain, 166 | quote: Optional[int] 167 | ): 168 | """ 169 | :说明: 170 | 171 | 发送消息 message_chain 到 target 群 172 | 173 | :必填: 174 | 175 | * ``target: int`` 群 id 176 | * ``message_chain: MessageChain`` 消息内容: (MessageChain("xxxx")) 177 | 178 | :选填: 179 | 180 | * ``quote: int`` 需引用消息的 id 181 | """ 182 | ... 183 | 184 | async def send_temp_message( 185 | self, *, 186 | qq: int, 187 | group: int, 188 | message_chain: MessageChain, 189 | quote: Optional[int] 190 | ): 191 | """ 192 | :说明: 193 | 194 | 发送消息 message_chain 到 target 群 195 | 196 | :必填: 197 | 198 | * ``qq: int`` qq id 199 | * ``group: int`` 群 id 200 | * ``message_chain: MessageChain`` 消息内容: (MessageChain("xxxx")) 201 | 202 | :选填: 203 | 204 | * ``quote: int`` 需引用消息的 id 205 | """ 206 | ... 207 | 208 | async def send_nudge( 209 | self, *, 210 | target: int, 211 | subject: int, 212 | kind: str 213 | ): 214 | """ 215 | :说明: 216 | 217 | 发送头像戳一戳消息 218 | 219 | :参数: 220 | 221 | * ``target: int`` 戳一戳目标 222 | * ``subject: int`` 戳一戳接受主体(戳一戳信息会发送到该主体,为 群号/qq号) 223 | * ``kind: str`` 上下文类型,可选值: (Friend, Group, Stranger) 224 | """ 225 | ... 226 | 227 | async def recall(self, *, target: int): 228 | """ 229 | :说明: 230 | 231 | 撤回消息 232 | 233 | :参数: 234 | 235 | * ``target: int`` 需要撤回的消息的 id 236 | """ 237 | ... 238 | 239 | async def file_list( 240 | self, *, 241 | id: str, 242 | path: Optional[str], 243 | target: Optional[int], 244 | group: Optional[int], 245 | qq: Optional[int], 246 | with_download_info: Optional[bool], 247 | offset: Optional[int], 248 | size: Optional[int] 249 | ): 250 | """ 251 | :说明: 252 | 253 | 查看文件列表 254 | 255 | :必填: 256 | 257 | * ``id: int`` 文件夹id,空串为根目录 258 | 259 | :可选: 260 | 261 | * ``path: str`` 文件夹路径,文件夹允许重名,不保证准确,准确定位使用 id 262 | * ``target: int`` 群号或好友 qq 号 263 | * ``group: int`` 群号 264 | * ``qq: int`` 好友 qq 号 265 | * ``with_download_info: bool`` 是否携带下载信息,额外请求,无必要不要携带 266 | * ``offset: int`` 分页偏移 267 | * ``size: int`` 分页大小 268 | """ 269 | ... 270 | 271 | async def file_info( 272 | self, *, 273 | id: str, 274 | path: Optional[str], 275 | target: Optional[int], 276 | group: Optional[int], 277 | qq: Optional[int], 278 | with_download_info: Optional[bool] 279 | ): 280 | """ 281 | :说明: 282 | 283 | 获取文件信息 284 | 285 | :必填: 286 | 287 | * ``id: int`` 文件夹id,空串为根目录 288 | 289 | :可选: 290 | 291 | * ``path: str`` 文件夹路径,文件夹允许重名,不保证准确,准确定位使用 id 292 | * ``target: int`` 群号或好友 qq 号 293 | * ``group: int`` 群号 294 | * ``qq: int`` 好友 qq 号 295 | * ``with_download_info: bool`` 是否携带下载信息,额外请求,无必要不要携带 296 | """ 297 | ... 298 | 299 | async def file_mkdir( 300 | self, *, 301 | id: str, 302 | directory_name: str, 303 | path: Optional[str], 304 | target: Optional[int], 305 | group: Optional[int], 306 | qq: Optional[int] 307 | ): 308 | """ 309 | :说明: 310 | 311 | 创建文件夹 312 | 313 | :必填: 314 | 315 | * ``id: int`` 文件夹id,空串为根目录 316 | * ``directory_name: str`` 是否携带下载信息,额外请求,无必要不要携带 317 | 318 | :可选: 319 | 320 | * ``path: str`` 文件夹路径,文件夹允许重名,不保证准确,准确定位使用 id 321 | * ``target: int`` 群号或好友 qq 号 322 | * ``group: int`` 群号 323 | * ``qq: int`` 好友 qq 号 324 | """ 325 | ... 326 | 327 | async def file_delete( 328 | self, *, 329 | id: str, 330 | path: Optional[str], 331 | target: Optional[int], 332 | group: Optional[int], 333 | qq: Optional[int] 334 | ): 335 | """ 336 | :说明: 337 | 338 | 删除文件 339 | 340 | :必填: 341 | 342 | * ``id: int`` 文件夹id,空串为根目录 343 | 344 | :可选: 345 | 346 | * ``path: str`` 文件夹路径,文件夹允许重名,不保证准确,准确定位使用 id 347 | * ``target: int`` 群号或好友 qq 号 348 | * ``group: int`` 群号 349 | * ``qq: int`` 好友 qq 号 350 | """ 351 | ... 352 | 353 | async def file_move( 354 | self, *, 355 | id: str, 356 | path: Optional[str], 357 | target: Optional[int], 358 | group: Optional[int], 359 | qq: Optional[int], 360 | move_to: Optional[str], 361 | move_to_path: Optional[str] 362 | ): 363 | """ 364 | :说明: 365 | 366 | 移动文件 367 | 368 | :必填: 369 | 370 | * ``id: int`` 文件夹id,空串为根目录 371 | 372 | :可选: 373 | 374 | * ``path: str`` 文件夹路径,文件夹允许重名,不保证准确,准确定位使用 id 375 | * ``target: int`` 群号或好友 qq 号 376 | * ``group: int`` 群号 377 | * ``qq: int`` 好友 qq 号 378 | * ``move_to: str`` 移动目标文件夹 id 379 | * ``move_to_path: str`` 移动目标文件夹路径,文件夹允许重名,不保证准确,准确定位使用 move_to 参数 380 | """ 381 | ... 382 | 383 | async def file_rename( 384 | self, *, 385 | id: str, 386 | path: Optional[str], 387 | target: Optional[int], 388 | group: Optional[int], 389 | qq: Optional[int], 390 | rename_to: Optional[int] 391 | ): 392 | """ 393 | :说明: 394 | 395 | 重命名文件 396 | 397 | :必填: 398 | 399 | * ``id: int`` 文件夹id,空串为根目录 400 | 401 | :可选: 402 | 403 | * ``path: str`` 文件夹路径,文件夹允许重名,不保证准确,准确定位使用 id 404 | * ``target: int`` 群号或好友 qq 号 405 | * ``group: int`` 群号 406 | * ``qq: int`` 好友 qq 号 407 | * ``rename_to: int`` 新文件名 408 | """ 409 | ... 410 | 411 | async def delete_friend(self, *, target: int): 412 | """ 413 | :说明: 414 | 415 | 删除好友 416 | 417 | :参数: 418 | 419 | * ``target: int`` 好友 id 420 | """ 421 | ... 422 | 423 | async def mute( 424 | self, *, 425 | target: int, 426 | member_id: int, 427 | time: int 428 | ): 429 | """ 430 | :说明: 431 | 432 | 禁言群 target 的 member_id 成员 time 秒 433 | 434 | :参数: 435 | 436 | * ``target: int`` 群 id 437 | * ``member_id: int`` 成员 id 438 | * ``time: int`` 时长(单位秒) 439 | """ 440 | ... 441 | 442 | async def unmute(self, *, target: int, member_id: int): 443 | """ 444 | :说明: 445 | 446 | 解除群成员禁言 447 | 448 | :参数: 449 | 450 | * ``target: int`` 群 id 451 | * ``member_id: int`` 成员 id 452 | """ 453 | ... 454 | 455 | async def kick( 456 | self, *, 457 | target: int, 458 | member_id: int, 459 | msg: Optional[str] 460 | ): 461 | """ 462 | :说明: 463 | 464 | 移除群成员 465 | 466 | :必填: 467 | 468 | * ``target: int`` 群 id 469 | * ``member_id: int`` 成员 id 470 | 471 | :可选: 472 | 473 | * ``msg: str`` 信息 474 | """ 475 | ... 476 | 477 | async def quit(self, *, target: int): 478 | """ 479 | :说明: 480 | 481 | 退出群聊 482 | 483 | :参数: 484 | 485 | * ``target: int`` 群 id 486 | """ 487 | ... 488 | 489 | async def mute_all(self, *, target: int): 490 | """ 491 | :说明: 492 | 493 | 全体禁言 494 | 495 | :参数: 496 | 497 | * ``target: int`` 群 id 498 | """ 499 | ... 500 | 501 | async def unmute_all(self, *, target: int): 502 | """ 503 | :说明: 504 | 505 | 解除全体禁言 506 | 507 | :参数: 508 | 509 | * ``target: int`` 群 id 510 | """ 511 | ... 512 | 513 | async def set_essence(self, *, target: int, message_id: int): 514 | """ 515 | :说明: 516 | 517 | 设置**群消息** id 为精华消息 518 | 519 | :参数: 520 | 521 | * ``target: int`` 群号 522 | * ``message_id: int`` 消息号 523 | """ 524 | ... 525 | 526 | @overload 527 | async def group_config( 528 | self, *, 529 | subcommand: Literal["get", "update"], 530 | target: int, 531 | ): 532 | """ 533 | :说明: 534 | 535 | 获取群设置(当 subcommand="get" 时) 536 | 537 | :参数: 538 | 539 | * ``subcommand: str`` 只可以使用 "get" 540 | * ``target: int`` 群 id 541 | """ 542 | ... 543 | 544 | @overload 545 | async def group_config( 546 | self, *, 547 | subcommand: Literal["get", "update"], 548 | target: int, 549 | config: dict, 550 | ): 551 | """ 552 | :说明: 553 | 554 | 修改群设置(当 subcommand="update" 时) 555 | 556 | :参数: 557 | 558 | * ``subcommand: str`` 只可以使用 "update" 559 | * ``target: int`` 群 id 560 | * ``config: dict`` 群设置 dict 561 | :config 例子: 562 | { 563 | "name": "群名称", 564 | "announcement": "群公告", 565 | "confessTalk": True, # 是否开启坦白说 566 | "allowMemberInvite": True # 是否允许群员邀请 567 | "autoApprove": True # 是否开启自动审批入群 568 | "anonymousChat": True # 是否允许匿名聊天 569 | } 570 | """ 571 | ... 572 | 573 | async def member_info(self, *, target: int): 574 | """ 575 | :说明: 576 | 577 | 群员设置相关(暂不支持) 578 | 579 | :参数: 580 | 581 | * ``target: int`` 群 id 582 | """ 583 | ... 584 | 585 | async def member_admin( 586 | self, *, 587 | target: int, 588 | member_id: int, 589 | assign: bool 590 | ): 591 | """ 592 | :说明: 593 | 594 | 修改群员管理员权限 595 | 596 | :参数: 597 | 598 | * ``target: int`` 群 id 599 | * ``member_id: int`` 群成员 id 600 | * ``assign: bool`` 是否设置为管理员 601 | """ 602 | ... 603 | 604 | async def anno_list( 605 | self, *, 606 | id: int, 607 | offset: Optional[int], 608 | size: Optional[int] 609 | ): 610 | """ 611 | :说明: 612 | 613 | 获取群公告 614 | 615 | :参数: 616 | 617 | * ``id: int`` 群 id 618 | * ``offset: int`` 分页参数 619 | * ``size: int`` 分页参数 默认10 620 | """ 621 | ... 622 | 623 | async def anno_publish( 624 | self, *, 625 | target: int, 626 | content: str, 627 | send_to_new_member: Optional[bool], 628 | pinned: Optional[bool], 629 | show_edit_card: Optional[bool], 630 | show_popup: Optional[bool], 631 | require_confirmation: Optional[bool], 632 | image_url: Optional[str], 633 | image_path: Optional[str], 634 | image_base64: Optional[str] 635 | ): 636 | """ 637 | :说明: 638 | 639 | 发送群公告 640 | 641 | :参数: 642 | 643 | * ``target: int`` 群号 644 | * ``content: str`` 公告内容 645 | * ``send_to_new_member`` 是否发送给新成员 646 | * ``pinned: bool`` 是否置顶 647 | * ``showEditCard: bool`` 是否显示群成员修改群名片的引导 648 | * ``showPopup: bool`` 是否自动弹出 649 | * ``requireConfirmation: bool`` 是否需要群成员确认 650 | * ``imageUrl: str`` 公告图片 url 651 | * ``imagePath: str`` 公告图片本地路径 652 | * ``imageBase64: str`` 公告图片 base64 编码 653 | """ 654 | ... 655 | 656 | async def anno_delete( 657 | self, *, id: int, fid: str 658 | ): 659 | """ 660 | :说明: 661 | 662 | 删除群公告 663 | 664 | :参数: 665 | 666 | * ``id: int`` 群号 667 | * ``fid: str`` 群公告唯一 id 668 | """ 669 | ... 670 | 671 | async def resp_newFriendRequestEvent( 672 | self, *, 673 | event_id: int, 674 | group_id: int, 675 | from_id: int, 676 | operate: int, 677 | message: str 678 | ): 679 | """ 680 | :说明: 681 | 682 | 处理添加好友事件 683 | 684 | :参数: 685 | 686 | * ``event_id: int`` 事件 id 687 | * ``group_id: int`` 群 id 688 | * ``from_id: int`` 事件对应申请人 qq id 689 | * ``operate: int`` 响应操作类型: 0 同意 1 拒绝 2 拒绝并加入黑名单 690 | * ``message: str`` 回复的消息内容 691 | """ 692 | ... 693 | 694 | async def resp_memberJoinRequestEvent( 695 | self, *, 696 | event_id: int, 697 | group_id: int, 698 | from_id: int, 699 | operate: int, 700 | message: str 701 | ): 702 | """ 703 | :说明: 704 | 705 | 处理用户入群申请事件 706 | 707 | :参数: 708 | 709 | * ``event_id: int`` 事件 id 710 | * ``group_id: int`` 群 id 711 | * ``from_id: int`` 事件对应申请人 qq id 712 | * ``operate: int`` 响应操作类型: 0 同意入群 1 拒绝入群 2 忽略请求 3 拒绝入群并加入黑名单 4 忽略请求并加入黑名单 # noqa 713 | * ``message: str`` 回复的消息内容 714 | """ 715 | ... 716 | 717 | async def resp_botInvitedJoinGroupRequestEvent( 718 | self, *, 719 | event_id: int, 720 | group_id: int, 721 | from_id: int, 722 | operate: int, 723 | message: str 724 | ): 725 | """ 726 | :说明: 727 | 728 | 处理 bot 被邀请入群事件 729 | 730 | :参数: 731 | 732 | * ``event_id: int`` 事件 id 733 | * ``group_id: int`` 群 id 734 | * ``from_id: int`` 事件对应申请人 qq id 735 | * ``operate: int`` 响应操作类型: 0 同意邀请 1 拒绝邀请 736 | * ``message: str`` 回复的消息内容 737 | """ 738 | ... 739 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/config.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional 2 | 3 | from pydantic import Field, Extra, BaseModel 4 | 5 | 6 | class Config(BaseModel): 7 | """ 8 | mirai2 配置类 9 | 10 | :配置项: 11 | 12 | - ``verify_key`` / ``mirai_verify_key``: mirai-api-http 的 verify_key 13 | - ``mirai_host``: mirai-api-http 的地址 14 | - ``mirai_port``: mirai-api-http 的端口 15 | - ``mirai_qq``: mirai-api-http qq 列表 16 | - ``mirai_reverse``: 是否启用正向 ws 17 | - ``mirai_access_token``: 反向 ws 专用的对客户端鉴权 token 18 | """ 19 | 20 | verify_key: str = Field( 21 | None, alias="mirai_verify_key" 22 | ) 23 | mirai_host: Optional[str] = None 24 | mirai_port: Optional[int] = None 25 | mirai_qq: Optional[List[str]] = None 26 | mirai_forward: Optional[bool] = True 27 | mirai_access_token: Optional[str] = None 28 | 29 | class Config: 30 | extra = Extra.ignore 31 | allow_population_by_field_name = True 32 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/event/__init__.py: -------------------------------------------------------------------------------- 1 | r""" 2 | \:\:\: warning 3 | 事件中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 4 | 5 | 部分字段可能与文档在符号上不一致 6 | \:\:\: 7 | """ 8 | from .base import (Event, GroupChatInfo, GroupInfo, PrivateChatInfo, 9 | UserPermission) 10 | from .message import * # noqa 11 | from .notice import * # noqa 12 | from .request import * # noqa 13 | from .meta import * # noqa 14 | 15 | __all__ = [ # noqa 16 | 'Event', 'GroupChatInfo', 'GroupInfo', 'PrivateChatInfo', 'UserPermission', 17 | 'MessageSource', 'MessageEvent', 'GroupMessage', 'FriendMessage', 18 | 'TempMessage', 'NoticeEvent', 'MuteEvent', 'BotMuteEvent', 'BotUnmuteEvent', 19 | 'MemberMuteEvent', 'MemberUnmuteEvent', 'BotJoinGroupEvent', 20 | 'BotLeaveEventActive', 'BotLeaveEventKick', 'MemberJoinEvent', 21 | 'MemberLeaveEventKick', 'MemberLeaveEventQuit', 'FriendRecallEvent', 22 | 'GroupRecallEvent', 'GroupStateChangeEvent', 'GroupNameChangeEvent', 23 | 'GroupEntranceAnnouncementChangeEvent', 'GroupMuteAllEvent', 24 | 'GroupAllowAnonymousChatEvent', 'GroupAllowConfessTalkEvent', 25 | 'GroupAllowMemberInviteEvent', 'MemberStateChangeEvent', 26 | 'MemberCardChangeEvent', 'MemberSpecialTitleChangeEvent', 27 | 'BotGroupPermissionChangeEvent', 'MemberPermissionChangeEvent', 28 | 'RequestEvent', 'NewFriendRequestEvent', 'MemberJoinRequestEvent', 29 | 'BotInvitedJoinGroupRequestEvent', 'MetaEvent', 'BotOnlineEvent', 30 | 'BotOfflineEventActive', 'BotOfflineEventForce', 'BotOfflineEventDropped' 31 | 'BotReloginEvent' 32 | ] 33 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/event/base.py: -------------------------------------------------------------------------------- 1 | import json 2 | from enum import Enum 3 | from typing_extensions import Literal 4 | from typing import Any, Dict, Optional, Type 5 | 6 | from pydantic import BaseModel, Field, ValidationError 7 | 8 | from nonebot.typing import overrides 9 | from nonebot.utils import escape_tag 10 | from nonebot.adapters import Event as BaseEvent 11 | from nonebot.adapters import Message as BaseMessage 12 | 13 | from .. import log 14 | 15 | 16 | class UserPermission(str, Enum): 17 | """ 18 | :说明: 19 | 20 | 用户权限枚举类 21 | 22 | * ``OWNER``: 群主 23 | * ``ADMINISTRATOR``: 群管理 24 | * ``MEMBER``: 普通群成员 25 | """ 26 | OWNER = 'OWNER' 27 | ADMINISTRATOR = 'ADMINISTRATOR' 28 | MEMBER = 'MEMBER' 29 | 30 | 31 | class GroupInfo(BaseModel): 32 | id: int 33 | name: str 34 | permission: UserPermission 35 | 36 | 37 | class GroupChatInfo(BaseModel): 38 | id: int 39 | name: str = Field(alias='memberName') 40 | special_title: Optional[str] = Field(alias='specialTitle') 41 | permission: UserPermission 42 | join_timestamp: Optional[int] = Field(alias='joinTimestamp') 43 | last_speak_timestamp: Optional[int] = Field(alias='lastSpeakTimestamp') 44 | mute_time_remaining: Optional[int] = Field(alias='muteTimeRemaining') 45 | group: GroupInfo 46 | 47 | 48 | class PrivateChatInfo(BaseModel): 49 | id: int 50 | nickname: str 51 | remark: str 52 | 53 | 54 | class StrangerChatInfo(BaseModel): 55 | id: int 56 | nickname: str 57 | remark: str 58 | 59 | 60 | class OtherChatInfo(BaseModel): 61 | id: int 62 | platform: str 63 | 64 | 65 | class Event(BaseEvent): 66 | """ 67 | mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 `mirai-api-http 事件类型`_ 68 | 69 | .. _mirai-api-http 事件类型: 70 | https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md 71 | """ 72 | self_id: int 73 | type: str 74 | 75 | @classmethod 76 | def new(cls, data: Dict[str, Any]) -> "Event": 77 | """ 78 | 此事件类的工厂函数, 能够通过事件数据选择合适的子类进行序列化 79 | """ 80 | type = data['type'] 81 | 82 | def all_subclasses(cls: Type[Event]): 83 | return set(cls.__subclasses__()).union( 84 | [s for c in cls.__subclasses__() for s in all_subclasses(c)]) 85 | 86 | event_class: Optional[Type[Event]] = None 87 | for subclass in all_subclasses(cls): 88 | if subclass.__name__ != type: 89 | continue 90 | event_class = subclass 91 | 92 | if event_class is None: 93 | return Event.parse_obj(data) 94 | 95 | while event_class and issubclass(event_class, Event): 96 | try: 97 | return event_class.parse_obj(data) 98 | except ValidationError as e: 99 | log.info( 100 | f'Failed to parse {data} to class {event_class.__name__}: ' 101 | f'{e.errors()!r}. Fallback to parent class.') 102 | event_class = event_class.__base__ # type: ignore 103 | 104 | raise ValueError(f'Failed to serialize {data}.') 105 | 106 | @overrides(BaseEvent) 107 | def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: # noqa 108 | raise ValueError("Event has no message!") 109 | 110 | @overrides(BaseEvent) 111 | def get_event_name(self) -> str: 112 | return self.type 113 | 114 | @overrides(BaseEvent) 115 | def get_event_description(self) -> str: 116 | return escape_tag(str(self.normalize_dict())) 117 | 118 | @overrides(BaseEvent) 119 | def get_message(self) -> BaseMessage: 120 | raise ValueError("Event has no message!") 121 | 122 | @overrides(BaseEvent) 123 | def get_plaintext(self) -> str: 124 | raise ValueError("Event has no message!") 125 | 126 | @overrides(BaseEvent) 127 | def get_user_id(self) -> str: 128 | raise ValueError("Event has no message!") 129 | 130 | @overrides(BaseEvent) 131 | def get_session_id(self) -> str: 132 | raise ValueError("Event has no message!") 133 | 134 | @overrides(BaseEvent) 135 | def is_tome(self) -> bool: 136 | return False 137 | 138 | def normalize_dict(self, **kwargs) -> Dict[str, Any]: 139 | """ 140 | 返回可以被json正常反序列化的结构体 141 | """ 142 | return json.loads(self.json(**kwargs)) 143 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/event/message.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from pydantic import BaseModel, Field 3 | from typing import Any, Literal, Optional 4 | 5 | from nonebot.typing import overrides 6 | 7 | from ..message import MessageChain 8 | from .base import ( 9 | Event, 10 | GroupChatInfo, 11 | GroupInfo, 12 | OtherChatInfo, 13 | PrivateChatInfo, 14 | StrangerChatInfo 15 | ) 16 | 17 | 18 | class MessageSource(BaseModel): 19 | id: int 20 | time: datetime 21 | 22 | 23 | class MessageQuote(BaseModel): 24 | _type: str = Field(..., alias="type") 25 | id: int 26 | sender_id: int = Field(..., alias="senderId") 27 | target_id: int = Field(..., alias="targetId") 28 | group_id: int = Field(None, alias="groupId") 29 | origin: MessageChain 30 | 31 | 32 | class MessageEvent(Event): 33 | """消息事件基类""" 34 | message_chain: MessageChain = Field(alias='messageChain') 35 | source: Optional[MessageSource] = None 36 | sender: Any 37 | quote: Optional[MessageQuote] = None 38 | 39 | @overrides(Event) 40 | def get_type(self) -> Literal["message"]: # noqa 41 | return 'message' 42 | 43 | @overrides(Event) 44 | def get_message(self) -> MessageChain: 45 | return self.message_chain 46 | 47 | @overrides(Event) 48 | def get_plaintext(self) -> str: 49 | return self.message_chain.extract_plain_text() 50 | 51 | @overrides(Event) 52 | def get_user_id(self) -> str: 53 | raise NotImplementedError 54 | 55 | @overrides(Event) 56 | def get_session_id(self) -> str: 57 | raise NotImplementedError 58 | 59 | 60 | class GroupMessage(MessageEvent): 61 | """群消息事件""" 62 | sender: GroupChatInfo 63 | to_me: bool = False 64 | 65 | @overrides(MessageEvent) 66 | def get_session_id(self) -> str: 67 | return f'group_{self.sender.group.id}_{self.sender.id}' 68 | 69 | @overrides(MessageEvent) 70 | def get_user_id(self) -> str: 71 | return str(self.sender.id) 72 | 73 | @overrides(MessageEvent) 74 | def is_tome(self) -> bool: 75 | return self.to_me 76 | 77 | 78 | class GroupSyncMessage(MessageEvent): 79 | """同步群消息事件""" 80 | sender: GroupInfo = Field(alias="subject") 81 | to_me: bool = False 82 | self_id: int 83 | 84 | @overrides(MessageEvent) 85 | def get_session_id(self) -> str: 86 | return f'groupSync_{self.sender.id}_{self.self_id}' 87 | 88 | @overrides(MessageEvent) 89 | def get_user_id(self) -> str: 90 | return str(self.self_id) 91 | 92 | @overrides(MessageEvent) 93 | def is_tome(self) -> bool: 94 | return self.to_me 95 | 96 | 97 | class FriendMessage(MessageEvent): 98 | """好友消息事件""" 99 | sender: PrivateChatInfo 100 | 101 | @overrides(MessageEvent) 102 | def get_user_id(self) -> str: 103 | return str(self.sender.id) 104 | 105 | @overrides(MessageEvent) 106 | def get_session_id(self) -> str: 107 | return f'friend_{self.sender.id}' 108 | 109 | @overrides(MessageEvent) 110 | def is_tome(self) -> bool: 111 | return True 112 | 113 | 114 | class FriendSyncMessage(MessageEvent): 115 | """同步好友消息事件""" 116 | sender: PrivateChatInfo = Field(alias="subject") 117 | 118 | @overrides(MessageEvent) 119 | def get_user_id(self) -> str: 120 | return str(self.sender.id) 121 | 122 | @overrides(MessageEvent) 123 | def get_session_id(self) -> str: 124 | return f'friendSync_{self.sender.id}' 125 | 126 | @overrides(MessageEvent) 127 | def is_tome(self) -> bool: 128 | return True 129 | 130 | 131 | class TempMessage(MessageEvent): 132 | """临时会话消息事件""" 133 | sender: GroupChatInfo 134 | 135 | @overrides(MessageEvent) 136 | def get_user_id(self) -> str: 137 | return str(self.sender.id) 138 | 139 | @overrides(MessageEvent) 140 | def get_session_id(self) -> str: 141 | return f'temp_{self.sender.group.id}_{self.sender.id}' 142 | 143 | @overrides(MessageEvent) 144 | def is_tome(self) -> bool: 145 | return True 146 | 147 | 148 | class TempSyncMessage(MessageEvent): 149 | """同步临时会话消息事件""" 150 | sender: GroupChatInfo = Field(alias="subject") 151 | 152 | @overrides(MessageEvent) 153 | def get_user_id(self) -> str: 154 | return str(self.sender.id) 155 | 156 | @overrides(MessageEvent) 157 | def get_session_id(self) -> str: 158 | return f'tempSync_{self.sender.group.id}_{self.sender.id}' 159 | 160 | @overrides(MessageEvent) 161 | def is_tome(self) -> bool: 162 | return True 163 | 164 | 165 | class StrangerMessage(MessageEvent): 166 | """陌生人消息事件""" 167 | sender: StrangerChatInfo 168 | 169 | @overrides(MessageEvent) 170 | def get_user_id(self) -> str: 171 | return str(self.sender.id) 172 | 173 | @overrides(MessageEvent) 174 | def get_session_id(self) -> str: 175 | return f'stranger_{self.sender.id}' 176 | 177 | 178 | class StrangerSyncMessage(MessageEvent): 179 | """同步陌生人消息事件""" 180 | subject: StrangerChatInfo = Field(alias="subject") 181 | self_id: int 182 | 183 | @overrides(MessageEvent) 184 | def get_user_id(self) -> str: 185 | return str(self.self_id) 186 | 187 | @overrides(MessageEvent) 188 | def get_session_id(self) -> str: 189 | return f'strangerSync_{self.self_id}' 190 | 191 | 192 | class OtherClientMessage(MessageEvent): 193 | """其他客户端消息事件""" 194 | sender: OtherChatInfo 195 | 196 | @overrides(MessageEvent) 197 | def get_user_id(self) -> str: 198 | return str(self.sender.id) 199 | 200 | @overrides(MessageEvent) 201 | def get_session_id(self) -> str: 202 | return f'other_{self.sender.id}' 203 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/event/meta.py: -------------------------------------------------------------------------------- 1 | from .base import Event 2 | from typing import Literal 3 | from nonebot.typing import overrides 4 | 5 | 6 | class MetaEvent(Event): 7 | """元事件基类""" 8 | qq: int 9 | 10 | @overrides(Event) 11 | def get_type(self) -> Literal["meta_event"]: # noqa 12 | return 'meta_event' 13 | 14 | 15 | class BotOnlineEvent(MetaEvent): 16 | """Bot登录成功""" 17 | pass 18 | 19 | 20 | class BotOfflineEventActive(MetaEvent): 21 | """Bot主动离线""" 22 | pass 23 | 24 | 25 | class BotOfflineEventForce(MetaEvent): 26 | """Bot被挤下线""" 27 | pass 28 | 29 | 30 | class BotOfflineEventDropped(MetaEvent): 31 | """Bot被服务器断开或因网络问题而掉线""" 32 | pass 33 | 34 | 35 | class BotReloginEvent(MetaEvent): 36 | """Bot主动重新登录""" 37 | pass 38 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/event/notice.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from nonebot.typing import overrides 3 | from pydantic import BaseModel, Field 4 | from typing import Any, Literal, Optional 5 | 6 | from .base import Event, GroupChatInfo, GroupInfo, UserPermission 7 | from .message import MessageChain 8 | 9 | 10 | class NoticeEvent(Event): 11 | """通知事件基类""" 12 | @overrides(Event) 13 | def get_type(self) -> Literal["notice"]: # noqa 14 | return 'notice' 15 | 16 | 17 | class MuteEvent(NoticeEvent): 18 | """禁言类事件基类""" 19 | operator: GroupChatInfo 20 | 21 | 22 | class BotMuteEvent(MuteEvent): 23 | """Bot被禁言""" 24 | duration_seconds: int = Field(alias='durationSeconds') 25 | 26 | 27 | class BotUnmuteEvent(MuteEvent): 28 | """Bot被取消禁言""" 29 | pass 30 | 31 | 32 | class MemberMuteEvent(MuteEvent): 33 | """群成员被禁言事件(该成员不是Bot)""" 34 | duration_seconds: int = Field(alias='durationSeconds') 35 | member: GroupChatInfo 36 | operator: Optional[GroupChatInfo] = None 37 | 38 | 39 | class MemberUnmuteEvent(MuteEvent): 40 | """群成员被取消禁言事件(该成员不是Bot)""" 41 | member: GroupChatInfo 42 | operator: Optional[GroupChatInfo] = None 43 | 44 | 45 | class BotJoinGroupEvent(NoticeEvent): 46 | """Bot加入了一个新群""" 47 | group: GroupInfo 48 | invitor: Optional[GroupChatInfo] 49 | 50 | 51 | class BotLeaveEventActive(NoticeEvent): 52 | """Bot主动退出一个群""" 53 | group: GroupInfo 54 | 55 | 56 | class BotLeaveEventKick(NoticeEvent): 57 | """Bot被踢出一个群""" 58 | group: GroupInfo 59 | operator: Optional[GroupChatInfo] 60 | 61 | 62 | class BotLeaveEventDisband(NoticeEvent): 63 | """Bot因群主解散群而退出群""" 64 | group: GroupInfo 65 | operator: Optional[GroupChatInfo] 66 | 67 | 68 | class MemberJoinEvent(NoticeEvent): 69 | """新人入群的事件""" 70 | member: GroupChatInfo 71 | invitor: Optional[GroupChatInfo] 72 | 73 | 74 | class MemberLeaveEventKick(NoticeEvent): 75 | """成员被踢出群(该成员不是Bot)""" 76 | member: GroupChatInfo 77 | operator: Optional[GroupChatInfo] = None 78 | 79 | 80 | class MemberLeaveEventQuit(NoticeEvent): 81 | """成员主动离群(该成员不是Bot)""" 82 | member: GroupChatInfo 83 | 84 | 85 | class GroupRecallEvent(NoticeEvent): 86 | """群消息撤回""" 87 | author_id: int = Field(alias='authorId') 88 | message_id: int = Field(alias='messageId') 89 | time: int 90 | group: GroupInfo 91 | operator: Optional[GroupChatInfo] = None 92 | 93 | 94 | class FriendRecallEvent(NoticeEvent): 95 | """好友消息撤回""" 96 | author_id: int = Field(alias='authorId') 97 | message_id: int = Field(alias='messageId') 98 | time: int 99 | operator: int 100 | 101 | 102 | class GroupStateChangeEvent(NoticeEvent): 103 | """群变化事件基类""" 104 | origin: Any 105 | current: Any 106 | group: GroupInfo 107 | operator: Optional[GroupChatInfo] = None 108 | 109 | 110 | class GroupNameChangeEvent(GroupStateChangeEvent): 111 | """某个群名改变""" 112 | origin: str 113 | current: str 114 | 115 | 116 | class GroupEntranceAnnouncementChangeEvent(GroupStateChangeEvent): 117 | """某群入群公告改变""" 118 | origin: str 119 | current: str 120 | 121 | 122 | class GroupMuteAllEvent(GroupStateChangeEvent): 123 | """全员禁言""" 124 | origin: bool 125 | current: bool 126 | 127 | 128 | class GroupAllowAnonymousChatEvent(GroupStateChangeEvent): 129 | """匿名聊天""" 130 | origin: bool 131 | current: bool 132 | 133 | 134 | class GroupAllowConfessTalkEvent(GroupStateChangeEvent): 135 | """坦白说""" 136 | origin: bool 137 | current: bool 138 | is_bot: bool = Field(alias='isByBot') 139 | 140 | 141 | class GroupAllowMemberInviteEvent(GroupStateChangeEvent): 142 | """允许群员邀请好友加群""" 143 | origin: bool 144 | current: bool 145 | 146 | 147 | class MemberStateChangeEvent(NoticeEvent): 148 | """群成员变化事件基类""" 149 | member: GroupChatInfo 150 | operator: Optional[GroupChatInfo] = None 151 | 152 | 153 | class MemberCardChangeEvent(MemberStateChangeEvent): 154 | """群名片改动""" 155 | origin: str 156 | current: str 157 | 158 | 159 | class MemberSpecialTitleChangeEvent(MemberStateChangeEvent): 160 | """群头衔改动(只有群主有操作限权)""" 161 | origin: str 162 | current: str 163 | 164 | 165 | class BotGroupPermissionChangeEvent(MemberStateChangeEvent): 166 | """Bot在群里的权限被改变""" 167 | origin: UserPermission 168 | current: UserPermission 169 | group: GroupInfo 170 | 171 | 172 | class MemberPermissionChangeEvent(MemberStateChangeEvent): 173 | """成员权限改变的事件(该成员不是Bot)""" 174 | origin: UserPermission 175 | current: UserPermission 176 | 177 | 178 | 179 | class NudgeSubjectKind(Enum): 180 | GROUP = "Group" 181 | FRIEND = "Friend" 182 | 183 | 184 | class NudgeSubject(BaseModel): 185 | id: int 186 | kind: NudgeSubjectKind 187 | suffix: str 188 | 189 | 190 | class NudgeEvent(NoticeEvent): 191 | """戳一戳事件""" 192 | from_id: int = Field(alias="FromId") 193 | target: int 194 | action: str 195 | subject: NudgeSubject 196 | suffix: str 197 | 198 | 199 | class friend(BaseModel): 200 | id: int 201 | nickname: str 202 | remark: str 203 | 204 | 205 | class FriendInputStatusChangedEvent(NoticeEvent): 206 | """好友输入状态改变事件""" 207 | friend: friend 208 | inputting: bool 209 | 210 | 211 | class FriendNickChangedEvent(NoticeEvent): 212 | """好友昵称改变事件""" 213 | friend: friend 214 | from_name: str 215 | new_name: str 216 | 217 | 218 | class action(Enum): 219 | ACHIEVE = "achieve" 220 | LOSE = "lose" 221 | 222 | 223 | class MemberHonorChangeEvent(NoticeEvent): 224 | """群员称号改变""" 225 | member: GroupChatInfo 226 | action: action 227 | honor: str 228 | 229 | 230 | class client(BaseModel): 231 | id: int 232 | platform: str 233 | kind: int 234 | 235 | 236 | class OtherClientOnlineEvent(NoticeEvent): 237 | """其他客户端上线""" 238 | client: client 239 | 240 | 241 | class OtherClientOfflineEvent(NoticeEvent): 242 | """其他客户端下线""" 243 | client: client 244 | 245 | 246 | class CommandExecutedEvent(NoticeEvent): 247 | """命令被执行""" 248 | name: str 249 | friend: Optional[friend] 250 | member: Optional[GroupChatInfo] 251 | args: MessageChain 252 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/event/request.py: -------------------------------------------------------------------------------- 1 | from typing import TYPE_CHECKING 2 | from pydantic import Field 3 | from typing_extensions import Literal 4 | from nonebot.typing import overrides 5 | 6 | from .base import Event 7 | 8 | if TYPE_CHECKING: 9 | from ..bot import Bot 10 | 11 | 12 | class RequestEvent(Event): 13 | """请求事件基类""" 14 | event_id: int = Field(alias='eventId') 15 | message: str 16 | nick: str 17 | 18 | @overrides(Event) 19 | def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: # noqa 20 | return 'request' 21 | 22 | 23 | class NewFriendRequestEvent(RequestEvent): 24 | """添加好友申请""" 25 | from_id: int = Field(alias='fromId') 26 | group_id: int = Field(0, alias='groupId') 27 | 28 | async def approve(self, bot: "Bot"): 29 | """ 30 | :说明: 31 | 32 | 通过此人的好友申请 33 | 34 | :参数: 35 | 36 | * ``bot: Bot``: 当前的 ``Bot`` 对象 37 | """ 38 | return await bot.resp_newFriendRequestEvent( 39 | event_id=self.event_id, 40 | group_id=self.group_id, 41 | from_id=self.from_id, 42 | operate=0, 43 | message='' 44 | ) 45 | 46 | async def reject(self, 47 | bot: "Bot", 48 | operate: Literal[1, 2] = 1, 49 | message: str = ''): 50 | """ 51 | :说明: 52 | 53 | 拒绝此人的好友申请 54 | 55 | :参数: 56 | 57 | * ``bot: Bot``: 当前的 ``Bot`` 对象 58 | * ``operate: Literal[1, 2]``: 响应的操作类型 59 | 60 | * ``1``: 拒绝添加好友 61 | * ``2``: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 62 | 63 | * ``message: str``: 回复的信息 64 | """ 65 | assert operate > 0 66 | return await bot.resp_newFriendRequestEvent( 67 | event_id=self.event_id, 68 | group_id=self.group_id, 69 | from_id=self.from_id, 70 | operate=operate, 71 | message=message 72 | ) 73 | 74 | 75 | class MemberJoinRequestEvent(RequestEvent): 76 | """用户入群申请(Bot需要有管理员权限)""" 77 | from_id: int = Field(alias='fromId') 78 | group_id: int = Field(alias='groupId') 79 | group_name: str = Field(alias='groupName') 80 | 81 | async def approve(self, bot: "Bot"): 82 | """ 83 | :说明: 84 | 85 | 通过此人的加群申请 86 | 87 | :参数: 88 | 89 | * ``bot: Bot``: 当前的 ``Bot`` 对象 90 | """ 91 | return await bot.resp_memberJoinRequestEvent( 92 | event_id=self.event_id, 93 | group_id=self.group_id, 94 | from_id=self.from_id, 95 | operate=0, 96 | message='' 97 | ) 98 | 99 | async def reject(self, 100 | bot: "Bot", 101 | operate: Literal[1, 2, 3, 4] = 1, 102 | message: str = ''): 103 | """ 104 | :说明: 105 | 106 | 拒绝(忽略)此人的加群申请 107 | 108 | :参数: 109 | 110 | * ``bot: Bot``: 当前的 ``Bot`` 对象 111 | * ``operate: Literal[1, 2, 3, 4]``: 响应的操作类型 112 | 113 | * ``1``: 拒绝入群 114 | * ``2``: 忽略请求 115 | * ``3``: 拒绝入群并添加黑名单,不再接收该用户的入群申请 116 | * ``4``: 忽略入群并添加黑名单,不再接收该用户的入群申请 117 | 118 | * ``message: str``: 回复的信息 119 | """ 120 | assert operate > 0 121 | return await bot.resp_memberJoinRequestEvent( 122 | event_id=self.event_id, 123 | group_id=self.group_id, 124 | from_id=self.from_id, 125 | operate=operate, 126 | message=message 127 | ) 128 | 129 | 130 | class BotInvitedJoinGroupRequestEvent(RequestEvent): 131 | """Bot被邀请入群申请""" 132 | from_id: int = Field(alias='fromId') 133 | group_id: int = Field(alias='groupId') 134 | group_name: str = Field(alias='groupName') 135 | 136 | async def approve(self, bot: "Bot"): 137 | """ 138 | :说明: 139 | 140 | 通过这份被邀请入群申请 141 | 142 | :参数: 143 | 144 | * ``bot: Bot``: 当前的 ``Bot`` 对象 145 | """ 146 | return await bot.resp_botInvitedJoinGroupRequestEvent( 147 | event_id=self.event_id, 148 | group_id=self.group_id, 149 | from_id=self.from_id, 150 | operate=0, 151 | message='' 152 | ) 153 | 154 | async def reject(self, bot: "Bot", message: str = ""): 155 | """ 156 | :说明: 157 | 158 | 拒绝这份被邀请入群申请 159 | 160 | :参数: 161 | 162 | * ``bot: Bot``: 当前的 ``Bot`` 对象 163 | * ``message: str``: 邀请消息 164 | """ 165 | return await bot.resp_botInvitedJoinGroupRequestEvent( 166 | event_id=self.event_id, 167 | group_id=self.group_id, 168 | from_id=self.from_id, 169 | operate=1, 170 | message=message 171 | ) 172 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/exception.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from nonebot.exception import ActionFailed as BaseActionFailed 3 | from nonebot.exception import AdapterException 4 | from nonebot.exception import ApiNotAvailable as BaseApiNotAvailable 5 | from nonebot.exception import NetworkError as BaseNetworkError 6 | 7 | 8 | class MiraiAdapterException(AdapterException): 9 | 10 | def __init__(self, *args): 11 | super().__init__('mirai', *args) 12 | 13 | 14 | class ActionFailed(BaseActionFailed, MiraiAdapterException): 15 | 16 | def __init__(self, **kwargs): 17 | super().__init__() 18 | self.info = kwargs 19 | 20 | def __repr__(self): 21 | return f"" 23 | 24 | def __str__(self): 25 | return self.__repr__() 26 | 27 | 28 | class NetworkError(BaseNetworkError, MiraiAdapterException): 29 | 30 | def __init__(self, msg: Optional[str] = None): 31 | super().__init__() 32 | self.msg = msg 33 | 34 | def __repr__(self): 35 | return f"" 36 | 37 | def __str__(self): 38 | return self.__repr__() 39 | 40 | 41 | class ApiNotAvailable(BaseApiNotAvailable, MiraiAdapterException): 42 | pass 43 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/log.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from nonebot.utils import logger_wrapper 3 | 4 | log = logger_wrapper("mirai2") 5 | 6 | 7 | def info(message: str, exception: Optional[Exception] = None): 8 | log("INFO", message=message, exception=exception) 9 | 10 | 11 | def warning(message: str, exception: Optional[Exception] = None): 12 | log("WARNING", message=message, exception=exception) 13 | 14 | 15 | def warn(message: str, exception: Optional[Exception] = None): 16 | log("WARNING", message=message, exception=exception) 17 | 18 | 19 | def debug(message: str, exception: Optional[Exception] = None): 20 | log("DEBUG", message=message, exception=exception) 21 | 22 | 23 | def error(message: str, exception: Optional[Exception] = None): 24 | log("ERROR", message=message, exception=exception) 25 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/message.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import Any, List, Dict, Type, Iterable, Optional, Union 3 | 4 | from pydantic import validate_arguments 5 | 6 | from nonebot.adapters import Message as BaseMessage 7 | from nonebot.adapters import MessageSegment as BaseMessageSegment 8 | from nonebot.typing import overrides 9 | 10 | 11 | class MessageType(str, Enum): 12 | """消息类型枚举类""" 13 | SOURCE = 'Source' 14 | QUOTE = 'Quote' 15 | AT = 'At' 16 | AT_ALL = 'AtAll' 17 | FACE = 'Face' 18 | PLAIN = 'Plain' 19 | IMAGE = 'Image' 20 | FLASH_IMAGE = 'FlashImage' 21 | VOICE = 'Voice' 22 | XML = 'Xml' 23 | JSON = 'Json' 24 | APP = 'App' 25 | DICE = 'Dice' 26 | POKE = 'Poke' 27 | MARKET_FACE = 'MarketFace' 28 | MUSIC_SHARE = 'MusicShare' 29 | FORWARD = 'Forward' 30 | FILE = 'File' 31 | MIRAI_CODE = 'MiraiCode' 32 | 33 | 34 | class MessageSegment(BaseMessageSegment["MessageChain"]): 35 | """ 36 | Mirai-API-HTTP 协议 MessageSegment 适配。具体方法参考 `mirai-api-http 消息类型`_ 37 | 38 | .. _mirai-api-http 消息类型: 39 | https://github.com/project-mirai/mirai-api-http/blob/master/docs/MessageType.md 40 | """ 41 | 42 | type: MessageType 43 | data: Dict[str, Any] 44 | 45 | @classmethod 46 | def get_message_class(cls) -> Type["MessageChain"]: 47 | return MessageChain 48 | 49 | @validate_arguments 50 | @overrides(BaseMessageSegment) 51 | def __init__(self, type: MessageType, **data: Any): 52 | super().__init__(type=type, 53 | data={k: v for k, v in data.items() if v is not None}) 54 | 55 | @overrides(BaseMessageSegment) 56 | def __str__(self) -> str: 57 | return self.data.get('text', "") if self.is_text() else repr(self) 58 | 59 | def __repr__(self) -> str: 60 | return '[mirai:%s]' % ','.join([ 61 | self.type.value, 62 | *map( 63 | lambda s: '%s=%r' % s, 64 | self.data.items(), 65 | ), 66 | ]) 67 | 68 | @classmethod 69 | def _validate(cls, value): 70 | if isinstance(value, cls): 71 | return value 72 | if not isinstance(value, dict): 73 | raise ValueError(f"Expected dict for MessageSegment, got {type(value)}") 74 | if "type" not in value: 75 | raise ValueError( 76 | f"Expected dict with 'type' for MessageSegment, got {value}" 77 | ) 78 | return cls(**value) 79 | 80 | @overrides(BaseMessageSegment) 81 | def is_text(self) -> bool: 82 | return self.type == MessageType.PLAIN 83 | 84 | def as_dict(self) -> Dict[str, Any]: 85 | """导出可以被正常json序列化的结构体""" 86 | return {'type': self.type.value, **self.data} 87 | 88 | @classmethod 89 | def source(cls, id: int, time: int): 90 | return cls(type=MessageType.SOURCE, id=id, time=time) 91 | 92 | @classmethod 93 | def quote(cls, id: int, group_id: int, sender_id: int, target_id: int, 94 | origin: "MessageChain"): 95 | """ 96 | :说明: 97 | 98 | 生成回复引用消息段 99 | 100 | :参数: 101 | 102 | * ``id: int``: 被引用回复的原消息的message_id 103 | * ``group_id: int``: 被引用回复的原消息所接收的群号,当为好友消息时为0 104 | * ``sender_id: int``: 被引用回复的原消息的发送者的QQ号 105 | * ``target_id: int``: 被引用回复的原消息的接收者者的QQ号(或群号) 106 | * ``origin: MessageChain``: 被引用回复的原消息的消息链对象 107 | """ 108 | return cls(type=MessageType.QUOTE, 109 | id=id, 110 | groupId=group_id, 111 | senderId=sender_id, 112 | targetId=target_id, 113 | origin=origin.export()) 114 | 115 | @classmethod 116 | def at(cls, target: int): 117 | """ 118 | :说明: 119 | 120 | @某个人 121 | 122 | :参数: 123 | 124 | * ``target: int``: 群员QQ号 125 | """ 126 | return cls(type=MessageType.AT, target=target) 127 | 128 | @classmethod 129 | def at_all(cls): 130 | """ 131 | :说明: 132 | 133 | @全体成员 134 | """ 135 | return cls(type=MessageType.AT_ALL) 136 | 137 | @classmethod 138 | def face(cls, face_id: Optional[int] = None, name: Optional[str] = None): 139 | """ 140 | :说明: 141 | 142 | 发送QQ表情 143 | 144 | :参数: 145 | 146 | * ``face_id: Optional[int]``: QQ表情编号,可选,优先高于name 147 | * ``name: Optional[str]``: QQ表情拼音,可选 148 | """ 149 | return cls(type=MessageType.FACE, faceId=face_id, name=name) 150 | 151 | @classmethod 152 | def plain(cls, text: str): 153 | """ 154 | :说明: 155 | 156 | 纯文本消息 157 | 158 | :参数: 159 | 160 | * ``text: str``: 文字消息 161 | """ 162 | return cls(type=MessageType.PLAIN, text=text) 163 | 164 | @classmethod 165 | def image(cls, 166 | image_id: Optional[str] = None, 167 | url: Optional[str] = None, 168 | path: Optional[str] = None, 169 | base64: Optional[str] = None): 170 | """ 171 | :说明: 172 | 173 | 图片消息 174 | 175 | :参数: 176 | 177 | * ``image_id: Optional[str]``: 图片的image_id,群图片与好友图片格式不同。不为空时将忽略url属性 178 | * ``url: Optional[str]``: 图片的URL,发送时可作网络图片的链接 179 | * ``path: Optional[str]``: 图片的路径,发送本地图片 180 | """ 181 | return cls(type=MessageType.IMAGE, imageId=image_id, url=url, path=path, base64=base64) 182 | 183 | @classmethod 184 | def flash_image(cls, 185 | image_id: Optional[str] = None, 186 | url: Optional[str] = None, 187 | path: Optional[str] = None): 188 | """ 189 | :说明: 190 | 191 | 闪照消息 192 | 193 | :参数: 194 | 195 | 同 ``image`` 196 | """ 197 | return cls(type=MessageType.FLASH_IMAGE, 198 | imageId=image_id, 199 | url=url, 200 | path=path) 201 | 202 | @classmethod 203 | def voice(cls, 204 | voice_id: Optional[str] = None, 205 | url: Optional[str] = None, 206 | path: Optional[str] = None): 207 | """ 208 | :说明: 209 | 210 | 语音消息 211 | 212 | :参数: 213 | 214 | * ``voice_id: Optional[str]``: 语音的voice_id,不为空时将忽略url属性 215 | * ``url: Optional[str]``: 语音的URL,发送时可作网络语音的链接 216 | * ``path: Optional[str]``: 语音的路径,发送本地语音 217 | """ 218 | return cls(type=MessageType.VOICE, 219 | imageId=voice_id, 220 | url=url, 221 | path=path) 222 | 223 | @classmethod 224 | def xml(cls, xml: str): 225 | """ 226 | :说明: 227 | 228 | XML消息 229 | 230 | :参数: 231 | 232 | * ``xml: str``: XML文本 233 | """ 234 | return cls(type=MessageType.XML, xml=xml) 235 | 236 | @classmethod 237 | def json(cls, json: str): 238 | """ 239 | :说明: 240 | 241 | Json消息 242 | 243 | :参数: 244 | 245 | * ``json: str``: Json文本 246 | """ 247 | return cls(type=MessageType.JSON, json=json) 248 | 249 | @classmethod 250 | def app(cls, content: str): 251 | """ 252 | :说明: 253 | 254 | 应用程序消息 255 | 256 | :参数: 257 | 258 | * ``content: str``: 内容 259 | """ 260 | return cls(type=MessageType.APP, content=content) 261 | 262 | @classmethod 263 | def Dice(cls, value: int): 264 | """ 265 | :说明: 266 | 267 | 掷骰子消息 268 | 269 | :参数: 270 | 271 | * ``value: int``: 骰子的值 272 | 273 | """ 274 | return cls(type=MessageType.DICE, value=value) 275 | 276 | @classmethod 277 | def poke(cls, name: str): 278 | """ 279 | :说明: 280 | 281 | 戳一戳消息 282 | 283 | :参数: 284 | 285 | * ``name: str``: 戳一戳的类型 286 | 287 | * ``Poke``: 戳一戳 288 | * ``ShowLove``: 比心 289 | * ``Like``: 点赞 290 | * ``Heartbroken``: 心碎 291 | * ``SixSixSix``: 666 292 | * ``FangDaZhao``: 放大招 293 | 294 | """ 295 | return cls(type=MessageType.POKE, name=name) 296 | 297 | @classmethod 298 | def market_face( 299 | cls, id: int, name: str 300 | ): 301 | """ 302 | :说明: 303 | 304 | 商城表情 305 | 306 | :参数: 307 | 308 | * ``id: int`` 商城表情唯一标识 309 | * ``name: str`` 表情显示名称 310 | """ 311 | return cls(type=MessageType.MARKET_FACE, id=id, name=name) 312 | 313 | @classmethod 314 | def music_share(cls, kind: str, title: str, summary: str, jump_url: str, picture_url: str, music_url: str, brief: str): 315 | """ 316 | :说明: 317 | 318 | 音乐卡片消息 319 | 320 | :参数: 321 | 322 | * ``kind: str``: 卡片类型 323 | * ``title: str``: 标题 324 | * ``summary: str``: 摘要 325 | * ``jump_url: str``: 跳转链接 326 | * ``picture_url: str``: 图片链接 327 | * ``music_url: str``: 音乐链接 328 | * ``brief: str``: 简介 329 | """ 330 | return cls(type=MessageType.MUSIC_SHARE, kind=kind, title=title, summary=summary, jumpUrl=jump_url, pictureUrl=picture_url, musicUrl=music_url, brief=brief) 331 | 332 | @classmethod 333 | def forward(cls, node_list: dict, senderld: int, time: int, sender_name: str, message_chain: "MessageChain", messageid: int): 334 | """ 335 | :说明: 336 | 337 | 转发消息 338 | 339 | :参数: 340 | 341 | * ``node_list: dict``: 节点列表 342 | * ``senderld: int``: 发送者的ld 343 | * ``time: int``: 时间戳 344 | * ``sender_name: str``: 发送者的名字 345 | * ``message_chain: MessageChain``: 消息链 346 | * ``messageid: int``: 消息id 347 | """ 348 | return cls(type=MessageType.FORWARD, nodeList=node_list, senderLd=senderld, time=time, senderName=sender_name, messageChain=message_chain, messageId=messageid) 349 | 350 | @classmethod 351 | def file(cls, id: str, name: str, size: int): 352 | """ 353 | :说明: 354 | 355 | 文件消息 356 | 357 | :参数: 358 | 359 | * ``id: str``: 文件的id 360 | * ``name: str``: 文件的名字 361 | * ``size: int``: 文件的大小 362 | """ 363 | return cls(type=MessageType.FILE, id=id, name=name, size=size) 364 | 365 | @classmethod 366 | def mirai_code(cls, code: str): 367 | """ 368 | :说明: 369 | 370 | Mirai-Code消息 371 | 372 | :参数: 373 | 374 | * ``code: str``: Mirai-Code 375 | """ 376 | return cls(type=MessageType.MIRAI_CODE, code=code) 377 | 378 | 379 | class MessageChain(BaseMessage[MessageSegment]): 380 | """ 381 | Mirai 协议 Message 适配 382 | 383 | 由于Mirai协议的Message实现较为特殊, 故使用MessageChain命名 384 | """ 385 | 386 | @classmethod 387 | @overrides(BaseMessage) 388 | def get_segment_class(cls) -> Type[MessageSegment]: 389 | return MessageSegment 390 | 391 | @overrides(BaseMessage) 392 | def __init__(self, message: Union[List[Dict[str, 393 | Any]], Iterable[MessageSegment], 394 | MessageSegment, str], **kwargs): 395 | super().__init__(**kwargs) 396 | if isinstance(message, MessageSegment): 397 | self.append(message) 398 | elif isinstance(message, str): 399 | self.append(MessageSegment.plain(text=message)) 400 | elif isinstance(message, Iterable): 401 | self.extend(self._construct(message)) 402 | else: 403 | raise ValueError( 404 | f'Type {type(message).__name__} is not supported in mirai adapter.' 405 | ) 406 | 407 | @overrides(BaseMessage) 408 | def _construct( 409 | self, message: Union[List[Dict[str, Any]], Iterable[MessageSegment]] 410 | ) -> List[MessageSegment]: 411 | if isinstance(message, str): 412 | return [MessageSegment.plain(text=message)] 413 | return [ 414 | *map( 415 | lambda x: x 416 | if isinstance(x, MessageSegment) else MessageSegment(**x), 417 | message) 418 | ] 419 | 420 | def export(self) -> List[Dict[str, Any]]: 421 | """导出为可以被正常json序列化的数组""" 422 | return [ 423 | *map(lambda segment: segment.as_dict(), self.copy()) # type: ignore 424 | ] 425 | 426 | def extract_first(self, *type: MessageType) -> Optional[MessageSegment]: 427 | """ 428 | :说明: 429 | 430 | 弹出该消息链的第一个消息 431 | 432 | :参数: 433 | 434 | * `*type: MessageType`: 指定的消息类型, 当指定后如类型不匹配不弹出 435 | """ 436 | if not len(self): 437 | return None 438 | first: MessageSegment = self[0] 439 | if (not type) or (first.type in type): 440 | return self.pop(0) 441 | return None 442 | 443 | def __repr__(self) -> str: 444 | return f'<{self.__class__.__name__} {[*self.copy()]}>' 445 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/permission.py: -------------------------------------------------------------------------------- 1 | 2 | from nonebot.permission import Permission 3 | from nonebot.adapters import Bot, Event 4 | 5 | from .event.base import UserPermission 6 | from .event.message import GroupMessage 7 | 8 | 9 | async def _group_member(bot: "Bot", event: "Event") -> bool: 10 | return isinstance(event, GroupMessage) and \ 11 | event.sender.permission == UserPermission.MEMBER 12 | 13 | 14 | async def _group_admin(bot: "Bot", event: "Event") -> bool: 15 | return isinstance(event, GroupMessage) and \ 16 | event.sender.permission == UserPermission.ADMINISTRATOR 17 | 18 | 19 | async def _group_admins(bot: "Bot", event: "Event") -> bool: 20 | return isinstance(event, GroupMessage) and \ 21 | event.sender.permission in \ 22 | (UserPermission.ADMINISTRATOR, UserPermission.OWNER) 23 | 24 | 25 | async def _group_owner(bot: "Bot", event: "Event") -> bool: 26 | return isinstance(event, GroupMessage) and \ 27 | event.sender.permission == UserPermission.OWNER 28 | 29 | 30 | async def _group_owner_superuser(bot: "Bot", event: "Event") -> bool: 31 | return isinstance(event, GroupMessage) and \ 32 | (event.sender.permission == UserPermission.OWNER or 33 | event.get_user_id() in bot.config.superusers) 34 | 35 | 36 | GROUP_MEMBER = Permission(_group_member) # 仅成员 37 | GROUP_ADMIN = Permission(_group_admin) # 仅管理员 38 | GROUP_ADMINS = Permission(_group_admins) # 群主或管理员 39 | GROUP_OWNER = Permission(_group_owner) # 仅群主 40 | GROUP_OWNER_SUPERUSER = Permission(_group_owner_superuser) # 仅群主或超管 41 | from nonebot.permission import SUPERUSER # 仅超管 # noqa 42 | -------------------------------------------------------------------------------- /nonebot/adapters/mirai2/utils.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import re 3 | import sys 4 | from typing import TYPE_CHECKING, Any, Dict, Optional, Union 5 | 6 | from nonebot.message import handle_event 7 | from nonebot.typing import overrides 8 | from nonebot.utils import DataclassEncoder 9 | 10 | from .exception import ApiNotAvailable 11 | 12 | from .event import Event, GroupMessage, MessageEvent, MessageSource, MessageQuote 13 | from .message import MessageSegment, MessageType 14 | from . import log 15 | 16 | if TYPE_CHECKING: 17 | from .bot import Bot 18 | 19 | 20 | def snake_to_camel(name: str): 21 | for i in ['anno', 'resp']: 22 | if re.match(i, name): 23 | return name 24 | first, *rest = name.split('_') 25 | return ''.join([first.lower(), *(r.title() for r in rest)]) 26 | 27 | 28 | def process_source(bot: "Bot", event: MessageEvent) -> MessageEvent: 29 | source = event.message_chain.extract_first(MessageType.SOURCE) 30 | if source is not None: 31 | event.source = MessageSource.parse_obj(source.data) 32 | return event 33 | 34 | 35 | def process_quote(bot: "Bot", event: Union[MessageEvent, GroupMessage]) -> MessageEvent: 36 | quote = event.message_chain.extract_first(MessageType.QUOTE) 37 | if quote is not None: 38 | event.quote = MessageQuote.parse_obj(quote.data) 39 | if quote.data['senderId'] == event.self_id: 40 | event.to_me = True 41 | return event 42 | 43 | 44 | def process_at(bot: "Bot", event: GroupMessage) -> GroupMessage: 45 | c = 0 46 | for msg in event.message_chain: 47 | if (msg.type == MessageType.AT) and (msg.data.get('target', '') == event.self_id): 48 | event.to_me = True 49 | event.message_chain.pop(c) 50 | break 51 | c += 1 52 | if not event.message_chain: 53 | event.message_chain.append(MessageSegment.plain("")) 54 | return event 55 | 56 | 57 | def process_nick(bot: "Bot", event: GroupMessage) -> GroupMessage: 58 | plain = event.message_chain.extract_first(MessageType.PLAIN) 59 | if plain is not None: 60 | if len(bot.config.nickname): 61 | text = str(plain) 62 | nick_regex = '|'.join(filter(lambda x: x, bot.config.nickname)) 63 | matched = re.search(rf"^({nick_regex})([\s,,]*|$)", text, re.IGNORECASE) 64 | if matched is not None: 65 | event.to_me = True 66 | nickname = matched.group(1) 67 | log.info(f'User is calling me {nickname}') 68 | plain.data['text'] = text[matched.end():] 69 | event.message_chain.insert(0, plain) 70 | return event 71 | 72 | 73 | async def process_event(bot: "Bot", event: Event) -> None: 74 | if isinstance(event, MessageEvent): 75 | event = process_source(bot, event) 76 | event = process_quote(bot, event) 77 | if isinstance(event, GroupMessage): 78 | event = process_nick(bot, event) 79 | event = process_at(bot, event) 80 | await handle_event(bot, event) 81 | 82 | 83 | class SyncIDStore: 84 | _sync_id = 0 85 | _futures: Dict[str, asyncio.Future] = {} 86 | 87 | @classmethod 88 | def get_id(cls) -> str: 89 | sync_id = cls._sync_id 90 | cls._sync_id = (cls._sync_id + 1) % sys.maxsize 91 | return str(sync_id) 92 | 93 | @classmethod 94 | def add_response(cls, response: Dict[str, Any]): 95 | if not isinstance(response.get('syncId'), str): 96 | return 97 | sync_id: str = response['syncId'] 98 | if sync_id in cls._futures: 99 | cls._futures[sync_id].set_result(response) 100 | return sync_id 101 | 102 | @classmethod 103 | async def fetch_response(cls, sync_id: str, 104 | timeout: Optional[float]) -> Dict[str, Any]: 105 | future = asyncio.get_running_loop().create_future() 106 | cls._futures[sync_id] = future 107 | try: 108 | return await asyncio.wait_for(future, timeout) 109 | except asyncio.TimeoutError: 110 | raise ApiNotAvailable('timeout') from None 111 | finally: 112 | del cls._futures[sync_id] 113 | 114 | 115 | class MiraiDataclassEncoder(DataclassEncoder): 116 | 117 | @overrides(DataclassEncoder) 118 | def default(self, o): 119 | if isinstance(o, MessageSegment): 120 | return o.as_dict() 121 | return super().default(o) 122 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "nonebot_adapter_mirai2" 3 | version = "0.0.22" 4 | description = "兼容 MiraiApiHttp2.x 的 nonebot2_adapter" 5 | authors = ["ieew "] 6 | license = "AGPL-3.0" 7 | 8 | packages = [ 9 | { include = "nonebot" } 10 | ] 11 | 12 | [tool.poetry.dependencies] 13 | python = ">=3.8,<4.0.0" 14 | nonebot2 = "^2.0.0-beta.4" 15 | 16 | [tool.poetry.dev-dependencies] 17 | 18 | 19 | [build-system] 20 | requires = ["poetry-core>=1.0.0"] 21 | build-backend = "poetry.core.masonry.api" 22 | --------------------------------------------------------------------------------