├── .editorconfig ├── .gitignore ├── LICENSE ├── OneBot-CommandRoute ├── .gitignore ├── CommandRoute │ ├── Attributes │ │ ├── BeforeCommandAttribute.cs │ │ ├── CQJsonAttribute.cs │ │ ├── CommandAttribute.cs │ │ ├── CommandParameterAttribute.cs │ │ └── ParsedArgumentsAttribute.cs │ ├── Command │ │ └── MatchingNode.cs │ ├── Configuration │ │ ├── DefaultOneBotCommandRouteConfiguration.cs │ │ └── IOneBotCommandRouteConfiguration.cs │ ├── Events │ │ ├── EventHandleException.cs │ │ └── EventManager.cs │ ├── Lexer │ │ ├── CommandLexer.cs │ │ └── ParseToTheEndException.cs │ ├── Mixin │ │ └── StartupMixin.cs │ ├── Models │ │ ├── Entities │ │ │ ├── CQJsonRouteModel.cs │ │ │ ├── CommandModel.cs │ │ │ └── OneBotContextDefault.cs │ │ ├── Enumeration │ │ │ └── EventType.cs │ │ ├── OneBotContext.cs │ │ └── VO │ │ │ └── CQHttpServerConfigModel.cs │ ├── OneBotControllers │ │ └── CQJsonRouterController.cs │ ├── Services │ │ ├── IBotService.cs │ │ ├── ICQJsonRouterService.cs │ │ ├── ICommandService.cs │ │ ├── IEventService.cs │ │ ├── IOneBotContextHolder.cs │ │ ├── IOneBotController.cs │ │ ├── IOneBotMiddleware.cs │ │ ├── Implements │ │ │ ├── BotService.cs │ │ │ ├── CQJsonRouterService.cs │ │ │ ├── CommandService.cs │ │ │ ├── EventService.cs │ │ │ ├── OneBotContextHolder.cs │ │ │ ├── OneBotHostedService.cs │ │ │ └── OneBotServer.cs │ │ └── OneBotRequestDelegate.cs │ └── Utils │ │ └── YukariToolBoxLogger.cs └── OneBot-CommandRoute.csproj ├── OneBot-Framework-Demo ├── .gitignore ├── Attributes │ └── DemoBeforeCommandAttribute.cs ├── Middleware │ └── TestMiddleware.cs ├── Models │ └── Duration.cs ├── Modules │ └── TestModule.cs ├── OneBot-Framework-Demo.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── appsettings-reverse_ws-example.Development.json ├── appsettings-reverse_ws-example.json ├── appsettings-ws-example.Development.json └── appsettings-ws-example.json ├── OneBot-Framework.sln ├── OneBot-Framework.sln.DotSettings ├── OneBot-OpenTelemetry ├── .gitignore ├── OneBot-OpenTelemetry.csproj └── OpenTelemetry │ └── TraceProviderBuilderExtensions.cs ├── OneBot-UnitTest ├── .gitignore ├── DurationTest.cs ├── LexerTest.cs ├── OneBot-UnitTest.csproj └── Util │ ├── AssertUtil.cs │ └── LexerUtil.cs └── README.md /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | 6 | indent_style = space 7 | indent_size = 4 8 | 9 | insert_final_newline = true; 10 | 11 | spaces_around_operators = true; 12 | 13 | end_of_line = lf; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Visual Studio 2015/2017 cache/options directory 2 | .vs/ 3 | [Pp]ackages/ 4 | *.DotSettings.user 5 | .idea -------------------------------------------------------------------------------- /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 | . -------------------------------------------------------------------------------- /OneBot-CommandRoute/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### VisualStudio template 3 | ## Ignore Visual Studio temporary files, build results, and 4 | ## files generated by popular Visual Studio add-ons. 5 | ## 6 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 7 | 8 | # User-specific files 9 | *.rsuser 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Ww][Ii][Nn]32/ 29 | [Aa][Rr][Mm]/ 30 | [Aa][Rr][Mm]64/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Ll]og/ 35 | [Ll]ogs/ 36 | 37 | # Visual Studio 2015/2017 cache/options directory 38 | .vs/ 39 | # Uncomment if you have tasks that create the project's static files in wwwroot 40 | #wwwroot/ 41 | 42 | # Visual Studio 2017 auto generated files 43 | Generated\ Files/ 44 | 45 | # MSTest test Results 46 | [Tt]est[Rr]esult*/ 47 | [Bb]uild[Ll]og.* 48 | 49 | # NUnit 50 | *.VisualState.xml 51 | TestResult.xml 52 | nunit-*.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # ASP.NET Scaffolding 68 | ScaffoldingReadMe.txt 69 | 70 | # StyleCop 71 | StyleCopReport.xml 72 | 73 | # Files built by Visual Studio 74 | *_i.c 75 | *_p.c 76 | *_h.h 77 | *.ilk 78 | *.meta 79 | *.obj 80 | *.iobj 81 | *.pch 82 | *.pdb 83 | *.ipdb 84 | *.pgc 85 | *.pgd 86 | *.rsp 87 | *.sbr 88 | *.tlb 89 | *.tli 90 | *.tlh 91 | *.tmp 92 | *.tmp_proj 93 | *_wpftmp.csproj 94 | *.log 95 | *.vspscc 96 | *.vssscc 97 | .builds 98 | *.pidb 99 | *.svclog 100 | *.scc 101 | 102 | # Chutzpah Test files 103 | _Chutzpah* 104 | 105 | # Visual C++ cache files 106 | ipch/ 107 | *.aps 108 | *.ncb 109 | *.opendb 110 | *.opensdf 111 | *.sdf 112 | *.cachefile 113 | *.VC.db 114 | *.VC.VC.opendb 115 | 116 | # Visual Studio profiler 117 | *.psess 118 | *.vsp 119 | *.vspx 120 | *.sap 121 | 122 | # Visual Studio Trace Files 123 | *.e2e 124 | 125 | # TFS 2012 Local Workspace 126 | $tf/ 127 | 128 | # Guidance Automation Toolkit 129 | *.gpState 130 | 131 | # ReSharper is a .NET coding add-in 132 | _ReSharper*/ 133 | *.[Rr]e[Ss]harper 134 | *.DotSettings.user 135 | 136 | # TeamCity is a build add-in 137 | _TeamCity* 138 | 139 | # DotCover is a Code Coverage Tool 140 | *.dotCover 141 | 142 | # AxoCover is a Code Coverage Tool 143 | .axoCover/* 144 | !.axoCover/settings.json 145 | 146 | # Coverlet is a free, cross platform Code Coverage Tool 147 | coverage*[.json, .xml, .info] 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # 362 | appsettings.json 363 | appsettings.Development.json -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Attributes/BeforeCommandAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OneBot.CommandRoute.Models; 3 | 4 | namespace OneBot.CommandRoute.Attributes; 5 | 6 | [AttributeUsage(AttributeTargets.Method)] 7 | public abstract class BeforeCommandAttribute : Attribute 8 | { 9 | public abstract void Invoke(OneBotContext scope); 10 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Attributes/CQJsonAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OneBot.CommandRoute.Models.Enumeration; 3 | 4 | namespace OneBot.CommandRoute.Attributes; 5 | 6 | /// 7 | /// CQ:Json 路由 8 | /// 9 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 10 | public class CQJsonAttribute : Attribute 11 | { 12 | /// 13 | /// 指令格式 14 | /// 15 | public string AppId { get; } 16 | 17 | /// 18 | /// 事件类型 19 | /// 20 | public EventType EventType { get; set; } = EventType.GroupMessage; 21 | 22 | /// 23 | /// CQ:Json 路由 24 | /// 25 | /// AppId 26 | public CQJsonAttribute(string appId) 27 | { 28 | AppId = appId; 29 | } 30 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Attributes/CommandAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OneBot.CommandRoute.Models.Enumeration; 3 | 4 | namespace OneBot.CommandRoute.Attributes; 5 | 6 | /// 7 | /// 指令路由 8 | /// 9 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 10 | public class CommandAttribute : Attribute 11 | { 12 | /// 13 | /// 指令格式 14 | /// 15 | public string Pattern { get; } 16 | 17 | /// 18 | /// 指令别名 19 | /// 20 | public string[] Alias { get; set; } = Array.Empty(); 21 | 22 | /// 23 | /// 事件类型 24 | /// 25 | public EventType EventType { get; set; } = EventType.GroupMessage; 26 | 27 | /// 28 | /// 指令路由 29 | /// 30 | /// 指令格式 31 | public CommandAttribute(string pattern) 32 | { 33 | Pattern = pattern; 34 | } 35 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Attributes/CommandParameterAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace OneBot.CommandRoute.Attributes; 4 | 5 | /// 6 | /// 指令参数绑定 7 | /// 8 | public class CommandParameterAttribute : Attribute 9 | { 10 | /// 11 | /// 参数名 12 | /// 13 | public string Name { get; } 14 | 15 | /// 16 | /// 指令参数绑定 17 | /// 18 | /// 参数名 19 | public CommandParameterAttribute(string name) 20 | { 21 | Name = name; 22 | } 23 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Attributes/ParsedArgumentsAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace OneBot.CommandRoute.Attributes; 4 | 5 | /// 6 | /// 获取全部的参数列表 7 | /// 8 | [AttributeUsage(AttributeTargets.Parameter)] 9 | public class ParsedArgumentsAttribute : Attribute 10 | { 11 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Command/MatchingNode.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using OneBot.CommandRoute.Configuration; 4 | using OneBot.CommandRoute.Lexer; 5 | using OneBot.CommandRoute.Models; 6 | using OneBot.CommandRoute.Models.Entities; 7 | using Sora.EventArgs.SoraEvent; 8 | 9 | namespace OneBot.CommandRoute.Command; 10 | 11 | /// 12 | /// 匹配结点 13 | /// 14 | /// 27 | public class MatchingNode 28 | { 29 | /// 30 | /// 为根节点 31 | /// 32 | public bool IsRoot = false; 33 | 34 | /// 35 | /// 指令前缀 36 | /// 37 | private readonly IOneBotCommandRouteConfiguration _configuration; 38 | 39 | /// 40 | /// 和这个结点相关的指令信息列表 41 | /// 42 | private List _command = new List(); 43 | 44 | /// 45 | /// 待匹配的子结点 46 | /// 47 | private readonly SortedDictionary _children = new SortedDictionary(); 48 | 49 | public MatchingNode(IOneBotCommandRouteConfiguration configuration) 50 | { 51 | this._configuration = configuration; 52 | } 53 | 54 | /// 55 | /// 处理指令匹配 56 | /// 57 | /// 事件上下文 58 | /// 0 继续 / 1 阻断 59 | public int ProcessingCommandMapping(OneBotContext context) 60 | { 61 | var eventArgs = context.SoraEventArgs; 62 | 63 | CommandLexer? lexer = eventArgs switch 64 | { 65 | GroupMessageEventArgs groupMessageEventArgs => new CommandLexer(groupMessageEventArgs.Message.MessageBody), 66 | PrivateMessageEventArgs privateMessageEventArgs => new CommandLexer(privateMessageEventArgs.Message.MessageBody), 67 | _ => null 68 | }; 69 | 70 | return lexer == null ? 0 : ProcessingCommandMapping(context, lexer); 71 | } 72 | 73 | 74 | /// 75 | /// 处理指令匹配 76 | /// 77 | /// 事件上下文 78 | /// 指令解析器 79 | /// 0 继续 / 1 阻断 80 | private int ProcessingCommandMapping(OneBotContext context, CommandLexer lexer) 81 | { 82 | if (!lexer.IsValid()) return 0; 83 | 84 | var oldParser = lexer.Clone(); 85 | 86 | object? nextToken = null; 87 | try 88 | { 89 | nextToken = lexer.GetNextNotBlank(); 90 | } 91 | catch (ParseToTheEndException) 92 | { 93 | } 94 | 95 | if (nextToken is string token) 96 | { 97 | foreach (var s in _children) 98 | { 99 | var nextStepForComparing = _configuration.IsCaseSensitive ? s.Key : s.Key.ToUpper(); 100 | var tokenForComparing = _configuration.IsCaseSensitive ? token : token.ToUpper(); 101 | 102 | // 如果是根,并且有设置指令前缀,并且是英文指令,那么我们就处理指令前缀匹配 103 | if (IsRoot && 104 | _configuration.CommandPrefix.Length > 0 && 105 | ( 106 | (nextStepForComparing[0] >= 'A' && nextStepForComparing[0] <= 'Z') || 107 | (nextStepForComparing[0] >= 'a' && nextStepForComparing[0] <= 'z')) 108 | ) 109 | { 110 | if (!_configuration.CommandPrefix.Contains("" + token[0])) continue; 111 | if (nextStepForComparing != tokenForComparing[1..]) continue; 112 | } 113 | else 114 | { 115 | if (nextStepForComparing != tokenForComparing) continue; 116 | } 117 | 118 | var ret = s.Value.ProcessingCommandMapping(context, lexer); 119 | if (ret != 0) return ret; 120 | } 121 | } 122 | 123 | foreach (var s in _command) 124 | { 125 | var ret = s.Invoke(context, oldParser); 126 | if (ret != 0) return ret; 127 | } 128 | 129 | return 0; 130 | } 131 | 132 | /// 133 | /// 注册指令 134 | /// 135 | /// 要注册的指令信息 136 | /// 深度 137 | public void Register(CommandModel command, int i) 138 | { 139 | if (i >= command.ParametersName.Count) 140 | { 141 | // 完全匹配完力 142 | _command.Add(command); 143 | // 保证先匹配更严格的指令再匹配宽松的指令 144 | _command = _command.OrderByDescending(s => s.WeightA).ThenByDescending(s => s.WeightB).ToList(); 145 | return; 146 | } 147 | 148 | if (command.ParametersMatchingType[i] != 0) 149 | { 150 | // 参数部分就不进入匹配了 151 | _command.Add(command); 152 | _command = _command.OrderByDescending(s => s.WeightA).ThenByDescending(s => s.WeightB).ToList(); 153 | return; 154 | } 155 | 156 | // 挂载子结点 157 | if (!_children.TryGetValue(command.ParametersName[i], out var tmp)) 158 | { 159 | tmp = new MatchingNode(_configuration); 160 | _children[command.ParametersName[i]] = tmp; 161 | } 162 | 163 | tmp.Register(command, i + 1); 164 | } 165 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Configuration/DefaultOneBotCommandRouteConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace OneBot.CommandRoute.Configuration; 2 | 3 | public class DefaultOneBotCommandRouteConfiguration : IOneBotCommandRouteConfiguration 4 | { 5 | private static readonly string[] CommandPrefixConst = { "!", "!", "/" }; 6 | 7 | /// 8 | /// 默认英文指令前缀 9 | /// 10 | public string[] CommandPrefix => CommandPrefixConst; 11 | 12 | /// 13 | /// 默认指令匹配大小写不敏感 14 | /// 15 | public bool IsCaseSensitive => false; 16 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Configuration/IOneBotCommandRouteConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace OneBot.CommandRoute.Configuration; 2 | 3 | public interface IOneBotCommandRouteConfiguration 4 | { 5 | /// 6 | /// 英文指令时使用的前缀,请保证数组每一个长度都等于 1。 7 | /// 若返回空数组,则表示英文指令也不使用前缀。 8 | /// 9 | string[] CommandPrefix { get; } 10 | 11 | /// 12 | /// 指令匹配是否大小写敏感 13 | /// 14 | bool IsCaseSensitive { get; } 15 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Events/EventHandleException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace OneBot.CommandRoute.Events; 4 | 5 | internal class EventHandleException : Exception 6 | { 7 | public EventHandleException(string msg) : base(msg) 8 | { 9 | } 10 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Events/EventManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using OneBot.CommandRoute.Models; 5 | using Sora.EventArgs.SoraEvent; 6 | 7 | namespace OneBot.CommandRoute.Events; 8 | 9 | public class EventManager 10 | { 11 | /// 客户端链接完成事件 12 | public event EventAsyncCallBackHandler? OnClientConnect; 13 | 14 | /// 群聊事件(触发指令之后) 15 | public event EventAsyncCallBackHandler? OnGroupMessage; 16 | 17 | /// 群聊事件(触发指令之前) 18 | public event EventAsyncCallBackHandler? OnGroupMessageReceived; 19 | 20 | /// 登录账号发送消息事件(群聊) 21 | public event EventAsyncCallBackHandler? OnSelfGroupMessage; 22 | 23 | /// 登录账号发送消息事件(私聊) 24 | public event EventAsyncCallBackHandler? OnSelfPrivateMessage; 25 | 26 | /// 私聊事件(触发指令之后) 27 | public event EventAsyncCallBackHandler? OnPrivateMessage; 28 | 29 | /// 私聊事件(触发指令之前) 30 | public event EventAsyncCallBackHandler? OnPrivateMessageReceived; 31 | 32 | /// 群申请事件 33 | public event EventAsyncCallBackHandler? OnGroupRequest; 34 | 35 | /// 好友申请事件 36 | public event EventAsyncCallBackHandler? OnFriendRequest; 37 | 38 | /// 群文件上传事件 39 | public event EventAsyncCallBackHandler? OnFileUpload; 40 | 41 | /// 管理员变动事件 42 | public event EventAsyncCallBackHandler? OnGroupAdminChange; 43 | 44 | /// 群成员变动事件 45 | public event EventAsyncCallBackHandler? OnGroupMemberChange; 46 | 47 | /// 群成员禁言事件 48 | public event EventAsyncCallBackHandler? OnGroupMemberMute; 49 | 50 | /// 好友添加事件 51 | public event EventAsyncCallBackHandler? OnFriendAdd; 52 | 53 | /// 群聊撤回事件 54 | public event EventAsyncCallBackHandler? OnGroupRecall; 55 | 56 | /// 好友撤回事件 57 | public event EventAsyncCallBackHandler? OnFriendRecall; 58 | 59 | /// 群名片变更事件 60 | public event EventAsyncCallBackHandler? OnGroupCardUpdate; 61 | 62 | /// 群内戳一戳事件 63 | public event EventAsyncCallBackHandler? OnGroupPoke; 64 | 65 | /// 运气王事件 66 | public event EventAsyncCallBackHandler? OnLuckyKingEvent; 67 | 68 | /// 群成员荣誉变更事件 69 | public event EventAsyncCallBackHandler? OnHonorEvent; 70 | 71 | /// 群成员头衔更新 72 | public event EventAsyncCallBackHandler? OnTitleUpdate; 73 | 74 | /// 离线文件事件 75 | public event EventAsyncCallBackHandler? OnOfflineFileEvent; 76 | 77 | /// 其他客户端在线状态变更事件 78 | public event EventAsyncCallBackHandler? OnClientStatusChangeEvent; 79 | 80 | /// 其他客户端在线状态变更事件 81 | public event EventAsyncCallBackHandler? OnEssenceChange; 82 | 83 | // ReSharper disable once UnusedTypeParameter 84 | public delegate int EventAsyncCallBackHandler(OneBotContext scope) where TEventArgs : EventArgs; 85 | 86 | /// 87 | /// 事件源 88 | /// 89 | private static readonly ActivitySource EventRouteActivitySource = new ActivitySource("OneBot.EventRoute", Assembly.GetExecutingAssembly().GetName().Version!.ToString()); 90 | 91 | /// 92 | /// 分发事件 93 | /// 94 | /// 95 | internal void Fire(OneBotContext context) 96 | { 97 | var eventArgs = context.SoraEventArgs; 98 | 99 | // ReSharper disable once ConvertIfStatementToSwitchStatement 100 | if (eventArgs is ConnectEventArgs) 101 | { 102 | Fire(context, OnClientConnect); 103 | } 104 | else if (eventArgs is GroupMessageEventArgs) 105 | { 106 | Fire(context, OnGroupMessage); 107 | } 108 | else if (eventArgs is PrivateMessageEventArgs) 109 | { 110 | Fire(context, OnPrivateMessage); 111 | } 112 | else if (eventArgs is AddGroupRequestEventArgs) 113 | { 114 | Fire(context, OnGroupRequest); 115 | } 116 | else if (eventArgs is FriendRequestEventArgs) 117 | { 118 | Fire(context, OnFriendRequest); 119 | } 120 | else if (eventArgs is FileUploadEventArgs) 121 | { 122 | Fire(context, OnFileUpload); 123 | } 124 | else if (eventArgs is GroupAdminChangeEventArgs) 125 | { 126 | Fire(context, OnGroupAdminChange); 127 | } 128 | else if (eventArgs is GroupMemberChangeEventArgs) 129 | { 130 | Fire(context, OnGroupMemberChange); 131 | } 132 | else if (eventArgs is GroupMuteEventArgs) 133 | { 134 | Fire(context, OnGroupMemberMute); 135 | } 136 | else if (eventArgs is FriendAddEventArgs) 137 | { 138 | Fire(context, OnFriendAdd); 139 | } 140 | else if (eventArgs is GroupRecallEventArgs) 141 | { 142 | Fire(context, OnGroupRecall); 143 | } 144 | else if (eventArgs is FriendRecallEventArgs) 145 | { 146 | Fire(context, OnFriendRecall); 147 | } 148 | else if (eventArgs is GroupCardUpdateEventArgs) 149 | { 150 | Fire(context, OnGroupCardUpdate); 151 | } 152 | else if (eventArgs is GroupPokeEventArgs) 153 | { 154 | Fire(context, OnGroupPoke); 155 | } 156 | else if (eventArgs is LuckyKingEventArgs) 157 | { 158 | Fire(context, OnLuckyKingEvent); 159 | } 160 | else if (eventArgs is HonorEventArgs) 161 | { 162 | Fire(context, OnHonorEvent); 163 | } 164 | else if (eventArgs is TitleUpdateEventArgs) 165 | { 166 | Fire(context, OnTitleUpdate); 167 | } 168 | else if (eventArgs is OfflineFileEventArgs) 169 | { 170 | Fire(context, OnOfflineFileEvent); 171 | } 172 | else if (eventArgs is ClientStatusChangeEventArgs) 173 | { 174 | Fire(context, OnClientStatusChangeEvent); 175 | } 176 | else if (eventArgs is EssenceChangeEventArgs) 177 | { 178 | Fire(context, OnEssenceChange); 179 | } 180 | else 181 | { 182 | throw new EventHandleException("不存在这样的事件。"); 183 | } 184 | } 185 | 186 | /// 187 | /// 触发事件 188 | /// 189 | /// 190 | /// 191 | /// 192 | /// 193 | // ReSharper disable once MemberCanBeMadeStatic.Local 194 | private int Fire(OneBotContext context, EventAsyncCallBackHandler? eventAsyncCallBackHandler) 195 | where T : BaseSoraEventArgs 196 | { 197 | Delegate[]? listeners = eventAsyncCallBackHandler?.GetInvocationList(); 198 | if (listeners == null) return 0; 199 | 200 | for (int counter = listeners.Length - 1; counter >= 0; counter--) 201 | { 202 | var func = (EventAsyncCallBackHandler)listeners[counter]; 203 | var target = func.Target; 204 | var method = func.Method; 205 | var operationName = (target?.GetType().FullName ?? "?") + "::" + method.Name; 206 | var activity = EventRouteActivitySource.CreateActivity(operationName, ActivityKind.Internal) ?? new Activity(operationName); 207 | activity.Start(); 208 | int ret = func(context); 209 | activity.Stop(); 210 | 211 | if (ret != 0) return ret; 212 | } 213 | 214 | return 0; 215 | } 216 | 217 | /// 218 | /// 分发接收到私聊消息后处理指令前事件 219 | /// 220 | /// 221 | /// 222 | internal int FirePrivateMessageReceived(OneBotContext scope) 223 | { 224 | return Fire(scope, OnPrivateMessageReceived); 225 | } 226 | 227 | /// 228 | /// 分发接收到群聊消息后处理指令前事件 229 | /// 230 | /// 231 | /// 232 | internal int FireGroupMessageReceived(OneBotContext scope) 233 | { 234 | return Fire(scope, OnGroupMessageReceived); 235 | } 236 | 237 | /// 238 | /// 异常处理事件 239 | /// 240 | public event ExceptionDelegate? OnException; 241 | 242 | public delegate void ExceptionDelegate(OneBotContext scope, Exception exception); 243 | 244 | /// 245 | /// 分发异常 246 | /// 247 | /// 248 | /// 249 | /// 250 | internal bool FireException(OneBotContext scope, Exception exception) 251 | { 252 | var onException = OnException; 253 | if (onException == null) return false; 254 | onException(scope, exception); 255 | return true; 256 | } 257 | 258 | /// 259 | /// 分发登录账号发送消息事件(群聊) 260 | /// 261 | /// 262 | internal void FireSelfGroupMessage(OneBotContext scope) 263 | { 264 | Fire(scope, OnSelfGroupMessage); 265 | } 266 | 267 | /// 268 | /// 分发登录账号发送消息事件(私聊) 269 | /// 270 | /// 271 | internal void FireSelfPrivateMessage(OneBotContext scope) 272 | { 273 | Fire(scope, OnSelfPrivateMessage); 274 | } 275 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Lexer/CommandLexer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Sora.Entities; 4 | using Sora.Entities.Segment.DataModel; 5 | using Sora.Entities.Segment; 6 | using Sora.Enumeration; 7 | 8 | namespace OneBot.CommandRoute.Lexer; 9 | 10 | /// 11 | /// 指令解析器 12 | /// 13 | public class CommandLexer 14 | { 15 | /// 16 | /// 空白字符 17 | /// 18 | private const string BlankCharacter = "\r\n\t "; 19 | 20 | /// 21 | /// 引号 22 | /// 23 | private const string QuoteCharacter = "\"\'"; 24 | 25 | /// 26 | /// 源信息 27 | /// 28 | // ReSharper disable once MemberCanBePrivate.Global 29 | public IList SourceCommand { get; } 30 | 31 | /// 32 | /// 已经解析了的参数信息 33 | /// 34 | public List ParsedArguments { get; private init; } = new List(); 35 | 36 | /// 37 | /// 当前扫描到 SourceCommand 的哪一个位置。 38 | /// 39 | // ReSharper disable once MemberCanBePrivate.Global 40 | public int ScanObjectPointer { get; private set; } 41 | 42 | /// 43 | /// 如果当前扫描到的 SourceCommandCQFunction.Text 的话当前字符串扫描到哪一个位置。 44 | /// 45 | // ReSharper disable once MemberCanBePrivate.Global 46 | public int ScanStringPointer { get; private set; } 47 | 48 | /// 49 | /// 构造函数 50 | /// 51 | /// 被解析的字符串 52 | public CommandLexer(IList s) 53 | { 54 | SourceCommand = s.Where(c => 55 | c.MessageType != SegmentType.Text 56 | || ((TextSegment)c.Data).Content.Length > 0) 57 | .ToList(); 58 | } 59 | 60 | /// 61 | /// 检查被解析的字符串是否有效 62 | /// 63 | /// 真: 有效/假: 无效 64 | public bool IsValid() 65 | { 66 | // 如果已经开始扫描了那必然合法 67 | if (ScanObjectPointer != 0 || ScanStringPointer != 0) return true; 68 | 69 | var scanObjectPointer = 0; 70 | var scanStringPointer = 0; 71 | 72 | // 空消息不合法 73 | if (SourceCommand.Count == 0) return false; 74 | 75 | // 如果第一个消息段为回复消息 76 | if (SourceCommand[0].MessageType == SegmentType.Reply) 77 | { 78 | // 如果消息段长度只有1则不合法 79 | if (SourceCommand.Count < 2) return false; 80 | scanObjectPointer = 1; 81 | } 82 | 83 | // ReSharper disable once JoinDeclarationAndInitializer 84 | string s; 85 | var flag = false; 86 | 87 | // 兼容 回复+At+(空格+正文) 的奇怪设计 88 | if (scanObjectPointer == 1 && SourceCommand[scanObjectPointer].MessageType == SegmentType.At) 89 | { 90 | if (SourceCommand[scanObjectPointer].MessageType == SegmentType.At) 91 | { 92 | // 如果消息段长度只有2则不合法 93 | if (SourceCommand.Count < 3) return false; 94 | scanObjectPointer = 2; 95 | } 96 | 97 | flag = true; 98 | } 99 | 100 | // 如果扫描起始消息段不为文本则不合法 101 | if (SourceCommand[scanObjectPointer].MessageType != SegmentType.Text) return false; 102 | s = ((TextSegment)SourceCommand[scanObjectPointer].Data).Content; 103 | 104 | // 兼容 回复+空格+At+正文 的奇怪设计 105 | if (scanObjectPointer == 1 && string.IsNullOrWhiteSpace(s)) 106 | { 107 | if (SourceCommand.Count < 4) return false; 108 | if (SourceCommand[2].MessageType != SegmentType.At) return false; 109 | if (SourceCommand[3].MessageType != SegmentType.Text) return false; 110 | 111 | scanObjectPointer = 3; 112 | s = ((TextSegment)SourceCommand[scanObjectPointer].Data).Content; 113 | 114 | flag = true; 115 | } 116 | 117 | if (flag) 118 | { 119 | // 舍弃空白段 120 | while (SourceCommand[scanObjectPointer].MessageType == SegmentType.Text) 121 | { 122 | if (!string.IsNullOrWhiteSpace(((TextSegment)SourceCommand[scanObjectPointer].Data).Content)) break; 123 | scanObjectPointer++; 124 | if (scanObjectPointer == SourceCommand.Count) return false; 125 | } 126 | 127 | // 如果舍弃空白段后不是文本段则不合法 128 | if (SourceCommand[scanObjectPointer].MessageType != SegmentType.Text) return false; 129 | s = ((TextSegment)(SourceCommand[scanObjectPointer].Data)).Content; 130 | 131 | // 舍弃开头空白字符 132 | while (scanStringPointer < s.Length && BlankCharacter.Contains(s[scanStringPointer])) 133 | { 134 | scanStringPointer++; 135 | } 136 | } 137 | 138 | // 普通发言支持 139 | if (scanObjectPointer == 0) 140 | { 141 | // 空消息不合法 142 | if (s.Length == 0) return false; 143 | 144 | // 空白符号开头不合法 145 | if (BlankCharacter.Contains((s[0]))) return false; 146 | } 147 | 148 | ScanObjectPointer = scanObjectPointer; 149 | ScanStringPointer = scanStringPointer; 150 | return true; 151 | } 152 | 153 | /// 154 | /// 尝试获得下一个字符串 155 | /// 156 | private bool TryGetNextStringObject(ref string str) 157 | { 158 | // 如果往后这个字符串已经扫完了 159 | if (ScanStringPointer >= str.Length) 160 | { 161 | // 那就往后取一个对象 162 | ScanObjectPointer++; 163 | ScanStringPointer = 0; 164 | 165 | if (ScanObjectPointer < SourceCommand.Count) 166 | { 167 | // 往后取一个 168 | var nextSegment = SourceCommand[ScanObjectPointer]; 169 | if (nextSegment.MessageType == SegmentType.Text) 170 | { 171 | // 接着往后识别 172 | str = ((TextSegment)(nextSegment.Data)).Content; 173 | } 174 | else 175 | { 176 | // 如果后面那个不是字符串,那么就结束 177 | return true; 178 | } 179 | } 180 | else 181 | { 182 | // 如果往后取一个对象已经没得再取了,那就直接返回 183 | return true; 184 | } 185 | } 186 | return false; 187 | } 188 | 189 | 190 | /// 191 | /// 获取下一个 Token 192 | /// 193 | /// 下一个 Token 194 | private object GetNext() 195 | { 196 | // 检查是否扫描到末尾 197 | if (ScanObjectPointer >= SourceCommand.Count) 198 | { 199 | throw new ParseToTheEndException(); 200 | } 201 | 202 | // 当前扫描到的消息段 203 | var s = SourceCommand[ScanObjectPointer]; 204 | 205 | // 如果当前扫描到的消息段不是文本消息段则返回当前消息段 206 | if (s.MessageType != SegmentType.Text) 207 | { 208 | ScanObjectPointer++; 209 | ScanStringPointer = 0; 210 | return s; 211 | } 212 | 213 | // 获取当前消息段的文本 214 | var str = ((TextSegment)(s.Data)).Content; 215 | var token = ""; 216 | 217 | // 检查当前元素是否扫描完成 218 | if (ScanStringPointer >= str.Length) 219 | { 220 | ScanObjectPointer++; 221 | ScanStringPointer = 0; 222 | if (ScanObjectPointer >= SourceCommand.Count) 223 | { 224 | throw new ParseToTheEndException(); 225 | } 226 | 227 | // 获取下一个消息段 228 | var ret = SourceCommand[ScanObjectPointer]; 229 | 230 | // 如果下一个消息段不是文本则返回 231 | if (ret.MessageType != SegmentType.Text) 232 | { 233 | ScanObjectPointer++; 234 | return ret; 235 | } 236 | 237 | // 如果下一个消息段是文本则继续扫描 238 | s = ret; 239 | str = ((TextSegment)(s.Data)).Content; 240 | } 241 | 242 | // 文本参数 243 | if (BlankCharacter.Contains(str[ScanStringPointer])) 244 | { 245 | // 空白元素 246 | while (BlankCharacter.Contains(str[ScanStringPointer])) 247 | { 248 | // 往后拼接 249 | token += str[ScanStringPointer]; 250 | ScanStringPointer++; 251 | if (TryGetNextStringObject(ref str)) 252 | { 253 | return token; 254 | } 255 | } 256 | } 257 | else 258 | { 259 | // 非空白元素 260 | if (QuoteCharacter.Contains(str[ScanStringPointer])) 261 | { 262 | MessageBody multiElementsToken = new MessageBody(); 263 | var terminate = str[ScanStringPointer]; 264 | 265 | ScanStringPointer++; 266 | TryGetNextStringObject(ref str); 267 | 268 | while (true) 269 | { 270 | // 往后拼接 271 | if (SourceCommand[ScanObjectPointer].MessageType == SegmentType.Text) 272 | { 273 | if (str[ScanStringPointer] == terminate) 274 | { 275 | // 如果遇到了字符串起始符号 276 | ScanStringPointer++; 277 | if (ScanStringPointer < str.Length) 278 | { 279 | // 如果当前字符串还没处理完 280 | if (str[ScanStringPointer] == terminate) 281 | { 282 | // 如果下一个符号还是起始符号 283 | token += terminate; 284 | ScanStringPointer++; 285 | TryGetNextStringObject(ref str); 286 | } 287 | else 288 | { 289 | // 如果不是起始符号 290 | multiElementsToken += token; 291 | // ReSharper disable once RedundantAssignment 292 | token = ""; 293 | break; 294 | } 295 | } 296 | else 297 | { 298 | // 如果当前字符串处理完了 299 | ScanStringPointer = 0; 300 | ScanObjectPointer++; 301 | 302 | if (ScanObjectPointer >= SourceCommand.Count) 303 | { 304 | // 如果整个消息已经处理完了 305 | multiElementsToken += token; 306 | // ReSharper disable once RedundantAssignment 307 | token = ""; 308 | break; 309 | } 310 | else 311 | { 312 | if (SourceCommand[ScanObjectPointer].MessageType != SegmentType.Text) 313 | { 314 | // 如果下一个消息段不是文本,意味着当前扫描到的地方就是一个完整的文本消息 315 | multiElementsToken += token; 316 | // ReSharper disable once RedundantAssignment 317 | token = ""; 318 | break; 319 | } 320 | else 321 | { 322 | // 如果下一个消息段是文本,意味着我们需要看一眼 323 | str = ((TextSegment)SourceCommand[ScanObjectPointer].Data).Content; 324 | if (str[ScanStringPointer] == terminate) 325 | { 326 | // 如果下一个符号还是起始符号 327 | token += terminate; 328 | ScanStringPointer++; 329 | TryGetNextStringObject(ref str); 330 | } 331 | else 332 | { 333 | // 如果不是起始符号 334 | multiElementsToken += token; 335 | // ReSharper disable once RedundantAssignment 336 | token = ""; 337 | break; 338 | } 339 | } 340 | } 341 | } 342 | } 343 | else 344 | { 345 | token += str[ScanStringPointer]; 346 | ScanStringPointer++; 347 | if (TryGetNextStringObject(ref str)) 348 | { 349 | multiElementsToken += token; 350 | token = ""; 351 | } 352 | } 353 | } 354 | else 355 | { 356 | multiElementsToken += SourceCommand[ScanObjectPointer]; 357 | ScanObjectPointer++; 358 | if (ScanObjectPointer < SourceCommand.Count) 359 | { 360 | str = ((TextSegment)SourceCommand[ScanObjectPointer].Data).Content; 361 | } 362 | } 363 | 364 | if (ScanObjectPointer >= SourceCommand.Count) 365 | { 366 | break; 367 | } 368 | } 369 | 370 | return multiElementsToken; 371 | } 372 | else 373 | { 374 | while (!BlankCharacter.Contains(str[ScanStringPointer])) 375 | { 376 | // 往后拼接 377 | token += str[ScanStringPointer]; 378 | ScanStringPointer++; 379 | if (TryGetNextStringObject(ref str)) 380 | { 381 | return token; 382 | } 383 | } 384 | } 385 | } 386 | return token; 387 | } 388 | 389 | /// 390 | /// 获取下一个不是空白的 Token 391 | /// 392 | /// 下一个 Token 393 | public object GetNextNotBlank() 394 | { 395 | var ret = GetNext(); 396 | while (ret is string s && string.IsNullOrWhiteSpace(s)) 397 | { 398 | ret = GetNext(); 399 | } 400 | ParsedArguments.Add(ret); 401 | return ret; 402 | } 403 | 404 | /// 405 | /// 获得现在已经得到的 Token 列表 406 | /// 407 | /// 已获得的 Token 列表 408 | public List GetNowParsedToken() 409 | { 410 | List ret = new List(ParsedArguments); 411 | 412 | if (ScanStringPointer != 0) 413 | { 414 | ret.Add(((TextSegment)(SourceCommand[ScanObjectPointer].Data)).Content.Substring(ScanStringPointer)); 415 | } 416 | else 417 | { 418 | for (int i = ScanObjectPointer; i < SourceCommand.Count; i++) 419 | { 420 | ret.Add(SourceCommand[i]); 421 | } 422 | } 423 | 424 | return ret; 425 | } 426 | 427 | /// 428 | /// 克隆 Lexer 的当前状态 429 | /// 430 | /// 新的 Lexer 431 | public CommandLexer Clone() 432 | { 433 | CommandLexer ret = new CommandLexer(SourceCommand) 434 | { 435 | ParsedArguments = new List(ParsedArguments), 436 | ScanObjectPointer = ScanObjectPointer, 437 | ScanStringPointer = ScanStringPointer 438 | }; 439 | return ret; 440 | } 441 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Lexer/ParseToTheEndException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace OneBot.CommandRoute.Lexer; 4 | 5 | public class ParseToTheEndException : Exception 6 | { 7 | internal ParseToTheEndException() 8 | { 9 | } 10 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Mixin/StartupMixin.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Hosting.Server; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using OneBot.CommandRoute.OneBotControllers; 7 | using OneBot.CommandRoute.Services; 8 | using OneBot.CommandRoute.Services.Implements; 9 | using OneBot.CommandRoute.Utils; 10 | using YukariToolBox.LightLog; 11 | 12 | namespace OneBot.CommandRoute.Mixin; 13 | 14 | public static class StartupMixin 15 | { 16 | /// 17 | /// 将 OneBot 服务注册到服务容器。包含:OneBot 服务、指令服务、CQ:Json 服务和日志服务。 18 | /// 19 | /// 20 | public static void ConfigureOneBot(this IServiceCollection services) 21 | { 22 | // OneBot 23 | services.AddSingleton(); 24 | services.AddSingleton(); 25 | 26 | // OneBot 上下文持有者 27 | services.AddScoped(); 28 | 29 | // 事件服务 30 | services.AddSingleton(); 31 | 32 | // 指令路由服务 33 | services.AddSingleton(); 34 | 35 | // CQ:Json 路由服务 36 | services.AddSingleton(); 37 | services.AddSingleton(); 38 | 39 | // 日志服务 40 | services.AddSingleton(); 41 | } 42 | 43 | 44 | public static IHostBuilder ConfigureOneBotHost(this IHostBuilder builder) 45 | { 46 | builder.ConfigureServices(s => s.AddSingleton()); 47 | return builder; 48 | } 49 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Models/Entities/CQJsonRouteModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using OneBot.CommandRoute.Attributes; 5 | using OneBot.CommandRoute.Services; 6 | using Sora.EventArgs.SoraEvent; 7 | 8 | namespace OneBot.CommandRoute.Models.Entities; 9 | 10 | public class CQJsonRouteModel 11 | { 12 | /// 13 | /// 指令对象(单例) 14 | /// 15 | // ReSharper disable once MemberCanBePrivate.Global 16 | public IOneBotController CommandObj { get; private set; } 17 | 18 | /// 19 | /// 指令方法 20 | /// 21 | // ReSharper disable once MemberCanBePrivate.Global 22 | public MethodInfo CommandMethod { get; private set; } 23 | 24 | /// 25 | /// 这个路由方法的属性 26 | /// 27 | // ReSharper disable once MemberCanBePrivate.Global 28 | public CQJsonAttribute Attribute { get; private set; } 29 | 30 | public CQJsonRouteModel(IOneBotController commandObj, MethodInfo commandMethod, CQJsonAttribute attribute) 31 | { 32 | CommandObj = commandObj; 33 | CommandMethod = commandMethod; 34 | Attribute = attribute; 35 | } 36 | 37 | public int Invoke(OneBotContext context, BaseSoraEventArgs baseSoraEventArgs) 38 | { 39 | var functionParametersList = CommandMethod.GetParameters(); 40 | object?[] functionArgs = new object[functionParametersList.Length]; 41 | 42 | // 依赖注入 43 | for (int i = 0; i < functionParametersList.Length; i++) 44 | { 45 | if (functionArgs[i] != null) continue; 46 | 47 | var parameter = functionParametersList[i]; 48 | var parameterType = parameter.ParameterType; 49 | 50 | // 判断是否需要传递事件信息 51 | if (parameterType == typeof(BaseSoraEventArgs)) 52 | { 53 | functionArgs[i] = baseSoraEventArgs; 54 | continue; 55 | } 56 | 57 | if (parameterType == typeof(PrivateMessageEventArgs) && baseSoraEventArgs is PrivateMessageEventArgs) 58 | { 59 | functionArgs[i] = baseSoraEventArgs; 60 | continue; 61 | } 62 | 63 | if (parameterType == typeof(GroupMessageEventArgs) && baseSoraEventArgs is GroupMessageEventArgs) 64 | { 65 | functionArgs[i] = baseSoraEventArgs; 66 | continue; 67 | } 68 | 69 | // 判断是否需要传递 Scope 信息 70 | if (parameterType == typeof(IServiceScope)) 71 | { 72 | functionArgs[i] = context.ServiceScope; 73 | continue; 74 | } 75 | 76 | if (parameterType == typeof(OneBotContext)) 77 | { 78 | functionArgs[i] = context; 79 | continue; 80 | } 81 | 82 | // 从 Scope 中获得参数 83 | functionArgs[i] = context.ServiceScope.ServiceProvider.GetService(parameterType); 84 | } 85 | 86 | // 在调用前执行 87 | if (System.Attribute.IsDefined(CommandMethod, typeof(BeforeCommandAttribute))) 88 | { 89 | var attrs = System.Attribute.GetCustomAttributes(CommandMethod, typeof(BeforeCommandAttribute)); 90 | foreach (var t in attrs) 91 | { 92 | (t as BeforeCommandAttribute)?.Invoke(context); 93 | } 94 | } 95 | 96 | // 调用 97 | if (CommandMethod.ReturnType == typeof(int)) 98 | { 99 | return CommandMethod.Invoke(CommandObj, functionArgs) is int i ? i : throw new InvalidCastException(); 100 | } 101 | 102 | CommandMethod.Invoke(CommandObj, functionArgs); 103 | return 1; 104 | } 105 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Models/Entities/CommandModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Reflection; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Sora.Enumeration; 8 | using Sora.EventArgs.SoraEvent; 9 | using Sora.Entities; 10 | using OneBot.CommandRoute.Services; 11 | using OneBot.CommandRoute.Attributes; 12 | using OneBot.CommandRoute.Lexer; 13 | using OneBot.CommandRoute.Models.Enumeration; 14 | using Sora.Entities.Segment; 15 | using Sora.Util; 16 | 17 | namespace OneBot.CommandRoute.Models.Entities; 18 | 19 | /// 20 | /// 指令信息 21 | /// 22 | public class CommandModel 23 | { 24 | /// 25 | /// 指令对象(单例) 26 | /// 27 | // ReSharper disable once MemberCanBePrivate.Global 28 | public IOneBotController CommandObj { get; private set; } 29 | 30 | /// 31 | /// 指令方法 32 | /// 33 | // ReSharper disable once MemberCanBePrivate.Global 34 | public MethodInfo CommandMethod { get; private set; } 35 | 36 | /// 37 | /// 匹配的指令参数类型 38 | /// 39 | // ReSharper disable once MemberCanBePrivate.Global 40 | public List ParametersType { get; private set; } 41 | 42 | /// 43 | /// 指令匹配类型 44 | /// 0 全字匹配 / 45 | /// 1 参数 / 46 | /// 2 可选参数 / 47 | /// 48 | public List ParametersMatchingType { get; private set; } 49 | 50 | /// 51 | /// 指令参数名 52 | /// 53 | public List ParametersName { get; private set; } 54 | 55 | /// 56 | /// 匹配到的参数与方法参数的映射关系 57 | /// y = ParameterPositionMapping[x] 58 | /// x 是指令参数位置 59 | /// y 是函数参数位置 60 | /// 61 | // ReSharper disable once MemberCanBePrivate.Global 62 | public List ParameterPositionMapping { get; private set; } 63 | 64 | /// 65 | /// 这个指令方法的属性 66 | /// 67 | // ReSharper disable once MemberCanBePrivate.Global 68 | public CommandAttribute Attribute { get; private set; } 69 | 70 | /// 71 | /// 全字匹配和必选参数的个数和 72 | /// 73 | public int WeightA { get; private set; } 74 | 75 | /// 76 | /// 可选参数的个数 77 | /// 78 | public int WeightB { get; private set; } 79 | 80 | /// 81 | /// 事件源 82 | /// 83 | private static readonly ActivitySource ActivitySource = new ActivitySource("OneBot.CommandRoute", Assembly.GetExecutingAssembly().GetName().Version!.ToString()); 84 | 85 | /// 86 | /// 构造函数 87 | /// 88 | /// 需保证匹配类型中可选参数必须全部在最后 89 | /// 90 | /// 指令对象 91 | /// 指令方法 92 | /// 指令参数类型 93 | /// 指令匹配类型 94 | /// 指令参数名 95 | /// 指令参数位置到方法参数位置的映射关系 96 | /// 指令方法的属性 97 | public CommandModel(IOneBotController commandObj, MethodInfo commandMethod, List parametersType, 98 | List parametersMatchingType, List parametersName, List parameterPositionMapping, 99 | CommandAttribute attribute) 100 | { 101 | CommandObj = commandObj; 102 | CommandMethod = commandMethod; 103 | ParametersType = parametersType; 104 | ParametersMatchingType = parametersMatchingType; 105 | ParametersName = parametersName; 106 | ParameterPositionMapping = parameterPositionMapping; 107 | Attribute = attribute; 108 | 109 | WeightA = parametersMatchingType.Count(s => s != 2); 110 | WeightB = parametersMatchingType.Count(s => s == 2); 111 | } 112 | 113 | /// 114 | /// 尝试调用这个函数 115 | /// 116 | /// 事件上下文 117 | /// 指令解析器 118 | /// 0 继续 / 1 阻断 119 | public int Invoke(OneBotContext context, CommandLexer lexer) 120 | { 121 | var baseSoraEventArgs = context.SoraEventArgs; 122 | switch (baseSoraEventArgs) 123 | { 124 | // 检查事件类型是否正确 125 | case PrivateMessageEventArgs when (Attribute.EventType & EventType.PrivateMessage) == 0: 126 | case GroupMessageEventArgs when (Attribute.EventType & EventType.GroupMessage) == 0: 127 | return 0; 128 | } 129 | 130 | // 尝试解析剩下的所有参数 131 | int step = lexer.ParsedArguments.Count; 132 | 133 | List matchedArgs = new List(); 134 | matchedArgs.AddRange(lexer.ParsedArguments); 135 | for (int i = step; i < ParametersName.Count; i++) 136 | { 137 | matchedArgs.Add(null); 138 | } 139 | 140 | bool needExecute = true; 141 | for (int i = step; i < ParametersName.Count; i++) 142 | { 143 | var newParser = lexer.Clone(); 144 | // 解析一个新的 145 | 146 | object? newArg = null; 147 | // ReSharper disable once RedundantAssignment 148 | bool succeed = false; 149 | 150 | // 解析新的参数 151 | try 152 | { 153 | newArg = newParser.GetNextNotBlank(); 154 | succeed = true; 155 | } 156 | catch (Exception) 157 | { 158 | succeed = false; 159 | } 160 | 161 | // 类型转换 162 | if (succeed) 163 | { 164 | if (ParametersMatchingType[i] == 0) 165 | { 166 | succeed = newArg is string s && s == ParametersName[i]; 167 | } 168 | else 169 | { 170 | succeed = TryParseType(baseSoraEventArgs, newArg, ParametersType[i], out object? result); 171 | if (succeed) 172 | { 173 | newArg = result; 174 | } 175 | } 176 | } 177 | 178 | if (succeed) 179 | { 180 | matchedArgs[i] = newArg; 181 | lexer = newParser; 182 | } 183 | else 184 | { 185 | // 如果解析失败就判断是否需要继续执行 186 | // 如果当前已经匹配到了可选参数那就可以继续执行 187 | needExecute = ParametersMatchingType[i] == 2; 188 | break; 189 | } 190 | } 191 | 192 | if (!needExecute) return 0; 193 | 194 | // 调用 195 | // 参数注入 196 | var functionParametersList = CommandMethod.GetParameters(); 197 | object?[] functionArgs = new object[functionParametersList.Length]; 198 | for (int i = 0; i < ParametersName.Count; i++) 199 | { 200 | if (ParameterPositionMapping[i] < 0) continue; 201 | functionArgs[ParameterPositionMapping[i]] = matchedArgs[i]; 202 | } 203 | 204 | // 依赖注入 205 | for (int i = 0; i < functionParametersList.Length; i++) 206 | { 207 | if (functionArgs[i] != null) continue; 208 | 209 | var parameter = functionParametersList[i]; 210 | var parameterType = parameter.ParameterType; 211 | 212 | // 判断是否需要传递所有的参数 213 | if (System.Attribute.IsDefined(parameter, typeof(ParsedArgumentsAttribute))) 214 | { 215 | if (parameterType == typeof(object[])) 216 | { 217 | functionArgs[i] = lexer.GetNowParsedToken().ToArray(); 218 | } 219 | else 220 | { 221 | throw new ArgumentException($"[ParsedArguments] 属性仅接受 object[] 类型。"); 222 | } 223 | 224 | continue; 225 | } 226 | 227 | // 判断是否需要传递事件信息 228 | if (parameterType == typeof(BaseSoraEventArgs)) 229 | { 230 | functionArgs[i] = baseSoraEventArgs; 231 | continue; 232 | } 233 | 234 | if (parameterType == typeof(PrivateMessageEventArgs) && baseSoraEventArgs is PrivateMessageEventArgs) 235 | { 236 | functionArgs[i] = baseSoraEventArgs; 237 | continue; 238 | } 239 | 240 | if (parameterType == typeof(GroupMessageEventArgs) && baseSoraEventArgs is GroupMessageEventArgs) 241 | { 242 | functionArgs[i] = baseSoraEventArgs; 243 | continue; 244 | } 245 | 246 | // 判断是否需要传递 Scope 信息 247 | if (parameterType == typeof(IServiceScope)) 248 | { 249 | functionArgs[i] = context.ServiceScope; 250 | continue; 251 | } 252 | 253 | if (parameterType == typeof(OneBotContext)) 254 | { 255 | functionArgs[i] = context; 256 | continue; 257 | } 258 | 259 | // 从 Scope 中获得参数 260 | functionArgs[i] = context.ServiceScope.ServiceProvider.GetService(parameterType); 261 | } 262 | 263 | // TODO 判断是否有基本类型但是是 NOTNULL 的。 264 | 265 | // 在调用前执行 266 | if (System.Attribute.IsDefined(CommandMethod, typeof(BeforeCommandAttribute))) 267 | { 268 | var attrs = System.Attribute.GetCustomAttributes(CommandMethod, typeof(BeforeCommandAttribute)); 269 | foreach (var t in attrs) 270 | { 271 | var operationName = t.GetType().FullName ?? "?"; 272 | var activity = ActivitySource.CreateActivity(operationName, ActivityKind.Internal) ?? new Activity(operationName); 273 | activity.Start(); 274 | (t as BeforeCommandAttribute)?.Invoke(context); 275 | activity.Stop(); 276 | } 277 | } 278 | 279 | // 调用 280 | if (CommandMethod.ReturnType == typeof(int)) 281 | { 282 | var operationName = (CommandObj.GetType().FullName ?? "?") + "::" + CommandMethod.Name; 283 | var activity = ActivitySource.CreateActivity(operationName, ActivityKind.Internal) ?? new Activity(operationName); 284 | activity.Start(); 285 | var ret = CommandMethod.Invoke(CommandObj, functionArgs) is int i ? i : throw new InvalidCastException(); 286 | activity.Stop(); 287 | return ret; 288 | } 289 | 290 | { 291 | var operationName = (CommandObj.GetType().FullName ?? "?") + "::" + CommandMethod.Name; 292 | var activity = ActivitySource.CreateActivity(operationName, ActivityKind.Internal) ?? new Activity(operationName); 293 | activity.Start(); 294 | CommandMethod.Invoke(CommandObj, functionArgs); 295 | activity.Stop(); 296 | return 1; 297 | } 298 | } 299 | 300 | /// 301 | /// 尝试解析一个参数 302 | /// 303 | /// Sora 事件对象 304 | /// 被 cast 的值 305 | /// 要 cast 的类型 306 | /// cast 结果 307 | /// 真: 成功 / 假: 失败 308 | private bool TryParseType(BaseSoraEventArgs baseSoraEventArgs, object? arg, Type type, out object? result) 309 | { 310 | result = null; 311 | 312 | if (arg is string argStr) 313 | { 314 | try 315 | { 316 | return TryParseString(baseSoraEventArgs, argStr, type, out result); 317 | } 318 | catch (Exception) 319 | { 320 | return false; 321 | } 322 | } 323 | 324 | if (arg is SoraSegment soraSegment) 325 | { 326 | try 327 | { 328 | return TryParseCQCode(baseSoraEventArgs, soraSegment, type, out result); 329 | } 330 | catch (Exception) 331 | { 332 | return false; 333 | } 334 | } 335 | 336 | if (arg is MessageBody messageBody) 337 | { 338 | try 339 | { 340 | return TryParseMessageBody(baseSoraEventArgs, messageBody, type, out result); 341 | } 342 | catch (Exception) 343 | { 344 | return false; 345 | } 346 | } 347 | 348 | return false; 349 | } 350 | 351 | /// 352 | /// 尝试解析 CQ 码 353 | /// 354 | /// Sora 事件对象 355 | /// 被 cast 的值 356 | /// 要 cast 的类型 357 | /// cast 结果 358 | /// 真: 成功 / 假: 失败 359 | // ReSharper disable once MemberCanBeMadeStatic.Local 360 | // ReSharper disable once UnusedParameter.Local 361 | private bool TryParseMessageBody(BaseSoraEventArgs baseSoraEventArgs, MessageBody arg, Type type, out object? result) 362 | { 363 | // ReSharper disable once RedundantAssignment 364 | bool ret = false; 365 | if (type == typeof(MessageBody)) 366 | { 367 | ret = true; 368 | result = arg; 369 | } 370 | else if (type == typeof(string)) 371 | { 372 | ret = true; 373 | result = arg.SerializeMessage(); 374 | } 375 | else 376 | { 377 | try 378 | { 379 | var converter = type.GetMethod("op_Implicit", new[] { arg.GetType() }); 380 | if (converter != null) 381 | { 382 | result = converter.Invoke(null, new object?[] { arg }); 383 | // ReSharper disable once RedundantAssignment 384 | ret = true; 385 | } 386 | else 387 | { 388 | result = null; 389 | // ReSharper disable once RedundantAssignment 390 | ret = false; 391 | } 392 | } 393 | catch (Exception) 394 | { 395 | result = null; 396 | // ReSharper disable once RedundantAssignment 397 | ret = false; 398 | } 399 | result = null; 400 | return false; 401 | } 402 | 403 | return ret; 404 | } 405 | 406 | /// 407 | /// 尝试解析 CQ 码 408 | /// 409 | /// Sora 事件对象 410 | /// 被 cast 的值 411 | /// 要 cast 的类型 412 | /// cast 结果 413 | /// 真: 成功 / 假: 失败 414 | // ReSharper disable once MemberCanBeMadeStatic.Local 415 | private bool TryParseCQCode(BaseSoraEventArgs baseSoraEventArgs, object arg, Type type, out object? result) 416 | { 417 | // ReSharper disable once RedundantAssignment 418 | bool ret = false; 419 | if (type == ((SoraSegment)arg).Data.GetType()) 420 | { 421 | ret = true; 422 | result = arg; 423 | } 424 | else if (((SoraSegment)arg).MessageType == SegmentType.At) 425 | { 426 | var cast = (Sora.Entities.Segment.DataModel.AtSegment)((SoraSegment)arg).Data; 427 | var succeed = long.TryParse(cast.Target, out long uid); 428 | if (!succeed) 429 | { 430 | result = null; 431 | } 432 | else if (type == typeof(long)) 433 | { 434 | result = uid; 435 | ret = true; 436 | } 437 | else if (type == typeof(User)) 438 | { 439 | result = baseSoraEventArgs.SoraApi.GetUser(uid); 440 | ret = true; 441 | } 442 | else 443 | { 444 | result = null; 445 | } 446 | } 447 | else 448 | { 449 | try 450 | { 451 | var converter = type.GetMethod("op_Implicit", new[] { arg.GetType() }); 452 | if (converter != null) 453 | { 454 | result = converter.Invoke(null, new[] { arg }); 455 | // ReSharper disable once RedundantAssignment 456 | ret = true; 457 | } 458 | else 459 | { 460 | result = null; 461 | // ReSharper disable once RedundantAssignment 462 | ret = false; 463 | } 464 | } 465 | catch (Exception) 466 | { 467 | result = null; 468 | // ReSharper disable once RedundantAssignment 469 | ret = false; 470 | } 471 | result = null; 472 | return false; 473 | } 474 | 475 | return ret; 476 | } 477 | 478 | /// 479 | /// 尝试解析字符串 480 | /// 481 | /// Sora 事件对象 482 | /// 被 cast 的值 483 | /// 要 cast 的类型 484 | /// cast 结果 485 | /// 真: 成功 / 假: 失败 486 | private bool TryParseString(BaseSoraEventArgs baseSoraEventArgs, string? arg, Type type, out object? result) 487 | { 488 | // ReSharper disable once RedundantAssignment 489 | bool ret = false; 490 | 491 | if (type == typeof(int) || type == typeof(int?)) 492 | { 493 | ret = int.TryParse(arg, out int number); 494 | result = number; 495 | } 496 | else if (type == typeof(long) || type == typeof(long?)) 497 | { 498 | ret = long.TryParse(arg, out long number); 499 | result = number; 500 | } 501 | else if (type == typeof(double) || type == typeof(double?)) 502 | { 503 | ret = double.TryParse(arg, out double number); 504 | result = number; 505 | } 506 | else if (type == typeof(decimal) || type == typeof(decimal?)) 507 | { 508 | ret = decimal.TryParse(arg, out decimal number); 509 | result = number; 510 | } 511 | else if (type == typeof(string)) 512 | { 513 | result = arg; 514 | ret = true; 515 | } 516 | else if (type.IsEnum) 517 | { 518 | ret = Enum.TryParse(type, arg, out result); 519 | } 520 | /*else if (type == typeof(Duration)) 521 | { 522 | ret = Duration.TryParse(arg, out Duration duration); 523 | result = duration; 524 | }*/ 525 | else if (type == typeof(User)) 526 | { 527 | ret = long.TryParse(arg, out long cast); 528 | result = baseSoraEventArgs.SoraApi.GetUser(cast); 529 | } 530 | else if (type == typeof(Group)) 531 | { 532 | ret = long.TryParse(arg, out long cast); 533 | result = baseSoraEventArgs.SoraApi.GetGroup(cast); 534 | } 535 | else 536 | { 537 | try 538 | { 539 | var converter = type.GetMethod("op_Implicit", new[] { typeof(string) }); 540 | if (converter != null) 541 | { 542 | result = converter.Invoke(null, new object?[] { arg }); 543 | ret = true; 544 | } 545 | else 546 | { 547 | result = null; 548 | ret = false; 549 | } 550 | } 551 | catch (Exception) 552 | { 553 | result = null; 554 | ret = false; 555 | } 556 | } 557 | 558 | return ret; 559 | } 560 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Models/Entities/OneBotContextDefault.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Sora.EventArgs.SoraEvent; 6 | 7 | namespace OneBot.CommandRoute.Models.Entities; 8 | 9 | public class OneBotContextDefault : OneBotContext 10 | { 11 | /// 12 | /// Sora 基本事件参数 13 | /// 14 | public override BaseSoraEventArgs SoraEventArgs { get; protected set; } = null!; 15 | 16 | /// 17 | /// Sora 基本事件参数 18 | /// 19 | /// 20 | /// 21 | public override T WrapSoraEventArgs() 22 | { 23 | if (SoraEventArgs is not T ret) 24 | { 25 | throw new ArgumentException($"SoraEventArgs is not an instance of {typeof(T).Name}", $"SoraEventArgs"); 26 | } 27 | return ret; 28 | } 29 | 30 | /// 31 | /// IOC Service Scope 32 | /// 33 | public override IServiceScope ServiceScope { get; protected set; } = null!; 34 | 35 | /// 36 | /// 上下文传递的内容 37 | /// 38 | public override IDictionary Items { get; protected set; } = 39 | new ConcurrentDictionary(); 40 | 41 | internal void SetSoraEventArgs(BaseSoraEventArgs e) 42 | { 43 | SoraEventArgs = e; 44 | } 45 | 46 | internal void SoraServiceScope(IServiceScope scope) 47 | { 48 | ServiceScope = scope; 49 | } 50 | 51 | /// 52 | /// Sora Sender 53 | /// 54 | // ReSharper disable once MemberCanBePrivate.Global 55 | public object Sender { get; private set; } = ""; 56 | 57 | internal void SetSoraEventSender(object sender) 58 | { 59 | Sender = sender; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Models/Enumeration/EventType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace OneBot.CommandRoute.Models.Enumeration; 4 | 5 | /// 6 | /// 指令类型 7 | /// 8 | [Flags] 9 | public enum EventType 10 | { 11 | /// 12 | /// 私聊 13 | /// 14 | PrivateMessage = 0x1, 15 | 16 | /// 17 | /// 私聊 18 | /// 19 | // ReSharper disable once InconsistentNaming 20 | PM = PrivateMessage, 21 | 22 | /// 23 | /// 群聊 24 | /// 25 | GroupMessage = 0x2, 26 | 27 | /// 28 | /// 群聊 29 | /// 30 | // ReSharper disable once InconsistentNaming 31 | GM = GroupMessage, 32 | 33 | /// 34 | /// 讨论组 35 | /// 36 | [Obsolete] DiscussMessage = 0x4, 37 | 38 | /// 39 | /// 讨论组 40 | /// 41 | // ReSharper disable once InconsistentNaming 42 | [Obsolete] DM = DiscussMessage 43 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Models/OneBotContext.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Sora.EventArgs.SoraEvent; 4 | namespace OneBot.CommandRoute.Models; 5 | 6 | public abstract class OneBotContext 7 | { 8 | /// 9 | /// Sora 基本事件参数 10 | /// 11 | public abstract BaseSoraEventArgs SoraEventArgs { get; protected set; } 12 | 13 | /// 14 | /// Sora 基本事件参数 15 | /// 16 | /// 17 | /// 18 | public abstract T WrapSoraEventArgs() where T : BaseSoraEventArgs; 19 | 20 | /// 21 | /// IOC Service Scope 22 | /// 23 | public abstract IServiceScope ServiceScope { get; protected set; } 24 | 25 | /// 26 | /// 上下文传递的内容 27 | /// 28 | public abstract IDictionary Items { get; protected set; } 29 | } 30 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Models/VO/CQHttpServerConfigModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json; 3 | using Sora.Interfaces; 4 | using Sora.Net.Config; 5 | 6 | namespace OneBot.CommandRoute.Models.VO; 7 | 8 | public class CQHttpServerConfigModel 9 | { 10 | /// 模式 ws / reverse_ws 11 | [JsonProperty("Mode")] 12 | public string Mode { get; set; } = "reverse_ws"; 13 | 14 | /// 反向连接服务器监听地址 / 正向连接服务器目标地址 15 | [JsonProperty("Host")] 16 | public string Host { get; set; } = "127.0.0.1"; 17 | 18 | /// 反向服务器端口 19 | [JsonProperty("Port")] 20 | public ushort Port { get; set; } = 8080; 21 | 22 | /// 鉴权Token 23 | [JsonProperty("AccessToken")] 24 | public string AccessToken { get; set; } = ""; 25 | 26 | /// Universal请求路径 27 | [JsonProperty("UniversalPath")] 28 | public string UniversalPath { get; set; } = ""; 29 | 30 | /// 31 | /// 心跳包超时设置(秒) 32 | /// 此值请不要小于或等于客户端心跳包的发送间隔 33 | /// 34 | [JsonProperty("HeartBeatTimeOut")] 35 | public uint HeartBeatTimeOut { get; set; } = 10; 36 | 37 | /// 38 | /// 客户端API调用超时设置(毫秒) 39 | /// 默认为1000无需修改 40 | /// 41 | [JsonProperty("ApiTimeOut")] 42 | public uint ApiTimeOut { get; set; } = 1000; 43 | 44 | public ISoraConfig ToServiceConfig() 45 | { 46 | var mode = Mode.ToLower(); 47 | 48 | return mode switch 49 | { 50 | "reverse_ws" => new ServerConfig 51 | { 52 | Host = Host, 53 | Port = Port, 54 | AccessToken = AccessToken, 55 | UniversalPath = UniversalPath, 56 | HeartBeatTimeOut = TimeSpan.FromSeconds(HeartBeatTimeOut), 57 | ApiTimeOut = TimeSpan.FromMilliseconds(ApiTimeOut), 58 | EnableSoraCommandManager = false 59 | }, 60 | "ws" => new ClientConfig 61 | { 62 | Host = Host, 63 | Port = Port, 64 | AccessToken = AccessToken, 65 | UniversalPath = UniversalPath, 66 | HeartBeatTimeOut = TimeSpan.FromSeconds(HeartBeatTimeOut), 67 | ApiTimeOut = TimeSpan.FromMilliseconds(ApiTimeOut), 68 | EnableSoraCommandManager = false 69 | }, 70 | _ => throw new ArgumentException(@"There is something wrong in OneBot settings.") 71 | }; 72 | } 73 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/OneBotControllers/CQJsonRouterController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Newtonsoft.Json; 5 | using Newtonsoft.Json.Linq; 6 | using OneBot.CommandRoute.Models; 7 | using OneBot.CommandRoute.Services; 8 | using Sora.Entities.Segment; 9 | using Sora.Entities.Segment.DataModel; 10 | using Sora.Enumeration; 11 | using Sora.EventArgs.SoraEvent; 12 | 13 | namespace OneBot.CommandRoute.OneBotControllers; 14 | 15 | public class CQJsonRouterController : IOneBotController 16 | { 17 | /// 18 | /// 路由服务 19 | /// 20 | private readonly ICQJsonRouterService _routeService; 21 | 22 | public CQJsonRouterController(ICommandService commandService, IServiceProvider serviceProvider) 23 | { 24 | _routeService = null!; 25 | var routeService = serviceProvider.GetService(); 26 | if (routeService != null) 27 | { 28 | _routeService = routeService; 29 | commandService.Event.OnGroupMessageReceived += EventOnGroupMessageReceived; 30 | commandService.Event.OnPrivateMessageReceived += EventOnPrivateMessageReceived; 31 | } 32 | } 33 | 34 | private int EventOnGroupMessageReceived(OneBotContext scope) 35 | { 36 | var eventArgs = scope.WrapSoraEventArgs(); 37 | var p = eventArgs.Message.MessageBody.FirstOrDefault(p => p.MessageType == SegmentType.Json); 38 | return p == default ? 0 : UniversalProcess(scope, eventArgs, p); 39 | } 40 | 41 | private int EventOnPrivateMessageReceived(OneBotContext scope) 42 | { 43 | var eventArgs = scope.WrapSoraEventArgs(); 44 | var p = eventArgs.Message.MessageBody.FirstOrDefault(p => p.MessageType == SegmentType.Json); 45 | return p == default ? 0 : UniversalProcess(scope, eventArgs, p); 46 | } 47 | 48 | private int UniversalProcess(OneBotContext scope, BaseSoraEventArgs eventArgs, SoraSegment firstElement) 49 | { 50 | var process = false; 51 | var appid = ""; 52 | 53 | try 54 | { 55 | if (firstElement.MessageType == SegmentType.Json) 56 | { 57 | var jsonData = ((CodeSegment)firstElement.Data).Content; 58 | var jObject = JObject.Parse(jsonData); 59 | 60 | if (jObject.TryGetValue("app", out var jToken)) 61 | { 62 | // According to the signature of JObject.TryGetValue, 63 | // jToken is not null when TryGetValue returns true. 64 | appid = jToken.Value() ?? ""; 65 | process = true; 66 | } 67 | } 68 | } 69 | catch (JsonReaderException) 70 | { 71 | // JSON 格式出错 72 | } 73 | 74 | return process ? _routeService.Handle(scope, eventArgs, appid) : 0; 75 | } 76 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/IBotService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Sora.Interfaces; 3 | 4 | namespace OneBot.CommandRoute.Services; 5 | 6 | /// 7 | /// OneBot 客户端(Sora) 8 | /// 9 | public interface IBotService 10 | { 11 | /// 12 | /// Sora WS 服务 13 | /// 14 | ISoraService SoraService { get; } 15 | 16 | /// 17 | /// Sora WS 服务设置 18 | /// 19 | public ISoraConfig ServiceConfig { get; } 20 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/ICQJsonRouterService.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using OneBot.CommandRoute.Attributes; 3 | using OneBot.CommandRoute.Models; 4 | using Sora.EventArgs.SoraEvent; 5 | 6 | namespace OneBot.CommandRoute.Services; 7 | 8 | /// 9 | /// CQJson 路由服务 10 | /// 11 | public interface ICQJsonRouterService 12 | { 13 | /// 14 | /// 注册路由 15 | /// 16 | /// 17 | /// 18 | /// 19 | void Register(IOneBotController oneBotController, MethodInfo method, CQJsonAttribute attr); 20 | 21 | /// 22 | /// 处理事件 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | int Handle(OneBotContext scope, BaseSoraEventArgs eventArgs, string appid); 29 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/ICommandService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using OneBot.CommandRoute.Events; 4 | using OneBot.CommandRoute.Models; 5 | 6 | namespace OneBot.CommandRoute.Services; 7 | 8 | /// 9 | /// 指令路由服务 10 | /// 11 | public interface ICommandService 12 | { 13 | /// 14 | /// 事件管理器 15 | /// 16 | public EventManager Event { get; set; } 17 | 18 | /// 19 | /// 注册指令 20 | /// 21 | public void RegisterCommand(); 22 | 23 | /// 24 | /// 事件处理 25 | /// 26 | /// 27 | /// 28 | public ValueTask HandleEvent(OneBotContext oneBotContext); 29 | 30 | 31 | /// 32 | /// 异常处理 33 | /// 34 | /// 35 | /// 36 | public ValueTask EventOnException(OneBotContext oneBotContext, Exception exception); 37 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/IEventService.cs: -------------------------------------------------------------------------------- 1 | namespace OneBot.CommandRoute.Services; 2 | 3 | /// 4 | /// OneBot 事件服务 5 | /// 6 | public interface IEventService 7 | { 8 | /// 9 | /// 注册事件服务 10 | /// 11 | void RegisterEventHandler(); 12 | } 13 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/IOneBotContextHolder.cs: -------------------------------------------------------------------------------- 1 | using OneBot.CommandRoute.Models; 2 | 3 | namespace OneBot.CommandRoute.Services; 4 | 5 | /// 6 | /// OneBot 上下文持有器 7 | /// 8 | public interface IOneBotContextHolder 9 | { 10 | /// 11 | /// 获取 OneBot 上下文,若无则返回 Null。 12 | /// 13 | public OneBotContext? OneBotContext { get; } 14 | 15 | /// 16 | /// 获取 OneBot 上下文,若无则抛出错误。 17 | /// 18 | public OneBotContext RequireOneBotContext(); 19 | } 20 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/IOneBotController.cs: -------------------------------------------------------------------------------- 1 | namespace OneBot.CommandRoute.Services; 2 | 3 | /// 4 | /// OneBot 控制器 5 | /// 6 | public interface IOneBotController 7 | { 8 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/IOneBotMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using OneBot.CommandRoute.Models; 3 | 4 | namespace OneBot.CommandRoute.Services; 5 | 6 | /// 7 | /// OneBot 中间件 8 | /// 9 | public interface IOneBotMiddleware 10 | { 11 | /// 12 | /// OneBot 中间件处理 13 | /// 14 | /// OneBot 事件上下文 15 | /// 下一步 16 | /// 17 | public ValueTask Invoke(OneBotContext oneBotContext, OneBotRequestDelegate next); 18 | } 19 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/BotService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Options; 4 | using OneBot.CommandRoute.Models.VO; 5 | using Sora; 6 | using Sora.Interfaces; 7 | using Sora.Net.Config; 8 | using YukariToolBox.LightLog; 9 | 10 | namespace OneBot.CommandRoute.Services.Implements; 11 | 12 | /// 13 | /// CQHTTP 客户端(Sora) 14 | /// 15 | public class BotService : IBotService 16 | { 17 | /// 18 | /// Sora WS 服务 19 | /// 20 | public ISoraService SoraService { get; } 21 | 22 | /// 23 | /// Sora WS 服务设置 24 | /// 25 | public ISoraConfig ServiceConfig { get; } 26 | 27 | public BotService(IOptions cqHttpServerConfigModel, IServiceProvider serviceProvider) 28 | { 29 | // 配置日志 30 | var logger = serviceProvider.GetService(); 31 | Log.LogConfiguration.DisableConsoleOutput(); 32 | if (logger != null) Log.LogConfiguration.AddLogService(logger); 33 | 34 | // 配置 CQHTTP Sora 35 | var cqHttpConfig = cqHttpServerConfigModel.Value; 36 | ServiceConfig = cqHttpConfig == null ? new ServerConfig() : cqHttpConfig.ToServiceConfig(); 37 | SoraService = SoraServiceFactory.CreateService(ServiceConfig); 38 | } 39 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/CQJsonRouterService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Reflection; 3 | using OneBot.CommandRoute.Attributes; 4 | using OneBot.CommandRoute.Models; 5 | using OneBot.CommandRoute.Models.Entities; 6 | using OneBot.CommandRoute.Models.Enumeration; 7 | using Sora.EventArgs.SoraEvent; 8 | 9 | namespace OneBot.CommandRoute.Services.Implements; 10 | 11 | class CQJsonRouterService : ICQJsonRouterService 12 | { 13 | private readonly SortedDictionary> _mapping; 14 | 15 | public CQJsonRouterService() 16 | { 17 | _mapping = new(); 18 | } 19 | 20 | /// 21 | /// 注册一个路由 22 | /// 23 | /// 24 | /// 25 | /// 26 | public void Register(IOneBotController oneBotController, MethodInfo method, CQJsonAttribute attr) 27 | { 28 | var mappingObj = new CQJsonRouteModel(oneBotController, method, attr); 29 | if (!_mapping.TryGetValue(attr.AppId, out var list)) 30 | { 31 | list = new(); 32 | _mapping[attr.AppId] = list; 33 | } 34 | list.Add(mappingObj); 35 | } 36 | 37 | /// 38 | /// 处理 39 | /// 40 | /// 41 | /// 42 | /// 43 | /// 44 | public int Handle(OneBotContext scope, BaseSoraEventArgs eventArgs, string appid) 45 | { 46 | if (!_mapping.TryGetValue(appid, out var list)) return 0; 47 | foreach (var mappingObj in list) 48 | { 49 | switch (eventArgs) 50 | { 51 | // 检查事件类型是否正确 52 | case PrivateMessageEventArgs when (mappingObj.Attribute.EventType & EventType.PrivateMessage) == 0: 53 | case GroupMessageEventArgs when (mappingObj.Attribute.EventType & EventType.GroupMessage) == 0: 54 | continue; 55 | } 56 | 57 | if (mappingObj.Invoke(scope, eventArgs) != 0) return 1; 58 | } 59 | return 0; 60 | } 61 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/CommandService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Logging; 3 | using OneBot.CommandRoute.Attributes; 4 | using OneBot.CommandRoute.Command; 5 | using OneBot.CommandRoute.Events; 6 | using OneBot.CommandRoute.Models.Entities; 7 | using Sora.EventArgs.SoraEvent; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Reflection; 12 | using System.Threading.Tasks; 13 | using OneBot.CommandRoute.Configuration; 14 | using OneBot.CommandRoute.Models; 15 | 16 | namespace OneBot.CommandRoute.Services.Implements; 17 | 18 | /// 19 | /// 指令路由服务 20 | /// 21 | public class CommandService : ICommandService 22 | { 23 | /// 24 | /// 服务容器 25 | /// 26 | private readonly IServiceProvider _serviceProvider; 27 | 28 | /// 29 | /// 指令匹配树根节点 30 | /// 31 | private readonly MatchingNode _matchingRootNode; 32 | 33 | /// 34 | /// 日志 35 | /// 36 | private readonly ILogger _logger; 37 | 38 | /// 39 | /// CQ:Json 路由 40 | /// 41 | private readonly ICQJsonRouterService? _jsonRouterService; 42 | 43 | /// 44 | /// 事件中心 45 | /// 46 | public EventManager Event { get; set; } 47 | 48 | public CommandService(IServiceProvider serviceProvider, ILogger logger) 49 | { 50 | _serviceProvider = serviceProvider; 51 | _jsonRouterService = _serviceProvider.GetService(); 52 | _logger = logger; 53 | Event = new EventManager(); 54 | 55 | var routeConfiguration = serviceProvider.GetService() ?? 56 | new DefaultOneBotCommandRouteConfiguration(); 57 | _matchingRootNode = new MatchingNode(routeConfiguration) { IsRoot = true }; 58 | } 59 | 60 | public async ValueTask HandleEvent(OneBotContext oneBotContext) 61 | { 62 | var eventArgs = oneBotContext.SoraEventArgs; 63 | 64 | // ReSharper disable once ConvertIfStatementToSwitchStatement 65 | // ReSharper disable once ConvertIfStatementToSwitchExpression 66 | if (eventArgs is GroupMessageEventArgs groupMessageEventArgs) 67 | { 68 | // ReSharper disable once ConvertIfStatementToSwitchStatement 69 | // ReSharper disable once ConvertIfStatementToReturnStatement 70 | if (groupMessageEventArgs.SenderInfo.UserId == groupMessageEventArgs.LoginUid) 71 | { 72 | await EventOnSelfGroupMessage(oneBotContext); 73 | } 74 | else 75 | { 76 | await EventOnGroupMessage(oneBotContext); 77 | } 78 | } 79 | else if (eventArgs is PrivateMessageEventArgs privateMessageEventArgs) 80 | { 81 | if (privateMessageEventArgs.SenderInfo.UserId == privateMessageEventArgs.LoginUid) 82 | { 83 | await EventOnSelfPrivateMessage(oneBotContext); 84 | } 85 | else 86 | { 87 | await EventOnPrivateMessage(oneBotContext); 88 | } 89 | } 90 | else 91 | { 92 | await OnGeneralEvent(oneBotContext); 93 | } 94 | } 95 | 96 | #region 事件处理 97 | 98 | /// 99 | /// 登录账号发送消息事件(群聊) 100 | /// 101 | /// 102 | /// 103 | private ValueTask EventOnSelfGroupMessage(OneBotContext oneBotContext) 104 | { 105 | try 106 | { 107 | Event.FireSelfGroupMessage(oneBotContext); 108 | return ValueTask.CompletedTask; 109 | } 110 | catch (Exception e1) 111 | { 112 | return EventOnException(oneBotContext, e1); 113 | } 114 | } 115 | 116 | /// 117 | /// 登录账号发送消息事件(私聊) 118 | /// 119 | /// 120 | /// 121 | private ValueTask EventOnSelfPrivateMessage(OneBotContext oneBotContext) 122 | { 123 | try 124 | { 125 | Event.FireSelfPrivateMessage(oneBotContext); 126 | return ValueTask.CompletedTask; 127 | } 128 | catch (Exception e1) 129 | { 130 | return EventOnException(oneBotContext, e1); 131 | } 132 | } 133 | 134 | /// 135 | /// 异常处理 136 | /// 137 | /// 138 | /// 139 | public ValueTask EventOnException(OneBotContext oneBotContext, Exception exception) 140 | { 141 | try 142 | { 143 | if (!Event.FireException(oneBotContext, exception)) 144 | { 145 | _logger.LogError(exception, "{exception}", exception.Message); 146 | } 147 | } 148 | catch (Exception e1) 149 | { 150 | _logger.LogError(exception, "{exception}", exception.Message); 151 | _logger.LogError(e1, "{e1}", e1.Message); 152 | } 153 | return ValueTask.CompletedTask; 154 | } 155 | 156 | /// 157 | /// 通用事件 158 | /// 159 | /// 160 | /// 161 | private ValueTask OnGeneralEvent(OneBotContext oneBotContext) 162 | { 163 | try 164 | { 165 | Event.Fire(oneBotContext); 166 | return ValueTask.CompletedTask; 167 | } 168 | catch (Exception e1) 169 | { 170 | return EventOnException(oneBotContext, e1); 171 | } 172 | } 173 | 174 | #endregion 事件处理 175 | 176 | #region 指令路由 177 | 178 | /// 179 | /// 私聊消息分发 180 | /// 181 | /// 182 | /// 183 | private ValueTask EventOnPrivateMessage(OneBotContext oneBotContext) 184 | { 185 | try 186 | { 187 | if (Event.FirePrivateMessageReceived(oneBotContext) != 0) return ValueTask.CompletedTask; 188 | if (_matchingRootNode.ProcessingCommandMapping(oneBotContext) != 0) return ValueTask.CompletedTask; 189 | Event.Fire(oneBotContext); 190 | return ValueTask.CompletedTask; 191 | } 192 | catch (Exception e1) 193 | { 194 | return EventOnException(oneBotContext, e1); 195 | } 196 | } 197 | 198 | /// 199 | /// 群聊消息分发 200 | /// 201 | /// 202 | /// 203 | private ValueTask EventOnGroupMessage(OneBotContext oneBotContext) 204 | { 205 | try 206 | { 207 | if (Event.FireGroupMessageReceived(oneBotContext) != 0) return ValueTask.CompletedTask; 208 | if (_matchingRootNode.ProcessingCommandMapping(oneBotContext) != 0) return ValueTask.CompletedTask; 209 | Event.Fire(oneBotContext); 210 | return ValueTask.CompletedTask; 211 | } 212 | catch (Exception e1) 213 | { 214 | return EventOnException(oneBotContext, e1); 215 | } 216 | } 217 | 218 | #endregion 指令路由 219 | 220 | #region 注册指令 221 | 222 | /// 223 | /// 注册指令 224 | /// 225 | public void RegisterCommand() 226 | { 227 | var onebotController = _serviceProvider.GetServices(); 228 | foreach (var s in onebotController) 229 | { 230 | var clazz = s.GetType(); 231 | var methods = clazz.GetMethods(); 232 | foreach (var method in methods) 233 | { 234 | if (Attribute.IsDefined(method, typeof(CommandAttribute))) 235 | { 236 | var attr = Attribute.GetCustomAttribute(method, typeof(CommandAttribute)) as CommandAttribute; 237 | RegisterCommand(s, method, attr!); 238 | } 239 | 240 | if (Attribute.IsDefined(method, typeof(CQJsonAttribute))) 241 | { 242 | if (_jsonRouterService == null) 243 | { 244 | _logger.LogWarning("检测到 CQ:Json 路由功能已被关闭,但依然有方法使用了 [CQJson]。{clazz.FullName}::{method.Name}", clazz.FullName, method.Name); 245 | } 246 | else 247 | { 248 | var attr = Attribute.GetCustomAttribute(method, typeof(CQJsonAttribute)) as CQJsonAttribute; 249 | _jsonRouterService.Register(s, method, attr!); 250 | _logger.LogDebug("成功添加 CQ:Json :{attr.AppId}\r\n{clazz.FullName}::{method.Name}", attr!.AppId,clazz.FullName, method.Name); 251 | } 252 | } 253 | } 254 | } 255 | } 256 | 257 | /// 258 | /// 将 [Command] 中的 pattern 和 alias 拆解为多个 pattern。 259 | /// 260 | /// 261 | /// 262 | /// 263 | private void RegisterCommand(IOneBotController commandObj, MethodInfo commandMethod, CommandAttribute attribute) 264 | { 265 | List command = attribute.Pattern.Trim().Split(' ').ToList(); 266 | List aliasList = attribute.Alias.Select(s => s.Trim()).Where(s => s.Length > 0) 267 | .ToList(); 268 | 269 | try 270 | { 271 | RegisterCommand(commandObj, commandMethod, command, attribute); 272 | } 273 | catch (ArgumentException e) 274 | { 275 | _logger.LogError(e, "{e.Message}", e.Message); 276 | } 277 | 278 | foreach (var c in aliasList.Select(s => s.Split(' ').ToList())) 279 | { 280 | try 281 | { 282 | RegisterCommand(commandObj, commandMethod, c, attribute); 283 | } 284 | catch (ArgumentException e) 285 | { 286 | _logger.LogError(e, "{e.Message}", e.Message); 287 | } 288 | } 289 | } 290 | 291 | /// 292 | /// 将 pattern 拆解为多个参数。 293 | /// 294 | /// 295 | /// 296 | /// 297 | /// 298 | /// 299 | private void RegisterCommand(IOneBotController commandObj, MethodInfo commandMethod, List matchPattern, 300 | CommandAttribute attribute) 301 | { 302 | // 参数类型 303 | List parametersType = new List(); 304 | 305 | // 参数匹配类型:0全字匹配 1参数 2可选参数 306 | List parametersMatchingType = new List(); 307 | 308 | // 被全字匹配的字符串或参数名 309 | List parametersName = new List(); 310 | 311 | // 这个参数是否被用过了 312 | List parametersUsed = new List(); 313 | 314 | // 这个参数对应函数的形参列表哪一位。负数表示不映射。 315 | List parameterPositionMapping = new List(); 316 | 317 | // 从指令定义中解析出 参数匹配类型 和 参数匹配字符串或参数名 318 | var withOptional = false; 319 | foreach (var s in matchPattern) 320 | { 321 | parametersType.Add(typeof(string)); 322 | parametersUsed.Add(false); 323 | parameterPositionMapping.Add(-1); 324 | 325 | // 必选参数 326 | if (s.StartsWith("<") && s.EndsWith(">")) 327 | { 328 | if (withOptional) 329 | { 330 | throw new ArgumentException($"我觉得你的指令定义有问题。可选参数只能写在末尾哦。"); 331 | } 332 | 333 | parametersMatchingType.Add(1); 334 | var paraName = s.Substring(1, s.Length - 2); 335 | for (var j = 0; j < parametersName.Count; j++) 336 | { 337 | if (parametersMatchingType[j] == 0) continue; 338 | if (parametersName[j] == paraName) 339 | { 340 | throw new ArgumentException($"我觉得你的指令定义有问题。参数名必须互异。"); 341 | } 342 | } 343 | 344 | parametersName.Add(paraName); 345 | continue; 346 | } 347 | 348 | // 可选参数 349 | if (s.StartsWith("[") && s.EndsWith("]")) 350 | { 351 | withOptional = true; 352 | parametersMatchingType.Add(2); 353 | var paraName = s.Substring(1, s.Length - 2); 354 | for (var j = 0; j < parametersName.Count; j++) 355 | { 356 | if (parametersMatchingType[j] == 0) continue; 357 | if (parametersName[j] == paraName) 358 | { 359 | throw new ArgumentException($"我觉得你的指令定义有问题。参数名必须互异。"); 360 | } 361 | } 362 | 363 | parametersName.Add(paraName); 364 | continue; 365 | } 366 | 367 | // 全字匹配 368 | if (withOptional) 369 | { 370 | throw new ArgumentException($"我觉得你的指令定义有问题。可选参数只能写在末尾哦。"); 371 | } 372 | 373 | parametersMatchingType.Add(0); 374 | parametersName.Add(s); 375 | // ReSharper disable once RedundantJumpStatement 376 | continue; 377 | } 378 | 379 | // 先检查属性 380 | var functionParametersList = commandMethod.GetParameters(); 381 | for (var i = 0; i < functionParametersList.Length; i++) 382 | { 383 | var type = functionParametersList[i]; 384 | if (Attribute.IsDefined(type, typeof(CommandParameterAttribute))) 385 | { 386 | var attr = Attribute.GetCustomAttribute(type, typeof(CommandParameterAttribute)) as CommandParameterAttribute; 387 | #pragma warning disable 8602 388 | var paraName = attr.Name; 389 | #pragma warning restore 8602 390 | 391 | var idx = -1; 392 | for (var j = 0; j < parametersName.Count; j++) 393 | { 394 | if (parametersMatchingType[j] == 0) continue; 395 | if (parametersName[j] != paraName) continue; 396 | 397 | idx = j; 398 | break; 399 | } 400 | 401 | if (idx < 0) 402 | { 403 | throw new ArgumentException($"我觉得你的指令定义有问题。在指令定义中找不到参数名为 {paraName} 的参数。"); 404 | } 405 | 406 | parametersType[idx] = type.ParameterType; 407 | parametersUsed[idx] = true; 408 | parameterPositionMapping[idx] = i; 409 | } 410 | } 411 | 412 | 413 | // 再检查形参参数名 414 | for (var i = 0; i < parametersName.Count; i++) 415 | { 416 | if (parametersUsed[i]) continue; 417 | if (parametersMatchingType[i] == 0) continue; 418 | 419 | var paraName = parametersName[i]; 420 | 421 | for (var j = 0; j < functionParametersList.Length; j++) 422 | { 423 | var type = functionParametersList[j]; 424 | if (type.Name == paraName) 425 | { 426 | parametersType[i] = type.ParameterType; 427 | parametersUsed[i] = true; 428 | parameterPositionMapping[i] = j; 429 | } 430 | } 431 | } 432 | 433 | _matchingRootNode.Register( 434 | new CommandModel(commandObj, commandMethod, 435 | parametersType, parametersMatchingType, parametersName, parameterPositionMapping, 436 | attribute) 437 | , 0); 438 | _logger.LogDebug("成功添加指令:{matchPattern}\r\n{commandType}::{commandMethod}", 439 | string.Join(", ", matchPattern.ToArray()), commandObj.GetType().FullName, commandMethod.Name); 440 | } 441 | 442 | #endregion 注册指令 443 | } 444 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/EventService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Immutable; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Logging; 8 | using OneBot.CommandRoute.Models.Entities; 9 | using Sora.EventArgs.SoraEvent; 10 | 11 | namespace OneBot.CommandRoute.Services.Implements; 12 | 13 | /// 14 | /// 事件服务 15 | /// 16 | public class EventService : IEventService 17 | { 18 | /// 19 | /// 机器人服务 20 | /// 21 | private readonly IBotService _bot; 22 | 23 | /// ` 24 | /// 服务容器 25 | /// 26 | // ReSharper disable once NotAccessedField.Local 27 | private readonly IServiceProvider _serviceProvider; 28 | 29 | /// 30 | /// Scope 工厂 31 | /// 32 | private readonly IServiceScopeFactory _scopeFactory; 33 | 34 | /// 35 | /// 日志 36 | /// 37 | // ReSharper disable once NotAccessedField.Local 38 | private ILogger _logger; 39 | 40 | /// 41 | /// 指令路由服务 42 | /// 43 | private readonly ICommandService _commandService; 44 | 45 | /// 46 | /// 事件源 47 | /// 48 | private readonly ActivitySource _eventActivitySource = new ActivitySource("OneBot.Event", Assembly.GetExecutingAssembly().GetName().Version!.ToString()); 49 | 50 | /// 51 | /// 中间件源 52 | /// 53 | private readonly ActivitySource _middlewareActivitySource = new ActivitySource("OneBot.Middleware", Assembly.GetExecutingAssembly().GetName().Version!.ToString()); 54 | 55 | public EventService(IBotService bot, IServiceProvider serviceProvider, IServiceScopeFactory scopeFactory, 56 | ILogger logger, ICommandService commandService) 57 | { 58 | _bot = bot; 59 | _serviceProvider = serviceProvider; 60 | _scopeFactory = scopeFactory; 61 | _logger = logger; 62 | _commandService = commandService; 63 | } 64 | 65 | public void RegisterEventHandler() 66 | { 67 | _bot.SoraService.Event.OnClientConnect += (sender, e) => 68 | { 69 | return OnGeneralEvent(sender, e, activity => 70 | { 71 | activity.AddTag("onebot.client_type", e.ClientType) 72 | .AddTag("onebot.client_version_code", e.ClientVersionCode); 73 | }); 74 | }; 75 | _bot.SoraService.Event.OnGroupRequest += (sender, e) => 76 | { 77 | return OnGeneralEvent(sender, e, activity => 78 | { 79 | activity.AddTag("onebot.comment", e.Comment) 80 | .AddTag("onebot.sender_id", e.Sender.Id) 81 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 82 | .AddTag("onebot.sub_type", e.SubType); 83 | }); 84 | }; 85 | _bot.SoraService.Event.OnFriendRequest += (sender, e) => 86 | { 87 | return OnGeneralEvent(sender, e, activity => 88 | { 89 | activity.AddTag("onebot.comment", e.Comment) 90 | .AddTag("onebot.sender_id", e.Sender.Id); 91 | }); 92 | }; 93 | _bot.SoraService.Event.OnFileUpload += (sender, e) => 94 | { 95 | return OnGeneralEvent(sender, e, activity => 96 | { 97 | activity.AddTag("onebot.sender_id", e.Sender.Id) 98 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 99 | .AddTag("onebot.file_info.file_id", e.FileInfo.FileId) 100 | .AddTag("onebot.file_info.name", e.FileInfo.Name) 101 | .AddTag("onebot.file_info.size", e.FileInfo.Size) 102 | .AddTag("onebot.file_info.bus_id", e.FileInfo.Busid); 103 | }); 104 | }; 105 | _bot.SoraService.Event.OnGroupAdminChange += (sender, e) => 106 | { 107 | return OnGeneralEvent(sender, e, activity => 108 | { 109 | activity.AddTag("onebot.sender_id", e.Sender.Id) 110 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 111 | .AddTag("onebot.sub_type", e.SubType); 112 | }); 113 | }; 114 | _bot.SoraService.Event.OnGroupMemberChange += (sender, e) => 115 | { 116 | return OnGeneralEvent(sender, e, activity => 117 | { 118 | activity.AddTag("onebot.operator_id", e.Operator.Id) 119 | .AddTag("onebot.change_user_id", e.ChangedUser.Id) 120 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 121 | .AddTag("onebot.sub_type", e.SubType); 122 | }); 123 | }; 124 | _bot.SoraService.Event.OnGroupMemberMute += (sender, e) => 125 | { 126 | return OnGeneralEvent(sender, e, activity => 127 | { 128 | activity.AddTag("onebot.operator_id", e.Operator.Id) 129 | .AddTag("onebot.user_id", e.User.Id) 130 | .AddTag("onebot.source_group_id", e.SourceGroup.Id); 131 | }); 132 | }; 133 | _bot.SoraService.Event.OnFriendAdd += (sender, e) => 134 | { 135 | return OnGeneralEvent(sender, e, activity => 136 | { 137 | activity.AddTag("onebot.new_friend_id", e.NewFriend.Id); 138 | }); 139 | }; 140 | _bot.SoraService.Event.OnGroupRecall += (sender, e) => 141 | { 142 | return OnGeneralEvent(sender, e, activity => 143 | { 144 | activity.AddTag("onebot.operator_id", e.Operator.Id) 145 | .AddTag("onebot.message_sender_id", e.MessageSender.Id) 146 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 147 | .AddTag("onebot.message_id", e.MessageId); 148 | }); 149 | }; 150 | _bot.SoraService.Event.OnFriendRecall += (sender, e) => 151 | { 152 | return OnGeneralEvent(sender, e, activity => 153 | { 154 | activity.AddTag("onebot.sender_id", e.Sender.Id) 155 | .AddTag("onebot.message_id", e.MessageId); 156 | }); 157 | }; 158 | _bot.SoraService.Event.OnGroupCardUpdate += (sender, e) => 159 | { 160 | return OnGeneralEvent(sender, e, activity => 161 | { 162 | activity.AddTag("onebot.user_id", e.User.Id) 163 | .AddTag("onebot.new_card", e.NewCard) 164 | .AddTag("onebot.old_card", e.OldCard) 165 | .AddTag("onebot.source_group_id", e.SourceGroup.Id); 166 | }); 167 | }; 168 | _bot.SoraService.Event.OnGroupPoke += (sender, e) => 169 | { 170 | return OnGeneralEvent(sender, e, activity => 171 | { 172 | activity.AddTag("onebot.send_user_id", e.SendUser.Id) 173 | .AddTag("onebot.target_user_id", e.TargetUser.Id) 174 | .AddTag("onebot.source_group_id", e.SourceGroup.Id); 175 | }); 176 | }; 177 | _bot.SoraService.Event.OnLuckyKingEvent += (sender, e) => 178 | { 179 | return OnGeneralEvent(sender, e, activity => 180 | { 181 | activity.AddTag("onebot.send_user_id", e.SendUser.Id) 182 | .AddTag("onebot.target_user_id", e.TargetUser.Id) 183 | .AddTag("onebot.source_group_id", e.SourceGroup.Id); 184 | }); 185 | }; 186 | _bot.SoraService.Event.OnHonorEvent += (sender, e) => 187 | { 188 | return OnGeneralEvent(sender, e, activity => 189 | { 190 | activity.AddTag("onebot.honor", e.Honor) 191 | .AddTag("onebot.target_user_id", e.TargetUser.Id) 192 | .AddTag("onebot.source_group_id", e.SourceGroup.Id); 193 | }); 194 | }; 195 | _bot.SoraService.Event.OnTitleUpdate += (sender, e) => 196 | { 197 | return OnGeneralEvent(sender, e, activity => 198 | { 199 | activity.AddTag("onebot.new_title", e.NewTitle) 200 | .AddTag("onebot.target_user_id", e.TargetUser.Id); 201 | }); 202 | }; 203 | _bot.SoraService.Event.OnOfflineFileEvent += (sender, e) => 204 | { 205 | return OnGeneralEvent(sender, e, activity => 206 | { 207 | activity.AddTag("onebot.sender_id", e.Sender.Id) 208 | .AddTag("onebot.offline_file_info.name", e.OfflineFileInfo.Name) 209 | .AddTag("onebot.offline_file_info.size", e.OfflineFileInfo.Size) 210 | .AddTag("onebot.offline_file_info.url", e.OfflineFileInfo.Url); 211 | }); 212 | }; 213 | _bot.SoraService.Event.OnClientStatusChangeEvent += (sender, e) => 214 | { 215 | return OnGeneralEvent(sender, e, activity => 216 | { 217 | activity.AddTag("onebot.online", e.Online); 218 | }); 219 | }; 220 | _bot.SoraService.Event.OnEssenceChange += (sender, e) => 221 | { 222 | return OnGeneralEvent(sender, e, activity => 223 | { 224 | activity.AddTag("onebot.operator_id", e.Operator.Id) 225 | .AddTag("onebot.sender_id", e.Sender.Id) 226 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 227 | .AddTag("onebot.message_id", e.MessageId) 228 | .AddTag("onebot.essence_change_type", e.EssenceChangeType); 229 | }); 230 | }; 231 | 232 | _bot.SoraService.Event.OnGroupMessage += (sender, e) => OnGeneralEvent(sender, e, GroupMessageActivityExtensionFactory(e)); 233 | _bot.SoraService.Event.OnPrivateMessage += (sender, e) => OnGeneralEvent(sender, e, PrivateMessageActivityExtensionFactory(e)); 234 | 235 | _bot.SoraService.Event.OnSelfGroupMessage += (sender, e) => OnGeneralEvent(sender, e, GroupMessageActivityExtensionFactory(e)); 236 | _bot.SoraService.Event.OnSelfPrivateMessage += (sender, e) => OnGeneralEvent(sender, e, PrivateMessageActivityExtensionFactory(e)); 237 | } 238 | 239 | private Action GroupMessageActivityExtensionFactory(GroupMessageEventArgs e) 240 | { 241 | return activity => 242 | { 243 | activity.AddTag("onebot.is_anonymous_message", e.IsAnonymousMessage); 244 | 245 | if (e.Anonymous != null) 246 | { 247 | activity.AddTag("onebot.anonymous.id", e.Anonymous.Id) 248 | .AddTag("onebot.anonymous.name", e.Anonymous.Name); 249 | } 250 | 251 | activity.AddTag("onebot.sender_id", e.Sender.Id) 252 | .AddTag("onebot.source_group_id", e.SourceGroup.Id) 253 | .AddTag("onebot.message", e.Message.RawText); 254 | }; 255 | } 256 | 257 | private Action PrivateMessageActivityExtensionFactory(PrivateMessageEventArgs e) 258 | { 259 | return activity => 260 | { 261 | activity.AddTag("onebot.sender_id", e.Sender.Id) 262 | .AddTag("onebot.message", e.Message.RawText); 263 | }; 264 | } 265 | 266 | /// 267 | /// 通用事件 268 | /// 269 | /// 270 | /// 271 | /// 272 | /// 273 | private async ValueTask OnGeneralEvent(object sender, BaseSoraEventArgs e, Action activityExtension) 274 | { 275 | using var scope = _scopeFactory.CreateScope(); 276 | 277 | var operationName = e.EventName ?? e.GetType().FullName ?? "OneBot-Event"; 278 | var activity = _eventActivitySource.CreateActivity(operationName, ActivityKind.Server) ?? new Activity(operationName); 279 | activity.Start(); 280 | activity.AddTag("onebot.type", e.EventName); 281 | activity.AddTag("onebot.source_type", e.SourceType); 282 | activity.AddTag("onebot.login_uid", e.LoginUid); 283 | activityExtension(activity); 284 | 285 | var ctx = new OneBotContextDefault(); 286 | ctx.SetSoraEventSender(sender); 287 | ctx.SetSoraEventArgs(e); 288 | ctx.SoraServiceScope(scope); 289 | 290 | var ctxHolder = scope.ServiceProvider.GetService(); 291 | if (ctxHolder is OneBotContextHolder holder) 292 | { 293 | holder.SetOneBotContext(ctx); 294 | } 295 | 296 | var middleware = scope.ServiceProvider.GetServices().ToImmutableArray(); 297 | var count = middleware.Length; 298 | 299 | OneBotRequestDelegate entry = async context => 300 | { 301 | const string middleOperationName = "OneBot.CommandRoute"; 302 | var middlewareActivity = _middlewareActivitySource.CreateActivity(middleOperationName, ActivityKind.Server) ?? new Activity(middleOperationName); 303 | middlewareActivity.Start(); 304 | await _commandService.HandleEvent(context); 305 | middlewareActivity.Stop(); 306 | }; 307 | 308 | for (int i = count - 1; i >= 0; i--) 309 | { 310 | var idx = i; 311 | var realEntry = entry; 312 | entry = async context => 313 | { 314 | var middleOperationName = middleware[idx].GetType().FullName ?? "?"; 315 | var middlewareActivity = _middlewareActivitySource.CreateActivity(middleOperationName, ActivityKind.Server) ?? new Activity(middleOperationName); 316 | middlewareActivity.Start(); 317 | await middleware[idx].Invoke(context, realEntry); 318 | middlewareActivity.Stop(); 319 | }; 320 | } 321 | 322 | try 323 | { 324 | await entry(ctx); 325 | } 326 | catch (Exception ex) 327 | { 328 | await _commandService.EventOnException(ctx, ex); 329 | } 330 | 331 | activity.Stop(); 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/OneBotContextHolder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using OneBot.CommandRoute.Models; 3 | 4 | namespace OneBot.CommandRoute.Services.Implements; 5 | 6 | public class OneBotContextHolder : IOneBotContextHolder 7 | { 8 | public OneBotContext? OneBotContext { get; private set; } 9 | 10 | internal void SetOneBotContext(OneBotContext context) 11 | { 12 | OneBotContext = context; 13 | } 14 | 15 | public OneBotContext RequireOneBotContext() 16 | { 17 | if (OneBotContext == null) 18 | { 19 | throw new NullReferenceException( 20 | @"找不到 OneBotContext 对象。 21 | 如果您确认您确实是在 OneBot 上下文中使用本 Holder 的话, 22 | 出现这个错误是因为 OneBotContextHolder 实例化时间早于 OneBotContext, 23 | 导致在早于 OneBot 上下文产生之前就使用这个函数(比如说在 24 | 构造函数注入时就使用)就会出现这个错误。可以考虑换为收到 25 | 了 OneBot 事件之后(比如已经在处理事件了的时候)再取。" 26 | ); 27 | } 28 | return OneBotContext; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/OneBotHostedService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Microsoft.Extensions.Hosting; 4 | 5 | namespace OneBot.CommandRoute.Services.Implements; 6 | 7 | public class OneBotHostedService: IHostedService 8 | { 9 | private readonly ICommandService _commandService; 10 | 11 | private readonly IEventService _eventService; 12 | 13 | private readonly IBotService _botService; 14 | 15 | public OneBotHostedService(ICommandService commandService, IEventService eventService, IBotService botService) 16 | { 17 | _commandService = commandService; 18 | _eventService = eventService; 19 | _botService = botService; 20 | } 21 | 22 | public async Task StartAsync(CancellationToken cancellationToken) 23 | { 24 | // 初始化指令系统 25 | _commandService.RegisterCommand(); 26 | 27 | // 初始化事件系统 28 | _eventService.RegisterEventHandler(); 29 | 30 | // 启动 CQHTTP 31 | await _botService.SoraService.StartService(); 32 | } 33 | 34 | public Task StopAsync(CancellationToken cancellationToken) 35 | { 36 | return Task.CompletedTask; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/Implements/OneBotServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting.Server; 6 | using Microsoft.AspNetCore.Http.Features; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Microsoft.Extensions.Hosting; 9 | 10 | namespace OneBot.CommandRoute.Services.Implements; 11 | 12 | public class OneBotServer : IServer 13 | { 14 | private readonly ICommandService _commandService; 15 | 16 | private readonly IEventService _eventService; 17 | 18 | private readonly IBotService _botService; 19 | 20 | private readonly IServiceProvider _serviceProvider; 21 | 22 | public OneBotServer(ICommandService commandService, IEventService eventService, IBotService botService, IServiceProvider serviceProvider) 23 | { 24 | _commandService = commandService; 25 | _eventService = eventService; 26 | _botService = botService; 27 | _serviceProvider = serviceProvider; 28 | } 29 | 30 | public void Dispose() 31 | { 32 | 33 | } 34 | 35 | public async Task StartAsync(IHttpApplication application, CancellationToken cancellationToken) where TContext : notnull 36 | { 37 | var hostedServices = _serviceProvider.GetServices(); 38 | if (hostedServices.Any(s => s.GetType() == typeof(OneBotHostedService))) 39 | { 40 | return; 41 | } 42 | 43 | // 初始化指令系统 44 | _commandService.RegisterCommand(); 45 | 46 | // 初始化事件系统 47 | _eventService.RegisterEventHandler(); 48 | 49 | // 启动 CQHTTP 50 | await _botService.SoraService.StartService(); 51 | } 52 | 53 | public Task StopAsync(CancellationToken cancellationToken) 54 | { 55 | return Task.CompletedTask; 56 | } 57 | 58 | public IFeatureCollection Features { get; } = new FeatureCollection(); 59 | } 60 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Services/OneBotRequestDelegate.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using OneBot.CommandRoute.Models; 3 | 4 | namespace OneBot.CommandRoute.Services; 5 | 6 | /// 7 | /// OneBot 拦截器传递对象,在 OneBot 中间件中直接调用表示将该时间传递给下一层处理。 8 | /// 9 | public delegate ValueTask OneBotRequestDelegate(OneBotContext context); 10 | -------------------------------------------------------------------------------- /OneBot-CommandRoute/CommandRoute/Utils/YukariToolBoxLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Diagnostics; 4 | using System.Globalization; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Threading; 8 | using Microsoft.Extensions.Logging; 9 | using YukariToolBox.LightLog; 10 | 11 | namespace OneBot.CommandRoute.Utils; 12 | 13 | public class YukariToolBoxLogger : ILogService 14 | { 15 | private readonly ILoggerFactory _loggerFactory; 16 | 17 | private readonly ILogger _logger; 18 | 19 | private readonly ConcurrentDictionary _loggerMap = new ConcurrentDictionary(); 20 | 21 | public YukariToolBoxLogger(ILoggerFactory loggerFactory, ILogger logger) 22 | { 23 | _loggerFactory = loggerFactory; 24 | _logger = logger; 25 | } 26 | 27 | private ILogger GetLogger() 28 | { 29 | StackTrace trace = new StackTrace(); 30 | StackFrame? frame = trace.GetFrame(3); 31 | if (frame == null) 32 | { 33 | return _logger; 34 | } 35 | 36 | MethodBase? logMethod = frame.GetMethod(); 37 | if (logMethod == null) 38 | { 39 | return _logger; 40 | } 41 | 42 | Type? logType = logMethod.ReflectedType; 43 | if (logType == null) 44 | { 45 | return _logger; 46 | } 47 | 48 | return _loggerMap.GetOrAdd(logType, s => _loggerFactory.CreateLogger(s)); 49 | } 50 | 51 | 52 | public void Info(string source, string message) 53 | { 54 | GetLogger().LogInformation("[{source}] {message}", source, message); 55 | } 56 | 57 | public void Info(string source, string message, T context) 58 | { 59 | GetLogger().LogInformation("[{source}] {message} {context}", source, message, context); 60 | } 61 | 62 | public void Warning(string source, string message) 63 | { 64 | GetLogger().LogWarning("[{source}] {message}", source, message); 65 | } 66 | 67 | public void Warning(string source, string message, T context) 68 | { 69 | GetLogger().LogWarning("[{source}] {message} {context}", source, message, context); 70 | } 71 | 72 | public void Error(string source, string message) 73 | { 74 | GetLogger().LogError("[{source}] {message}", source, message); 75 | } 76 | 77 | public void Error(Exception exception, string source, string message) 78 | { 79 | GetLogger().LogError(exception, "[{source}] {message}", source, message); 80 | } 81 | 82 | public void Error(string source, string message, T context) 83 | { 84 | GetLogger().LogError("[{source}] {message} {context}", source, message, context); 85 | } 86 | 87 | public void Error(Exception exception, string source, string message, T context) 88 | { 89 | GetLogger().LogError(exception, "[{source}] {message} {context}", source, message, context); 90 | } 91 | 92 | public void Fatal(Exception exception, string source, string message) 93 | { 94 | GetLogger().LogCritical(exception, "[{source}] {message}", source, message); 95 | } 96 | 97 | public void Fatal(Exception exception, string source, string message, T context) 98 | { 99 | GetLogger().LogCritical(exception, "[{source}] {message} {context}", source, message, context); 100 | } 101 | 102 | public void Debug(string source, string message) 103 | { 104 | GetLogger().LogDebug("[{source}] {message}", source, message); 105 | } 106 | 107 | public void Debug(string source, string message, T context) 108 | { 109 | GetLogger().LogDebug("[{source}] {message} {context}", source, message, context); 110 | } 111 | 112 | public void Verbose(string source, string message) 113 | { 114 | GetLogger().LogDebug("[{source}] {message}", source, message); 115 | } 116 | 117 | public void Verbose(string source, string message, T context) 118 | { 119 | GetLogger().LogDebug("[{source}] {message} {context}", source, message, context); 120 | } 121 | 122 | public void UnhandledExceptionLog(UnhandledExceptionEventArgs args) 123 | { 124 | StringBuilder errorLogBuilder = new StringBuilder(); 125 | errorLogBuilder.Append("检测到未处理的异常"); 126 | if (args.IsTerminating) 127 | { 128 | errorLogBuilder.Append(",服务器将停止运行"); 129 | } 130 | 131 | _logger.LogCritical(args.ExceptionObject as Exception, "{errorLog}",errorLogBuilder.ToString()); 132 | if (args.IsTerminating) 133 | { 134 | _logger.LogWarning("[Sora] 将在5s后自动退出"); 135 | Thread.Sleep(5000); 136 | Environment.Exit(-1); 137 | } 138 | } 139 | 140 | public void SetCultureInfo(CultureInfo cultureInfo) 141 | { 142 | // 143 | } 144 | } -------------------------------------------------------------------------------- /OneBot-CommandRoute/OneBot-CommandRoute.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | OneBot 6 | ParaParty 7 | ParaParty 8 | ParaParty 9 | 使用 Sora 作 OneBot 客户端,Microsoft.Extensions.DependencyInjection 作 IOC 框架的 OneBot 指令路由系统。 10 | ParaParty 2021 11 | AGPL-3.0-only 12 | https://github.com/ParaParty/OneBot-Framework/ 13 | https://github.com/ParaParty/OneBot-Framework/ 14 | git 15 | OneBot 16 | zh 17 | 3.3.0 18 | 3.3.0.0 19 | 3.3.0.0 20 | enable 21 | Nullable 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /OneBot-Framework-Demo/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### VisualStudio template 3 | ## Ignore Visual Studio temporary files, build results, and 4 | ## files generated by popular Visual Studio add-ons. 5 | ## 6 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 7 | 8 | # User-specific files 9 | *.rsuser 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Ww][Ii][Nn]32/ 29 | [Aa][Rr][Mm]/ 30 | [Aa][Rr][Mm]64/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Ll]og/ 35 | [Ll]ogs/ 36 | 37 | # Visual Studio 2015/2017 cache/options directory 38 | .vs/ 39 | # Uncomment if you have tasks that create the project's static files in wwwroot 40 | #wwwroot/ 41 | 42 | # Visual Studio 2017 auto generated files 43 | Generated\ Files/ 44 | 45 | # MSTest test Results 46 | [Tt]est[Rr]esult*/ 47 | [Bb]uild[Ll]og.* 48 | 49 | # NUnit 50 | *.VisualState.xml 51 | TestResult.xml 52 | nunit-*.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # ASP.NET Scaffolding 68 | ScaffoldingReadMe.txt 69 | 70 | # StyleCop 71 | StyleCopReport.xml 72 | 73 | # Files built by Visual Studio 74 | *_i.c 75 | *_p.c 76 | *_h.h 77 | *.ilk 78 | *.meta 79 | *.obj 80 | *.iobj 81 | *.pch 82 | *.pdb 83 | *.ipdb 84 | *.pgc 85 | *.pgd 86 | *.rsp 87 | *.sbr 88 | *.tlb 89 | *.tli 90 | *.tlh 91 | *.tmp 92 | *.tmp_proj 93 | *_wpftmp.csproj 94 | *.log 95 | *.vspscc 96 | *.vssscc 97 | .builds 98 | *.pidb 99 | *.svclog 100 | *.scc 101 | 102 | # Chutzpah Test files 103 | _Chutzpah* 104 | 105 | # Visual C++ cache files 106 | ipch/ 107 | *.aps 108 | *.ncb 109 | *.opendb 110 | *.opensdf 111 | *.sdf 112 | *.cachefile 113 | *.VC.db 114 | *.VC.VC.opendb 115 | 116 | # Visual Studio profiler 117 | *.psess 118 | *.vsp 119 | *.vspx 120 | *.sap 121 | 122 | # Visual Studio Trace Files 123 | *.e2e 124 | 125 | # TFS 2012 Local Workspace 126 | $tf/ 127 | 128 | # Guidance Automation Toolkit 129 | *.gpState 130 | 131 | # ReSharper is a .NET coding add-in 132 | _ReSharper*/ 133 | *.[Rr]e[Ss]harper 134 | *.DotSettings.user 135 | 136 | # TeamCity is a build add-in 137 | _TeamCity* 138 | 139 | # DotCover is a Code Coverage Tool 140 | *.dotCover 141 | 142 | # AxoCover is a Code Coverage Tool 143 | .axoCover/* 144 | !.axoCover/settings.json 145 | 146 | # Coverlet is a free, cross platform Code Coverage Tool 147 | coverage*[.json, .xml, .info] 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # 362 | appsettings.json 363 | appsettings.Development.json -------------------------------------------------------------------------------- /OneBot-Framework-Demo/Attributes/DemoBeforeCommandAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using OneBot.CommandRoute.Attributes; 4 | using OneBot.CommandRoute.Models; 5 | using Sora.Entities.Info; 6 | using Sora.Enumeration.ApiType; 7 | using Sora.Enumeration.EventParamsType; 8 | using Sora.EventArgs.SoraEvent; 9 | 10 | namespace OneBot.FrameworkDemo.Attributes; 11 | 12 | /// 13 | /// 在触发指令前的切片 14 | /// 15 | public class DemoBeforeCommandAttribute : BeforeCommandAttribute 16 | { 17 | public override void Invoke(OneBotContext context) 18 | { 19 | IServiceScope scope = context.ServiceScope; 20 | BaseSoraEventArgs baseSoraEventArgs = context.SoraEventArgs; 21 | 22 | if (baseSoraEventArgs is not GroupMessageEventArgs p) return; 23 | 24 | var taskValue = p.SoraApi.GetGroupMemberInfo(p.SourceGroup, p.Sender.Id, true).AsTask(); 25 | taskValue.Wait(); 26 | 27 | if (taskValue.Result.apiStatus.RetCode != ApiStatusType.Ok) 28 | { 29 | return; 30 | } 31 | 32 | GroupMemberInfo uInfo = taskValue.Result.memberInfo; 33 | 34 | if (uInfo.Role != MemberRoleType.Member) 35 | { 36 | Console.WriteLine($"发送者 {uInfo.UserId} 是管理员"); 37 | } 38 | else 39 | { 40 | Console.WriteLine($"发送者 {uInfo.UserId} 不是管理员"); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/Middleware/TestMiddleware.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.Extensions.Logging; 3 | using OneBot.CommandRoute.Models; 4 | using OneBot.CommandRoute.Services; 5 | 6 | namespace OneBot.FrameworkDemo.Middleware; 7 | 8 | public class TestMiddleware: IOneBotMiddleware 9 | { 10 | private ILogger _logger; 11 | 12 | public TestMiddleware(ILogger logger) 13 | { 14 | _logger = logger; 15 | } 16 | 17 | public ValueTask Invoke(OneBotContext oneBotContext, OneBotRequestDelegate next) 18 | { 19 | using (_logger.BeginScope("机器人开始处理东西了")) { 20 | return next(oneBotContext); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /OneBot-Framework-Demo/Models/Duration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | 4 | namespace OneBot.FrameworkDemo.Models; 5 | 6 | /// 7 | /// 时长类型; 8 | /// 这里是示例自定义参数类型; 9 | /// 需实现一个从 String 或 CQCode 类型来的隐式转换函数才能触发类型解析。 10 | /// 11 | public class Duration 12 | { 13 | /// 14 | /// 时长 15 | /// 16 | public long Seconds { get; private set; } 17 | public Duration(long seconds) 18 | { 19 | Seconds = seconds; 20 | } 21 | 22 | /// 23 | /// 实现一个从数字到 Duration 的隐式转换 24 | /// 25 | /// 时长 26 | public static implicit operator Duration(int seconds) 27 | { 28 | if (seconds < 0) 29 | { 30 | throw new ArgumentException($"无法解析参数。 {seconds}"); 31 | } 32 | 33 | return new Duration(seconds); 34 | } 35 | 36 | /// 37 | /// 实现一个从数字到 Duration 的隐式转换 38 | /// 39 | /// 时长 40 | public static implicit operator Duration(long seconds) 41 | { 42 | if (seconds < 0) 43 | { 44 | throw new ArgumentException($"无法解析参数。 {seconds}"); 45 | } 46 | 47 | return new Duration(seconds); 48 | } 49 | 50 | /// 51 | /// 实现一个从字符串到 Duration 的隐式转换。 52 | /// 1d2h3m4s -> 1天2小时3分钟4秒 53 | /// 54 | /// 时长 55 | public static implicit operator Duration(string value) 56 | { 57 | if (!CanParse(value)) 58 | { 59 | throw new ArgumentException($"无法解析参数。 {value}"); 60 | } 61 | 62 | var s = ""; 63 | long ret = 0; 64 | for (var i = 0; i < value.Length; i++) 65 | { 66 | if ((value[i] == 's') || (value[i] == 'S')) 67 | { 68 | ret += Convert.ToInt64(s); 69 | s = ""; 70 | continue; 71 | } 72 | 73 | if ((value[i] == 'm') || (value[i] == 'M')) 74 | { 75 | ret += Convert.ToInt64(s) * 60; 76 | s = ""; 77 | continue; 78 | } 79 | 80 | if ((value[i] == 'h') || (value[i] == 'H')) 81 | { 82 | ret += Convert.ToInt64(s) * 3600; 83 | s = ""; 84 | continue; 85 | } 86 | 87 | if ((value[i] == 'd') || (value[i] == 'D')) 88 | { 89 | ret += Convert.ToInt64(s) * 86400; 90 | s = ""; 91 | continue; 92 | } 93 | 94 | s += value[i]; 95 | } 96 | return new Duration(ret); 97 | } 98 | 99 | /// 100 | /// 判断能否解析 101 | /// 102 | /// 103 | /// 104 | public static bool CanParse(string s) 105 | { 106 | return s != null && Regex.IsMatch(s, @"^(\d*d)?(\d*h)?(\d*m)?(\d*s)?$"); 107 | } 108 | 109 | /// 110 | /// 尝试解析 111 | /// 112 | /// 113 | /// 114 | /// 115 | public static bool TryParse(string s, out Duration duration) 116 | { 117 | duration = null; 118 | if (s == null) return false; 119 | if (long.TryParse(s, out long number)) 120 | { 121 | duration = number; 122 | } 123 | else if (Regex.IsMatch(s, @"^(\d*d)?(\d*h)?(\d*m)?(\d*s)?$")) 124 | { 125 | duration = s; 126 | } 127 | else return false; 128 | return true; 129 | } 130 | 131 | /// 132 | /// 返回可用 ^(\d*d)?(\d*h)?(\d*m)?(\d*s)?$ 匹配的最简时长表达式 133 | /// 134 | /// 135 | public override string ToString() 136 | { 137 | var temp = Seconds; 138 | var ret = ""; 139 | var day = temp / 86400; 140 | if (day > 0) ret += $"{day}d"; 141 | temp %= 86400; 142 | var hour = temp / 3600; 143 | if (hour > 0) ret += $"{hour}h"; 144 | temp %= 3600; 145 | var min = temp / 60; 146 | if (min > 0) ret += $"{min}m"; 147 | temp %= 60; 148 | if (temp > 0) ret += $"{temp}s"; 149 | return ret; 150 | } 151 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/Modules/TestModule.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Logging; 3 | using OneBot.CommandRoute.Attributes; 4 | using OneBot.CommandRoute.Models.Enumeration; 5 | using OneBot.CommandRoute.Services; 6 | using OneBot.FrameworkDemo.Attributes; 7 | using OneBot.FrameworkDemo.Models; 8 | using Sora.Entities; 9 | using Sora.EventArgs.SoraEvent; 10 | 11 | namespace OneBot.FrameworkDemo.Modules; 12 | 13 | /// 14 | /// 这个是示例处理代码,所有的 OneBot 处理对象均需实现 IOneBotController 接口 15 | /// 16 | public class TestModule : IOneBotController 17 | { 18 | private readonly ILogger _logger; 19 | 20 | public TestModule(ICommandService commandService, ILogger logger) 21 | { 22 | // 通过构造函数获得指令路由服务对象 23 | 24 | // 基本事件处理例子 25 | // 如果你不想要指令路由,可以使用这个方法来注册最原始的事件监听方法 26 | commandService.Event.OnGroupMessage += (scope) => 27 | { 28 | var args = scope.WrapSoraEventArgs(); 29 | 30 | // 在控制台中复读群里的信息 31 | logger.LogInformation($"{args.SourceGroup.Id} : {args.Sender.Id} : {args.Message.RawText}"); 32 | 33 | return 0; 34 | // 这里返回 0,表示继续传递该事件给后续的指令或监听。 35 | }; 36 | 37 | // 全局异常处理事件 38 | commandService.Event.OnException += (scope, exception) => 39 | { 40 | logger.LogError($"{exception.Message}"); 41 | }; 42 | 43 | _logger = logger; 44 | } 45 | 46 | /// 47 | /// 指令定义例子 48 | /// 49 | /// 定义一个指令: 50 | /// 使用 < > 括起来的是必选参数; 51 | /// 使用 [ ] 括起来的是可选参数 52 | /// 53 | /// 禁言时长 54 | /// 全参数列表 55 | /// 被禁言用户 56 | /// 原始事件信息 57 | [Command("mute [duration]", Alias = new[] {"禁言 [duration]", "口球 [duration]"}, EventType = EventType.GroupMessage)] 58 | [DemoBeforeCommand] 59 | public void MuteInGroupWithDuration(Duration duration, [ParsedArguments] object[] args, [CommandParameter("uid")] User userInfo, GroupMessageEventArgs e) 60 | { 61 | duration ??= new Duration(600); 62 | _logger.LogInformation($"{e.Sender.Id} 使用指令禁言 {userInfo.Id} 用户 {duration.Seconds} 秒。"); 63 | 64 | // 这个指令没有返回值,其隐式返回 1,在执行完毕后不再传递该事件给后续的指令或监听。 65 | } 66 | 67 | /// 68 | /// 再定义一个指令: 69 | /// 70 | /// 参数不必要按顺序、参数会触发依赖注入 71 | /// 72 | /// 操作群号 73 | /// 被禁言用户 74 | /// 禁言时长 75 | /// 原始事件信息 76 | 77 | [Command("mute [duration]", Alias = new[] {"禁言 [duration]", "口球 [duration]"}, EventType = EventType.GroupMessage | EventType.PrivateMessage)] 78 | public int MuteInGroupWithGroupId(Group gid, User uid, Duration duration, BaseSoraEventArgs e) 79 | { 80 | duration ??= new Duration(600); 81 | 82 | switch (e) 83 | { 84 | case GroupMessageEventArgs s1: 85 | _logger.LogInformation($"{s1.Sender.Id} 使用指令禁言 {gid.Id} 群里的 {uid.Id} 用户 {duration.Seconds} 秒。"); 86 | break; 87 | case PrivateMessageEventArgs s2: 88 | _logger.LogInformation($"{s2.Sender.Id} 使用指令禁言 {gid.Id} 群里的 {uid.Id} 用户 {duration.Seconds} 秒。"); 89 | break; 90 | } 91 | 92 | return 1; 93 | // 这里是显示返回 1,在执行完毕后不再传递该事件给后续的指令或监听。 94 | // return 0; 95 | // 当然也可以返回 0,表示继续传递。 96 | } 97 | 98 | /// 99 | /// 小程序简单监听方法, 100 | /// 这里是监听了群签到。 101 | /// 102 | /// 103 | [CQJson("com.tencent.qq.checkin", EventType = EventType.GroupMessage)] 104 | public void CheckInListener(GroupMessageEventArgs e) 105 | { 106 | _logger.LogInformation($"{e.Sender.Id} 签到成功!"); 107 | 108 | // 当然这里也是可以返回 0 或 1 的。 109 | } 110 | 111 | /// 112 | /// 全局异常处理函数测试 113 | /// 114 | [Command("exception", EventType = EventType.GroupMessage | EventType.PrivateMessage)] 115 | public void ExceptionTest() 116 | { 117 | throw new Exception("测试全局异常处理"); 118 | } 119 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/OneBot-Framework-Demo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | warnings 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /OneBot-Framework-Demo/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using OneBot.CommandRoute.Mixin; 4 | using OneBot.CommandRoute.Models.VO; 5 | using OneBot.CommandRoute.Services; 6 | using OneBot.FrameworkDemo.Middleware; 7 | using OneBot.FrameworkDemo.Modules; 8 | 9 | namespace OneBot.FrameworkDemo; 10 | 11 | public class Program 12 | { 13 | public static void Main(string[] args) 14 | { 15 | // 创建主机 16 | var builder = Host.CreateDefaultBuilder(args); 17 | 18 | // 配置 OneBot 主机 19 | builder.ConfigureOneBotHost(); 20 | 21 | // 配置服务 22 | builder.ConfigureServices((context, services) => 23 | { 24 | var configuration = context.Configuration; 25 | // 配置机器人核心 26 | // 设置 OneBot 配置 27 | services.Configure(configuration.GetSection("CQHttpConfig")); 28 | services.ConfigureOneBot(); 29 | 30 | // 添加中间件 31 | // 单例模式或原型模式都可以,问题不大。 32 | services.AddScoped(); 33 | 34 | // 添加指令 / 事件 35 | // 推荐使用单例模式(而实际上框架代码也是当单例模式使用的) 36 | services.AddSingleton(); 37 | // 一行一行地将指令模块加进去 38 | }); 39 | 40 | // 开始运行 41 | builder.Build().Run(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /OneBot-Framework-Demo/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:50698", 7 | "sslPort": 44310 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "OneBot-Framework-Demo": { 19 | "commandName": "Project", 20 | "environmentVariables": { 21 | "ASPNETCORE_ENVIRONMENT": "Development" 22 | }, 23 | "applicationUrl": "https://localhost:5001;http://localhost:5000" 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/appsettings-reverse_ws-example.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "CQHttpConfig": { 10 | "Mode": "reverse_ws", 11 | "Host": "127.0.0.1", 12 | "Port": 15951, 13 | "AccessToken": "", 14 | "ApiPath": "", 15 | "EventPath": "", 16 | "UniversalPath": "", 17 | "HeartBeatTimeOut": 10, 18 | "ApiTimeOut": 1000 19 | } 20 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/appsettings-reverse_ws-example.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "CQHttpConfig": { 10 | "Mode": "reverse_ws", 11 | "Host": "127.0.0.1", 12 | "Port": 15951, 13 | "AccessToken": "", 14 | "ApiPath": "", 15 | "EventPath": "", 16 | "UniversalPath": "", 17 | "HeartBeatTimeOut": 10, 18 | "ApiTimeOut": 1000 19 | } 20 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/appsettings-ws-example.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "CQHttpConfig": { 10 | "Mode": "ws", 11 | "Host": "127.0.0.1", 12 | "Port": 6700, 13 | "AccessToken": "", 14 | "ApiPath": "", 15 | "EventPath": "", 16 | "UniversalPath": "", 17 | "HeartBeatTimeOut": 10, 18 | "ApiTimeOut": 1000 19 | } 20 | } -------------------------------------------------------------------------------- /OneBot-Framework-Demo/appsettings-ws-example.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "CQHttpConfig": { 10 | "Mode": "ws", 11 | "Host": "127.0.0.1", 12 | "Port": 6700, 13 | "AccessToken": "", 14 | "ApiPath": "", 15 | "EventPath": "", 16 | "UniversalPath": "", 17 | "HeartBeatTimeOut": 10, 18 | "ApiTimeOut": 1000 19 | } 20 | } -------------------------------------------------------------------------------- /OneBot-Framework.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30907.101 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{4AD52A7F-365F-49B1-8B11-36E3F408488E}") = "OneBot-Framework-Demo", "OneBot-Framework-Demo\OneBot-Framework-Demo.csproj", "{AD94F698-0595-469B-8ECE-4D4CD362D81A}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OneBot-CommandRoute", "OneBot-CommandRoute\OneBot-CommandRoute.csproj", "{64442450-B821-4036-8993-3FC3FFE06CDE}" 9 | EndProject 10 | Project("{EE6532C9-9C4E-47DB-A487-9200572B7553}") = "OneBot-OpenTelemetry", "OneBot-OpenTelemetry\OneBot-OpenTelemetry.csproj", "{DD253E2B-F8D3-4893-91D4-4F9ACD89BB99}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E1F29AC3-B85B-42F2-B535-71D7E401F034}" 13 | ProjectSection(SolutionItems) = preProject 14 | .editorconfig = .editorconfig 15 | EndProjectSection 16 | EndProject 17 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OneBot-UnitTest", "OneBot-UnitTest\OneBot-UnitTest.csproj", "{0512F90F-18C2-4BFF-A1A3-3AD52F00EA51}" 18 | EndProject 19 | Global 20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 21 | Debug|Any CPU = Debug|Any CPU 22 | Release|Any CPU = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {AD94F698-0595-469B-8ECE-4D4CD362D81A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {AD94F698-0595-469B-8ECE-4D4CD362D81A}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {AD94F698-0595-469B-8ECE-4D4CD362D81A}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {AD94F698-0595-469B-8ECE-4D4CD362D81A}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {64442450-B821-4036-8993-3FC3FFE06CDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {64442450-B821-4036-8993-3FC3FFE06CDE}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {64442450-B821-4036-8993-3FC3FFE06CDE}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {64442450-B821-4036-8993-3FC3FFE06CDE}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {0512F90F-18C2-4BFF-A1A3-3AD52F00EA51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {0512F90F-18C2-4BFF-A1A3-3AD52F00EA51}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {0512F90F-18C2-4BFF-A1A3-3AD52F00EA51}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {0512F90F-18C2-4BFF-A1A3-3AD52F00EA51}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {DD253E2B-F8D3-4893-91D4-4F9ACD89BB99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {DD253E2B-F8D3-4893-91D4-4F9ACD89BB99}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {DD253E2B-F8D3-4893-91D4-4F9ACD89BB99}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {DD253E2B-F8D3-4893-91D4-4F9ACD89BB99}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(ExtensibilityGlobals) = postSolution 46 | SolutionGuid = {08C43C5D-0ADC-407A-8672-667C1DE72122} 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /OneBot-Framework.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True 3 | True -------------------------------------------------------------------------------- /OneBot-OpenTelemetry/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### VisualStudio template 3 | ## Ignore Visual Studio temporary files, build results, and 4 | ## files generated by popular Visual Studio add-ons. 5 | ## 6 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 7 | 8 | # User-specific files 9 | *.rsuser 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Ww][Ii][Nn]32/ 29 | [Aa][Rr][Mm]/ 30 | [Aa][Rr][Mm]64/ 31 | bld/ 32 | [Bb]in/ 33 | [Oo]bj/ 34 | [Ll]og/ 35 | [Ll]ogs/ 36 | 37 | # Visual Studio 2015/2017 cache/options directory 38 | .vs/ 39 | # Uncomment if you have tasks that create the project's static files in wwwroot 40 | #wwwroot/ 41 | 42 | # Visual Studio 2017 auto generated files 43 | Generated\ Files/ 44 | 45 | # MSTest test Results 46 | [Tt]est[Rr]esult*/ 47 | [Bb]uild[Ll]og.* 48 | 49 | # NUnit 50 | *.VisualState.xml 51 | TestResult.xml 52 | nunit-*.xml 53 | 54 | # Build Results of an ATL Project 55 | [Dd]ebugPS/ 56 | [Rr]eleasePS/ 57 | dlldata.c 58 | 59 | # Benchmark Results 60 | BenchmarkDotNet.Artifacts/ 61 | 62 | # .NET Core 63 | project.lock.json 64 | project.fragment.lock.json 65 | artifacts/ 66 | 67 | # ASP.NET Scaffolding 68 | ScaffoldingReadMe.txt 69 | 70 | # StyleCop 71 | StyleCopReport.xml 72 | 73 | # Files built by Visual Studio 74 | *_i.c 75 | *_p.c 76 | *_h.h 77 | *.ilk 78 | *.meta 79 | *.obj 80 | *.iobj 81 | *.pch 82 | *.pdb 83 | *.ipdb 84 | *.pgc 85 | *.pgd 86 | *.rsp 87 | *.sbr 88 | *.tlb 89 | *.tli 90 | *.tlh 91 | *.tmp 92 | *.tmp_proj 93 | *_wpftmp.csproj 94 | *.log 95 | *.vspscc 96 | *.vssscc 97 | .builds 98 | *.pidb 99 | *.svclog 100 | *.scc 101 | 102 | # Chutzpah Test files 103 | _Chutzpah* 104 | 105 | # Visual C++ cache files 106 | ipch/ 107 | *.aps 108 | *.ncb 109 | *.opendb 110 | *.opensdf 111 | *.sdf 112 | *.cachefile 113 | *.VC.db 114 | *.VC.VC.opendb 115 | 116 | # Visual Studio profiler 117 | *.psess 118 | *.vsp 119 | *.vspx 120 | *.sap 121 | 122 | # Visual Studio Trace Files 123 | *.e2e 124 | 125 | # TFS 2012 Local Workspace 126 | $tf/ 127 | 128 | # Guidance Automation Toolkit 129 | *.gpState 130 | 131 | # ReSharper is a .NET coding add-in 132 | _ReSharper*/ 133 | *.[Rr]e[Ss]harper 134 | *.DotSettings.user 135 | 136 | # TeamCity is a build add-in 137 | _TeamCity* 138 | 139 | # DotCover is a Code Coverage Tool 140 | *.dotCover 141 | 142 | # AxoCover is a Code Coverage Tool 143 | .axoCover/* 144 | !.axoCover/settings.json 145 | 146 | # Coverlet is a free, cross platform Code Coverage Tool 147 | coverage*[.json, .xml, .info] 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # 362 | appsettings.json 363 | appsettings.Development.json -------------------------------------------------------------------------------- /OneBot-OpenTelemetry/OneBot-OpenTelemetry.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | OneBot 6 | ParaParty 7 | ParaParty 8 | ParaParty 9 | OneBot-CommandRoute OpenTelemetry 支持 10 | ParaParty 2021 11 | AGPL-3.0-only 12 | https://github.com/ParaParty/OneBot-Framework/ 13 | https://github.com/ParaParty/OneBot-Framework/ 14 | git 15 | OneBot 16 | zh 17 | 3.3.0 18 | 3.3.0.0 19 | 3.3.0.0 20 | enable 21 | Nullable 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /OneBot-OpenTelemetry/OpenTelemetry/TraceProviderBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // ReSharper disable once CheckNamespace 2 | namespace OpenTelemetry.Trace; 3 | 4 | public static class TraceProviderBuilderExtensions 5 | { 6 | public static TracerProviderBuilder AddOneBotInstrumentation( 7 | this TracerProviderBuilder builder) 8 | { 9 | builder.AddSource("OneBot.Event", "OneBot.Middleware", "OneBot.CommandRoute", "OneBot.EventRoute"); 10 | return builder; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /OneBot-UnitTest/.gitignore: -------------------------------------------------------------------------------- 1 | ### VisualStudio template 2 | ## Ignore Visual Studio temporary files, build results, and 3 | ## files generated by popular Visual Studio add-ons. 4 | ## 5 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 6 | 7 | # User-specific files 8 | *.rsuser 9 | *.suo 10 | *.user 11 | *.userosscache 12 | *.sln.docstates 13 | 14 | # User-specific files (MonoDevelop/Xamarin Studio) 15 | *.userprefs 16 | 17 | # Mono auto generated files 18 | mono_crash.* 19 | 20 | # Build results 21 | [Dd]ebug/ 22 | [Dd]ebugPublic/ 23 | [Rr]elease/ 24 | [Rr]eleases/ 25 | x64/ 26 | x86/ 27 | [Ww][Ii][Nn]32/ 28 | [Aa][Rr][Mm]/ 29 | [Aa][Rr][Mm]64/ 30 | bld/ 31 | [Bb]in/ 32 | [Oo]bj/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*[.json, .xml, .info] 147 | 148 | # Visual Studio code coverage results 149 | *.coverage 150 | *.coveragexml 151 | 152 | # NCrunch 153 | _NCrunch_* 154 | .*crunch*.local.xml 155 | nCrunchTemp_* 156 | 157 | # MightyMoose 158 | *.mm.* 159 | AutoTest.Net/ 160 | 161 | # Web workbench (sass) 162 | .sass-cache/ 163 | 164 | # Installshield output folder 165 | [Ee]xpress/ 166 | 167 | # DocProject is a documentation generator add-in 168 | DocProject/buildhelp/ 169 | DocProject/Help/*.HxT 170 | DocProject/Help/*.HxC 171 | DocProject/Help/*.hhc 172 | DocProject/Help/*.hhk 173 | DocProject/Help/*.hhp 174 | DocProject/Help/Html2 175 | DocProject/Help/html 176 | 177 | # Click-Once directory 178 | publish/ 179 | 180 | # Publish Web Output 181 | *.[Pp]ublish.xml 182 | *.azurePubxml 183 | # Note: Comment the next line if you want to checkin your web deploy settings, 184 | # but database connection strings (with potential passwords) will be unencrypted 185 | *.pubxml 186 | *.publishproj 187 | 188 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 189 | # checkin your Azure Web App publish settings, but sensitive information contained 190 | # in these scripts will be unencrypted 191 | PublishScripts/ 192 | 193 | # NuGet Packages 194 | *.nupkg 195 | # NuGet Symbol Packages 196 | *.snupkg 197 | # The packages folder can be ignored because of Package Restore 198 | **/[Pp]ackages/* 199 | # except build/, which is used as an MSBuild target. 200 | !**/[Pp]ackages/build/ 201 | # Uncomment if necessary however generally it will be regenerated when needed 202 | #!**/[Pp]ackages/repositories.config 203 | # NuGet v3's project.json files produces more ignorable files 204 | *.nuget.props 205 | *.nuget.targets 206 | 207 | # Microsoft Azure Build Output 208 | csx/ 209 | *.build.csdef 210 | 211 | # Microsoft Azure Emulator 212 | ecf/ 213 | rcf/ 214 | 215 | # Windows Store app package directories and files 216 | AppPackages/ 217 | BundleArtifacts/ 218 | Package.StoreAssociation.xml 219 | _pkginfo.txt 220 | *.appx 221 | *.appxbundle 222 | *.appxupload 223 | 224 | # Visual Studio cache files 225 | # files ending in .cache can be ignored 226 | *.[Cc]ache 227 | # but keep track of directories ending in .cache 228 | !?*.[Cc]ache/ 229 | 230 | # Others 231 | ClientBin/ 232 | ~$* 233 | *~ 234 | *.dbmdl 235 | *.dbproj.schemaview 236 | *.jfm 237 | *.pfx 238 | *.publishsettings 239 | orleans.codegen.cs 240 | 241 | # Including strong name files can present a security risk 242 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 243 | #*.snk 244 | 245 | # Since there are multiple workflows, uncomment next line to ignore bower_components 246 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 247 | #bower_components/ 248 | 249 | # RIA/Silverlight projects 250 | Generated_Code/ 251 | 252 | # Backup & report files from converting an old project file 253 | # to a newer Visual Studio version. Backup files are not needed, 254 | # because we have git ;-) 255 | _UpgradeReport_Files/ 256 | Backup*/ 257 | UpgradeLog*.XML 258 | UpgradeLog*.htm 259 | ServiceFabricBackup/ 260 | *.rptproj.bak 261 | 262 | # SQL Server files 263 | *.mdf 264 | *.ldf 265 | *.ndf 266 | 267 | # Business Intelligence projects 268 | *.rdl.data 269 | *.bim.layout 270 | *.bim_*.settings 271 | *.rptproj.rsuser 272 | *- [Bb]ackup.rdl 273 | *- [Bb]ackup ([0-9]).rdl 274 | *- [Bb]ackup ([0-9][0-9]).rdl 275 | 276 | # Microsoft Fakes 277 | FakesAssemblies/ 278 | 279 | # GhostDoc plugin setting file 280 | *.GhostDoc.xml 281 | 282 | # Node.js Tools for Visual Studio 283 | .ntvs_analysis.dat 284 | node_modules/ 285 | 286 | # Visual Studio 6 build log 287 | *.plg 288 | 289 | # Visual Studio 6 workspace options file 290 | *.opt 291 | 292 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 293 | *.vbw 294 | 295 | # Visual Studio LightSwitch build output 296 | **/*.HTMLClient/GeneratedArtifacts 297 | **/*.DesktopClient/GeneratedArtifacts 298 | **/*.DesktopClient/ModelManifest.xml 299 | **/*.Server/GeneratedArtifacts 300 | **/*.Server/ModelManifest.xml 301 | _Pvt_Extensions 302 | 303 | # Paket dependency manager 304 | .paket/paket.exe 305 | paket-files/ 306 | 307 | # FAKE - F# Make 308 | .fake/ 309 | 310 | # CodeRush personal settings 311 | .cr/personal 312 | 313 | # Python Tools for Visual Studio (PTVS) 314 | __pycache__/ 315 | *.pyc 316 | 317 | # Cake - Uncomment if you are using it 318 | # tools/** 319 | # !tools/packages.config 320 | 321 | # Tabs Studio 322 | *.tss 323 | 324 | # Telerik's JustMock configuration file 325 | *.jmconfig 326 | 327 | # BizTalk build output 328 | *.btp.cs 329 | *.btm.cs 330 | *.odx.cs 331 | *.xsd.cs 332 | 333 | # OpenCover UI analysis results 334 | OpenCover/ 335 | 336 | # Azure Stream Analytics local run output 337 | ASALocalRun/ 338 | 339 | # MSBuild Binary and Structured Log 340 | *.binlog 341 | 342 | # NVidia Nsight GPU debugger configuration file 343 | *.nvuser 344 | 345 | # MFractors (Xamarin productivity tool) working folder 346 | .mfractor/ 347 | 348 | # Local History for Visual Studio 349 | .localhistory/ 350 | 351 | # BeatPulse healthcheck temp database 352 | healthchecksdb 353 | 354 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 355 | MigrationBackup/ 356 | 357 | # Ionide (cross platform F# VS Code tools) working folder 358 | .ionide/ 359 | 360 | # 361 | appsettings.json 362 | appsettings.Development.json -------------------------------------------------------------------------------- /OneBot-UnitTest/DurationTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using OneBot.FrameworkDemo.Models; 3 | 4 | namespace OneBot_UnitTest; 5 | 6 | [TestClass] 7 | public class DurationTest 8 | { 9 | [TestMethod] 10 | public void ParseFromString() 11 | { 12 | Assert.IsTrue(Duration.TryParse("11d4h51m4s",out var duration)); 13 | Assert.AreEqual(11 * 86400 + 4 * 3600 + 51 * 60 + 4, duration.Seconds); 14 | } 15 | 16 | [TestMethod] 17 | public void DurationToString() 18 | { 19 | Duration.TryParse("11d4h51m4s", out var duration); 20 | Assert.AreEqual("11d4h51m4s", duration.ToString()); 21 | Duration.TryParse("1919d8m10s", out duration); 22 | Assert.AreEqual("1919d8m10s", duration.ToString()); 23 | } 24 | } -------------------------------------------------------------------------------- /OneBot-UnitTest/LexerTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Diagnostics.CodeAnalysis; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using OneBot.CommandRoute.Lexer; 5 | using OneBot_UnitTest.Util; 6 | using Sora.Entities; 7 | using Sora.Entities.Segment; 8 | 9 | namespace OneBot_UnitTest; 10 | 11 | [TestClass] 12 | [SuppressMessage("ReSharper", "ArrangeObjectCreationWhenTypeNotEvident")] 13 | public class LexerTest 14 | { 15 | 16 | [TestMethod] 17 | public void LexerTestForString() 18 | { 19 | List<(List, List)> testCasts = new() 20 | { 21 | (new (){"a b c d"}, new (){"a", "b", "c", "d"}), 22 | (new (){@"a 23 | b 24 | c 25 | d 26 | e 27 | "}, new (){"a", "b", "c", "d", "e"}), 28 | (new (){"a b c d"}, new (){"a", "b", "c", "d"}), 29 | (new (){@"a b c 30 | 31 | 32 | 33 | 34 | d"}, new (){"a", "b", "c", "d"}), 35 | (new (){"测试\t\t测试"}, new (){"测试", "测试"}), 36 | (new (){"a","b c d"}, new (){"ab", "c", "d"}), 37 | (new (){"a "," b c d"}, new (){"a", "b", "c", "d"}), 38 | (new (){"a","b","c","d"}, new (){"abcd"}), 39 | }; 40 | 41 | testCasts.ForEach((data) => 42 | { 43 | var lexer = new CommandLexer(data.Item1); 44 | var tokens = lexer.ExtraAllTokens(); 45 | AssertUtil.ArrayAreEqual(data.Item2, tokens); 46 | AssertUtil.ArrayAreEqual(lexer.ParsedArguments, tokens); 47 | }); 48 | } 49 | 50 | 51 | [TestMethod] 52 | public void LexerForNormalMixedMessage() 53 | { 54 | List<(List, List)> testCasts = new() 55 | { 56 | (new (){"mute ", SoraSegment.At(114514), " 1d"}, new (){"mute", SoraSegment.At(114514), "1d"}), 57 | (new (){"mute", SoraSegment.At(114514), "1d"}, new (){"mute", SoraSegment.At(114514), "1d"}), 58 | }; 59 | 60 | testCasts.ForEach((data) => 61 | { 62 | var lexer = new CommandLexer(data.Item1); 63 | var tokens = lexer.ExtraAllTokens(); 64 | AssertUtil.ArrayAreEqual(data.Item2, tokens); 65 | AssertUtil.ArrayAreEqual(lexer.ParsedArguments, tokens); 66 | }); 67 | } 68 | 69 | 70 | [TestMethod] 71 | public void LexerTestForQuotedString() 72 | { 73 | List<(List, List)> testCasts = new() 74 | { 75 | (new() { "a \"b c\" d" }, new() { "a", new MessageBody { "b c" }, "d" }), 76 | (new() { "a \"b\n c\" d" }, new() { "a", new MessageBody { "b\n c" }, "d" }), 77 | (new() { "a \"b c\"" }, new() { "a", new MessageBody { "b c" } }), 78 | (new() { "\"a a\",\"" }, new() { new MessageBody { "a a" }, ",\"" }), 79 | (new() { "\"''''\" '\"\"\"\"'" }, new() { new MessageBody { "''''" }, new MessageBody { "\"\"\"\"" } }), 80 | (new() { "\" '''' \" ' \"\"\"\" '" }, new() { new MessageBody { " '''' " }, new MessageBody { " \"\"\"\" " } }), 81 | (new() { "\"114514" }, new() { new MessageBody { "114514" } }), 82 | (new() { "'1919810" }, new() { new MessageBody { "1919810" } }), 83 | (new() { "\"\"\"\"" }, new() { new MessageBody { "\"" } }), 84 | (new() { "\"", "", "\"", "", "", "\"", "", "", "\"" }, new() { new MessageBody { "\"" } }), 85 | }; 86 | 87 | testCasts.ForEach((data) => 88 | { 89 | var lexer = new CommandLexer(data.Item1); 90 | var tokens = lexer.ExtraAllTokens(); 91 | AssertUtil.ArrayAreEqual(data.Item2, tokens); 92 | AssertUtil.ArrayAreEqual(lexer.ParsedArguments, tokens); 93 | }); 94 | } 95 | 96 | [TestMethod] 97 | public void LexerForNormalQuotedMixedMessage() 98 | { 99 | List<(List, List)> testCasts = new() 100 | { 101 | ( 102 | new() { "draw 喜报 \"恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。\"" }, 103 | new() { "draw", "喜报", new MessageBody { "恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。" }} 104 | ), 105 | ( 106 | new() { "draw 喜报 '恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。'" }, 107 | new() { "draw", "喜报", new MessageBody { "恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。" }} 108 | ), 109 | ( 110 | new() 111 | { 112 | "draw 喜报 \"恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。\"' ", SoraSegment.At(1919810), " '" 113 | }, 114 | new() 115 | { 116 | "draw", "喜报", new MessageBody { "恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。" }, 117 | new MessageBody { " ", SoraSegment.At(1919810), " " } 118 | } 119 | ), 120 | ( 121 | new() { "draw 喜报 \"恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。\"", SoraSegment.At(1919810) }, 122 | new() { "draw", "喜报", new MessageBody { "恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。" }, SoraSegment.At(1919810)} 123 | ), 124 | ( 125 | new() { "draw 喜报 \"恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。\"", "test" }, 126 | new() { "draw", "喜报", new MessageBody { "恭喜 ", SoraSegment.At(114514), "获得群 Bug 最多奖。" }, "test"} 127 | ), 128 | }; 129 | 130 | testCasts.ForEach((data) => 131 | { 132 | var lexer = new CommandLexer(data.Item1); 133 | var tokens = lexer.ExtraAllTokens(); 134 | AssertUtil.ArrayAreEqual(data.Item2, tokens); 135 | AssertUtil.ArrayAreEqual(lexer.ParsedArguments, tokens); 136 | }); 137 | } 138 | } -------------------------------------------------------------------------------- /OneBot-UnitTest/OneBot-UnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | OneBot_UnitTest 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /OneBot-UnitTest/Util/AssertUtil.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Linq; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace OneBot_UnitTest.Util; 6 | 7 | public static class AssertUtil 8 | { 9 | public static void ArrayAreEqual(IEnumerable expected, IEnumerable actual) 10 | { 11 | var expectedList = expected.Cast().ToList(); 12 | var actualList = actual.Cast().ToList(); 13 | 14 | Assert.AreEqual(expectedList.Count, actualList.Count); 15 | 16 | for (var i = 0; i < expectedList.Count; i++) 17 | { 18 | if ( 19 | expectedList[i] is not string && actualList[i] is not string && 20 | expectedList[i] is IEnumerable && actualList[i] is IEnumerable 21 | ) 22 | { 23 | ArrayAreEqual(expectedList[i] as IEnumerable, actualList[i] as IEnumerable); 24 | } 25 | else 26 | { 27 | Assert.AreEqual(expectedList[i], actualList[i]); 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /OneBot-UnitTest/Util/LexerUtil.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using OneBot.CommandRoute.Lexer; 3 | 4 | namespace OneBot_UnitTest.Util; 5 | 6 | public static class LexerUtil 7 | { 8 | public static List ExtraAllTokens(this CommandLexer self) 9 | { 10 | var ret = new List(); 11 | try 12 | { 13 | while (true) 14 | { 15 | ret.Add(self.GetNextNotBlank()); 16 | } 17 | } 18 | catch (ParseToTheEndException) 19 | { 20 | // ignored 21 | } 22 | 23 | return ret; 24 | } 25 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OneBot - Framework 2 | 3 | ## 使用说明 4 | 5 | 本仓库仅为指令路由框架本体及其相关工具的存储仓库,如果您需要基于本工具制作一个机器人,请移步这个仓库:[ParaParty/OneBot-CommandRoute-Template](https://github.com/ParaParty/OneBot-CommandRoute-Template) 6 | 7 | ## 文件夹介绍 8 | 9 | | 文件夹 | 作用 | 10 | |-----------------------|--------------------------------------| 11 | | OneBot-CommandRoute | 指令路由框架本体 | 12 | | OneBot-OpenTelemetry | 指令路由框架的 Open-Telemetry 集成库 | 13 | | OneBot-UnitTest | 指令路由框架的单元测试 | 14 | | OneBot-Framework-Demo | 指令路由框架的使用范例 | 15 | 16 | ## 发布页 17 | - 指令路由框架本体: 18 | - 指令路由框架的 Open-Telemetry 集成库: --------------------------------------------------------------------------------