├── .github ├── dependabot.yml └── workflows │ └── release.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── cn │ └── evole │ └── onebot │ └── client │ ├── OneBotClient.java │ ├── annotations │ ├── EventBus.java │ └── SubscribeEvent.java │ ├── connection │ └── WSClient.java │ ├── core │ ├── Bot.java │ └── BotConfig.java │ ├── instances │ ├── action │ │ ├── ActionFactory.java │ │ └── ActionSendUnit.java │ └── event │ │ ├── EventExecutorFactoryImpl.java │ │ ├── EventFactory.java │ │ ├── EventsBusImpl.java │ │ ├── MethodScannerImpl.java │ │ └── MsgHandlerImpl.java │ ├── interfaces │ ├── EventsBus.java │ ├── Listener.java │ └── MsgHandler.java │ ├── internal │ └── TestHandler.java │ └── utils │ ├── ConnectionUtils.java │ ├── IOUtils.java │ ├── ReflectionUtils.java │ └── TransUtils.java └── test └── java ├── ApiTest.java ├── HandlerTest.java ├── JsonTest.java └── server ├── AbstractWsEchoServer.java └── impl └── SimpleWsEchoServer.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "" # See documentation for possible values 4 | directory: "/" # Location of package manifests 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v4 16 | with: 17 | show-progress: false 18 | 19 | - name: Set up JDK 8 20 | uses: actions/setup-java@v4 21 | with: 22 | java-version: '8' 23 | distribution: 'adopt' 24 | 25 | - name: Validate Gradle Wrapper 26 | uses: gradle/wrapper-validation-action@v1 27 | 28 | - name: Make Gradle Wrapper Executable 29 | run: chmod +x ./gradlew 30 | 31 | - name: Build project 32 | run: | 33 | gradle wrapper 34 | bash gradlew shadowJar 35 | 36 | - name: Release 37 | uses: softprops/action-gh-release@v1 38 | if: startsWith(github.ref, 'refs/tags/') 39 | with: 40 | files: build/libs/* 41 | body: Please refer to [CHANGELOG.md](https://github.com/cnlimiter/onebot-client/blob/master/CHANGELOG.md) for details. -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /build/ 3 | /.gradle/ 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # ChangeLog 2 | 3 | All notable changes to this project will be documented in this file,ChangeLog information is generated by the [CommitMessage plugin](https://plugins.jetbrains.com/plugin/12256-commit-message-create) 4 | 5 | ## [v0.4.3](http://github.com/cnlimiter/onebot-client/compare/v0.4.3...master) 6 | 7 | 8 | ### feat 9 | 10 | * implement reconnection mechanism and improve error handling ([fdb0108](http://github.com/cnlimiter/onebot-client/commit/fdb0108)) 11 | * upgrade SDK and add new features ([51e777b](http://github.com/cnlimiter/onebot-client/commit/51e777b)) 12 | * add support for access token in bot configuration ([545d799](http://github.com/cnlimiter/onebot-client/commit/545d799)) 13 | * api 更新 ([93ce175](http://github.com/cnlimiter/onebot-client/commit/93ce175)) 14 | 15 | 16 | ### fix 17 | 18 | * c51a23f + fix ([c51a23f](http://github.com/cnlimiter/onebot-client/commit/c51a23f)) 19 | 20 | 21 | ### style 22 | 23 | * logger ([09b814d](http://github.com/cnlimiter/onebot-client/commit/09b814d)) 24 | 25 | 26 | ### perf 27 | 28 | * 安全关闭线程 ([243bb38](http://github.com/cnlimiter/onebot-client/commit/243bb38)) 29 | * 批量注册Listener3 ([9f8b1b3](http://github.com/cnlimiter/onebot-client/commit/9f8b1b3)) 30 | * 批量注册Listener ([bfef361](http://github.com/cnlimiter/onebot-client/commit/bfef361)) 31 | * 优化 ([a8206df](http://github.com/cnlimiter/onebot-client/commit/a8206df)) 32 | * 优化json解析 ([84cff38](http://github.com/cnlimiter/onebot-client/commit/84cff38)) 33 | * 重构 ([8316782](http://github.com/cnlimiter/onebot-client/commit/8316782)) 34 | 35 | 36 | ### refactor 37 | 38 | * 优化事件监听器注册与客户端创建流程 ([9abf6b5](http://github.com/cnlimiter/onebot-client/commit/9abf6b5)) 39 | * 优化8 ([d9f892e](http://github.com/cnlimiter/onebot-client/commit/d9f892e)) 40 | * 重新格式化代码,并优化性能 ([18f92bb](http://github.com/cnlimiter/onebot-client/commit/18f92bb)) 41 | 42 | 43 | ### build 44 | 45 | * update project dependencies- Update client version from 0.4.2 to 0.4.3 - Downgrade SDK version from 0.3.2 to 0.3.1 ([ef41a6f](http://github.com/cnlimiter/onebot-client/commit/ef41a6f)) 46 | * change dependency configuration from implementation to shadow ([0b594d7](http://github.com/cnlimiter/onebot-client/commit/0b594d7)) 47 | * maven名更新 ([9e6c00b](http://github.com/cnlimiter/onebot-client/commit/9e6c00b)) 48 | * 添加gitignore ([e17e257](http://github.com/cnlimiter/onebot-client/commit/e17e257)) 49 | 50 | 51 | ### ci 52 | 53 | * 自动打包 ([1f21b51](http://github.com/cnlimiter/onebot-client/commit/1f21b51)) 54 | 55 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 | # OneBot Client 5 | 6 | _✨ 基于java开发的 [OneBot](https://github.com/howmanybots/onebot/blob/master/README.md) 协议客户端✨_ 7 | 8 |
9 |
10 |

11 | issues 12 | 13 | License 14 | 15 |

16 |

17 | 文档 | 18 | QuickStart 19 |

20 | 21 | 22 | # QuickStart 23 | 24 | ### 使用api进行请求 25 | ```java 26 | public class WebSocketClientTest { 27 | public static OneBotClient onebot; 28 | public static void sendApi(String[] args) { 29 | onebot = OneBotClient.create(new BotConfig("ws://127.0.0.1:8080"))//创建websocket客户端 30 | .open()//连接onebot服务端 31 | .registerEvents(new EventListeners());//注册事件监听器 32 | 33 | onebot.getBot().sendGroupMsg(123456, MsgUtils.builder().text("123").build(), true);//发送群消息 34 | GroupMemberInfoResp sender = onebot.getBot().getGroupMemberInfo(123456, 123456, false).getData();//获取响应的群成员信息 35 | System.out.println(sender.toString());//打印 36 | } 37 | } 38 | ``` 39 | 40 | ### 事件监听示例 41 | ```java 42 | public class EventListeners implements Listener{ 43 | @SubscribeEvent 44 | public void onGroup(GroupMessageEvent event){ 45 | System.out.println(event); 46 | } 47 | } 48 | 49 | public class WebSocketClientTest { 50 | public static OneBotClient onebot; 51 | public static void main(String[] args){ 52 | onebot = OneBotClient.create(new BotConfig("ws://127.0.0.1:8080"))//创建websocket客户端 53 | .open()//连接onebot服务端 54 | .registerEvents(new EventListeners());//注册事件监听器 55 | } 56 | 57 | public static void stopped() { 58 | if (onebot != null) onebot.close(); 59 | } 60 | } 61 | ``` 62 | 63 | # Client 64 | 65 | OneBot-Client 以 [OneBot-v11](https://github.com/howmanybots/onebot/tree/master/v11/specs) 标准协议进行开发,兼容所有支持正向WebSocket的OneBot协议端 66 | 67 | | 项目地址 | 核心作者 | 备注 | 68 | |-----------------------------------------------------------------------------------|----------------|-----------------------------------------------------------------------| 69 | | [Overflow](https://github.com/MrXiaoM/Overflow) | MrXiaoM | 实现 mirai 的无缝迁移 | 70 | | [Lagrange.Core](https://github.com/LagrangeDev/Lagrange.Core) | NepPure | C#实现 By Konata.Core | 71 | | [OpenShamrock](https://github.com/whitechi73/OpenShamrock) | whitechi73 | Xposed框架hook实现 | 72 | | [Gensokyo](https://github.com/Hoshinonyaruko/Gensokyo) | Hoshinonyaruko | 基于官方api 轻量 原生跨平台 | 73 | | [LLOnebot](https://github.com/LLOneBot/LLOneBot) | linyuchen | 使用[LiteLoaderQQNT](https://github.com/LiteLoaderQQNT/LiteLoaderQQNT) | 74 | 75 | # Credits 76 | 77 | * [OneBot](https://github.com/botuniverse/onebot) 78 | 79 | # License 80 | 81 | This product is licensed under the GNU General Public License version 3. The license is as published by the Free 82 | Software Foundation published at https://www.gnu.org/licenses/gpl-3.0.html. 83 | 84 | Alternatively, this product is licensed under the GNU Lesser General Public License version 3 for non-commercial use. 85 | The license is as published by the Free Software Foundation published at https://www.gnu.org/licenses/lgpl-3.0.html. 86 | 87 | Feel free to contact us if you have any questions about licensing or want to use the library in a commercial closed 88 | source product. 89 | 90 | # Thanks 91 | 92 | Thanks [JetBrains](https://www.jetbrains.com/?from=onebot-client) Provide Free License Support OpenSource Project 93 | 94 | [](https://www.jetbrains.com/?from=onebot-client) 95 | 96 | ## Stargazers over time 97 | 98 | [![Stargazers over time](https://starchart.cc/cnlimiter/onebot-client.svg)](https://starchart.cc/cnlimiter/onebot-client) 99 | 100 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'maven-publish' 4 | id 'com.github.johnrengelman.shadow' version '7.1.2' 5 | } 6 | 7 | version = project.client_version 8 | group = project.maven_group 9 | 10 | def targetJavaVersion = 8 11 | 12 | tasks.withType(JavaCompile).configureEach { 13 | it.options.encoding = "UTF-8" 14 | if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { 15 | it.options.release = targetJavaVersion 16 | } 17 | } 18 | 19 | java { 20 | def javaVersion = JavaVersion.toVersion(targetJavaVersion) 21 | if (JavaVersion.current() < javaVersion) { 22 | toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) 23 | } 24 | archivesBaseName = project.archives_base_name 25 | 26 | } 27 | 28 | configurations { 29 | shadow 30 | implementation.extendsFrom shadow 31 | } 32 | 33 | 34 | repositories { 35 | mavenLocal() 36 | maven { url = "https://maven.nova-committee.cn/releases"} 37 | maven { url = "https://repo.papermc.io/repository/maven-public/" } 38 | mavenCentral() 39 | } 40 | 41 | 42 | dependencies { 43 | compileOnly("org.projectlombok:lombok:1.18.24") 44 | compileOnly("com.google.code.gson:gson:2.10.1") 45 | compileOnly("org.jetbrains:annotations:24.0.1") 46 | 47 | compileOnly("org.apache.logging.log4j:log4j-api:2.19.0") 48 | compileOnly("org.apache.logging.log4j:log4j-core:2.19.0") 49 | 50 | testImplementation("org.apache.logging.log4j:log4j-core:2.19.0") 51 | testImplementation("com.google.code.gson:gson:2.10.1") 52 | testCompileOnly("org.projectlombok:lombok:1.18.24") 53 | testRuntimeOnly 'org.slf4j:slf4j-simple:2.0.6' 54 | 55 | shadow "net.kyori:event-api:${eventbus_version}" 56 | shadow "net.kyori:event-method:${eventbus_version}" 57 | shadow "cn.evole.onebot:OneBot-SDK:${sdk_version}" 58 | shadow "org.java-websocket:Java-WebSocket:${websocket_version}" 59 | 60 | annotationProcessor("org.projectlombok:lombok:1.18.24") 61 | 62 | } 63 | 64 | artifacts { 65 | archives jar 66 | archives shadowJar 67 | } 68 | 69 | 70 | shadowJar { 71 | project.configurations.shadow.setTransitive(false); 72 | configurations = [project.configurations.shadow] 73 | relocate 'org.java_websocket', "cn.evole.onebot.sdk.websocket" 74 | relocate 'net.kyori.event', "cn.evole.onebot.eventbus" 75 | dependencies { 76 | exclude(dependency('org.slf4j:slf4j-api:2.0.6')) 77 | } 78 | archiveClassifier = "" 79 | archiveBaseName.set(project.archives_base_name) 80 | archiveVersion.set(project.client_version) 81 | 82 | } 83 | 84 | publishing { 85 | publications { 86 | shadow(MavenPublication) { publication -> 87 | project.shadow.component(publication) 88 | version = "${project.client_version}" 89 | artifactId = "${project.archives_base_name}" 90 | groupId = "${project.maven_group}" 91 | } 92 | } 93 | 94 | repositories { 95 | if (System.getenv('MAVEN_USERNAME') != null && System.getenv('MAVEN_PASSWORD') != null) { 96 | maven { 97 | name 's3' 98 | url = 'https://maven.nova-committee.cn/s3' 99 | 100 | credentials { 101 | username System.getenv('MAVEN_USERNAME') 102 | password System.getenv('MAVEN_PASSWORD') 103 | } 104 | } 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Done to increase the memory available to gradle. 2 | org.gradle.jvmargs=-Xmx1G 3 | 4 | 5 | maven_group=cn.evole.onebot 6 | archives_base_name=OneBot-Client 7 | client_version=0.4.3 8 | 9 | java_version=8 10 | sdk_version=0.3.1 11 | eventbus_version=3.0.0 12 | websocket_version=1.6.0 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cnlimiter/onebot-client/3cba0a110a6ee01b479c36ee4958e16dc6929f05/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'onebot-client' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/OneBotClient.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client; 2 | 3 | import cn.evole.onebot.client.connection.WSClient; 4 | import cn.evole.onebot.client.core.Bot; 5 | import cn.evole.onebot.client.core.BotConfig; 6 | import cn.evole.onebot.client.instances.action.ActionFactory; 7 | import cn.evole.onebot.client.instances.event.EventFactory; 8 | import cn.evole.onebot.client.instances.event.EventsBusImpl; 9 | import cn.evole.onebot.client.instances.event.MsgHandlerImpl; 10 | import cn.evole.onebot.client.interfaces.EventsBus; 11 | import cn.evole.onebot.client.interfaces.Listener; 12 | import lombok.Getter; 13 | import org.apache.logging.log4j.LogManager; 14 | import org.apache.logging.log4j.Logger; 15 | 16 | import java.net.URI; 17 | import java.util.concurrent.ExecutorService; 18 | import java.util.concurrent.Executors; 19 | import java.util.concurrent.TimeUnit; 20 | 21 | /** 22 | * @Project: onebot-client 23 | * @Author: cnlimiter 24 | * @CreateTime: 2024/1/26 22:58 25 | * @Description: 26 | */ 27 | 28 | @Getter 29 | public final class OneBotClient { 30 | private final ExecutorService eventExecutor = Executors.newFixedThreadPool(2, r -> new Thread(r, "OneBot Event")); 31 | private final ExecutorService wsPool = Executors.newFixedThreadPool(2, r -> new Thread(r, "OneBot WS")); 32 | private final Logger logger; 33 | private final BotConfig config; 34 | private final EventsBus eventsBus; 35 | private final MsgHandlerImpl msgHandler; 36 | private final EventFactory eventFactory; 37 | private final ActionFactory actionFactory; 38 | 39 | private WSClient ws = null; 40 | private Bot bot = null; 41 | 42 | private OneBotClient(BotConfig config) { 43 | this.logger = LogManager.getLogger("OneBot Client"); 44 | this.config = config; 45 | this.eventsBus = new EventsBusImpl(this); 46 | this.msgHandler = new MsgHandlerImpl(this); 47 | this.eventFactory = new EventFactory(this); 48 | this.actionFactory = new ActionFactory(this); 49 | } 50 | 51 | public static OneBotClient create(BotConfig config){ 52 | return new OneBotClient(config); 53 | } 54 | 55 | public static OneBotClient create(BotConfig config, Listener... listeners){ 56 | return new OneBotClient(config).registerEvents(listeners); 57 | } 58 | 59 | public OneBotClient open() { 60 | StringBuilder url = new StringBuilder(); 61 | wsPool.execute(() -> { 62 | url.append(config.getUrl()) 63 | .append(config.isMirai() ? "/all?verifyKey=" + config.getToken() + "&qq=" + config.getBotId() : ""); 64 | try { 65 | ws = new WSClient(this, URI.create(url.toString())); 66 | ws.connect(); 67 | bot = ws.createBot(); 68 | } catch (Exception e) { 69 | logger.error("▌ §c{}连接错误,请检查服务端是否开启 §a┈━═☆", URI.create(url.toString())); 70 | } 71 | }); 72 | return this; 73 | } 74 | 75 | public boolean close() { 76 | try { 77 | ws.getTimer().cancel(); 78 | ws.closeBlocking(); 79 | } catch (InterruptedException e) { 80 | logger.error("▌ §c{} 打断关闭进程的未知错误 §a┈━═☆", e); 81 | ws = null; 82 | } 83 | return threadStop(eventExecutor) && threadStop(wsPool); 84 | } 85 | 86 | public OneBotClient registerEvents(Listener... listeners){ 87 | for (Listener c : listeners){ 88 | getEventsBus().register(c); 89 | } 90 | return this; 91 | } 92 | 93 | private boolean threadStop(ExecutorService service){ 94 | if (!service.isShutdown()) { 95 | service.shutdown(); 96 | try { 97 | return service.awaitTermination(2, TimeUnit.SECONDS); 98 | } catch (InterruptedException e) { 99 | logger.error("▌ §c{} 打断关闭进程的未知错误 §a┈━═☆", e); 100 | service.shutdownNow(); 101 | Thread.currentThread().interrupt(); 102 | } 103 | } 104 | return false; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/annotations/EventBus.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.annotations; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @Project: onebot-client 10 | * @Author: cnlimiter 11 | * @CreateTime: 2024/2/20 10:12 12 | * @Description: 13 | */ 14 | @Target({ElementType.TYPE}) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | public @interface EventBus { 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/annotations/SubscribeEvent.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.annotations; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * @Project: onebot-client 10 | * @Author: cnlimiter 11 | * @CreateTime: 2024/1/26 23:09 12 | * @Description: 13 | */ 14 | 15 | @Target({ElementType.METHOD}) 16 | @Retention(RetentionPolicy.RUNTIME) 17 | public @interface SubscribeEvent { 18 | /** 19 | * 内部注册的处理器优先度更高 20 | * @return 是否内部注册 21 | */ 22 | boolean internal() default false; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/connection/WSClient.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.connection; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import cn.evole.onebot.client.core.Bot; 5 | import lombok.Getter; 6 | import org.java_websocket.client.WebSocketClient; 7 | import org.java_websocket.handshake.ServerHandshake; 8 | 9 | import java.net.ConnectException; 10 | import java.net.URI; 11 | import java.util.Timer; 12 | import java.util.TimerTask; 13 | 14 | /** 15 | * @Project: onebot-client 16 | * @Author: cnlimiter 17 | * @CreateTime: 2023/4/4 2:20 18 | * @Description: 19 | */ 20 | public class WSClient extends WebSocketClient { 21 | @Getter private final Timer timer = new Timer(); 22 | private final OneBotClient client; 23 | private int reconnectTimes = 1; 24 | public WSClient(OneBotClient client, URI uri) { 25 | super(uri); 26 | this.client = client; 27 | this.setConnectionLostTimeout(0); 28 | addHeader("User-Agent", "OneBot Client v4"); 29 | addHeader("x-client-role", "Universal"); // koishi-adapter-onebot 需要这个字段 30 | if (!client.getConfig().getToken().isEmpty()) addHeader("Authorization", "Bearer " + client.getConfig().getToken()); 31 | if (client.getConfig().getBotId() != 0) addHeader("X-Self-ID", String.valueOf(client.getConfig().getBotId())); 32 | } 33 | 34 | public Bot createBot(){ 35 | return new Bot(this, client.getActionFactory()); 36 | } 37 | 38 | @Override 39 | public void onOpen(ServerHandshake handshake) { 40 | client.getLogger().info("▌ §c已连接到服务器 {} §a┈━═☆", getURI()); 41 | reconnectTimes = 1; 42 | //handshake.iterateHttpFields().forEachRemaining(s -> System.out.println(s + ": " + handshake.getFieldValue(s))); 43 | } 44 | 45 | @Override 46 | public void onMessage(String message) { 47 | client.getMsgHandler().handle(message); 48 | } 49 | 50 | @Override 51 | public void onClose(int code, String reason, boolean remote) { 52 | if (client.getConfig().isReconnect() && remote && reconnectTimes <= client.getConfig().getReconnectMaxTimes()) { 53 | reconnectWebsocket(); 54 | } else client.getLogger().info("▌ §c服务器{}因{}已关闭", getURI(), reason); 55 | 56 | } 57 | 58 | @Override 59 | public void onError(Exception ex) { 60 | if (ex instanceof ConnectException && ex.getMessage().equals("Connection refused: connect") 61 | && client.getConfig().isReconnect() 62 | && reconnectTimes <= client.getConfig().getReconnectMaxTimes()) { 63 | reconnectWebsocket(); 64 | } else client.getLogger().error("▌ §c服务器{}出现错误{}或未连接§a┈━═☆", getURI(), ex.getLocalizedMessage()); 65 | } 66 | 67 | @Override 68 | public void send(String text) { 69 | if (isOpen()) { 70 | super.send(text); 71 | client.getLogger().debug("▌ §c向服务端{}发送{}", getURI(), text); 72 | } else { 73 | client.getLogger().debug("▌ §c向服务端{}发送{}失败", getURI(), text); 74 | } 75 | } 76 | 77 | @Override 78 | public void reconnect() { 79 | reconnectTimes++; 80 | super.reconnect(); 81 | if (reconnectTimes == client.getConfig().getReconnectMaxTimes() + 1) { 82 | client.getLogger().info("▌ §c连接至{}已达到最大次数", getURI()); 83 | } 84 | } 85 | 86 | public void reconnectWebsocket() { 87 | TimerTask timerTask = new TimerTask() { 88 | @Override 89 | public void run() { 90 | reconnect(); 91 | } 92 | }; 93 | timer.schedule(timerTask, client.getConfig().getReconnectInterval() * 1000L); 94 | } 95 | 96 | 97 | public void stopWithoutReconnect(int code, String reason) { 98 | timer.cancel(); 99 | close(code, reason); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/core/Bot.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.core; 2 | 3 | 4 | import cn.evole.onebot.client.instances.action.ActionFactory; 5 | import cn.evole.onebot.sdk.action.BaseBot; 6 | import cn.evole.onebot.sdk.action.misc.ActionData; 7 | import cn.evole.onebot.sdk.action.misc.ActionList; 8 | import cn.evole.onebot.sdk.action.misc.ActionPath; 9 | import cn.evole.onebot.sdk.action.misc.ActionRaw; 10 | import cn.evole.onebot.sdk.entity.Anonymous; 11 | import cn.evole.onebot.sdk.entity.ArrayMsg; 12 | import cn.evole.onebot.sdk.entity.GuildMsgId; 13 | import cn.evole.onebot.sdk.entity.MsgId; 14 | import cn.evole.onebot.sdk.enums.ActionType; 15 | import cn.evole.onebot.sdk.event.message.WholeMessageEvent; 16 | import cn.evole.onebot.sdk.response.contact.FriendInfoResp; 17 | import cn.evole.onebot.sdk.response.contact.LoginInfoResp; 18 | import cn.evole.onebot.sdk.response.contact.StrangerInfoResp; 19 | import cn.evole.onebot.sdk.response.contact.UnidirectionalFriendListResp; 20 | import cn.evole.onebot.sdk.response.group.*; 21 | import cn.evole.onebot.sdk.response.guild.*; 22 | import cn.evole.onebot.sdk.response.misc.*; 23 | import cn.evole.onebot.sdk.util.GsonUtils; 24 | import com.google.gson.JsonArray; 25 | import com.google.gson.JsonObject; 26 | import com.google.gson.reflect.TypeToken; 27 | import lombok.Getter; 28 | import lombok.Setter; 29 | import lombok.val; 30 | import org.java_websocket.WebSocket; 31 | 32 | import java.util.List; 33 | import java.util.Map; 34 | 35 | /** 36 | * @Project: onebot-client 37 | * @Author: cnlimiter 38 | * @CreateTime: 2022/9/14 15:19 39 | * @Description: 40 | */ 41 | @SuppressWarnings("unused") 42 | public class Bot implements BaseBot { 43 | private long selfId; 44 | 45 | private final ActionFactory actionFactory; 46 | 47 | @Getter 48 | @Setter 49 | private WebSocket channel; 50 | 51 | /** 52 | * @param channel {@link WebSocket} 53 | * @param actionFactory {@link ActionFactory} 54 | */ 55 | public Bot(WebSocket channel, ActionFactory actionFactory) { 56 | this.channel = channel; 57 | this.actionFactory = actionFactory; 58 | } 59 | 60 | @Override 61 | public long getSelfId() { 62 | return this.selfId; 63 | } 64 | 65 | /** 66 | * 发送消息 67 | * 68 | * @param event {@link WholeMessageEvent} 69 | * @param msg 要发送的内容 70 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 71 | * @return {@link ActionData} of {@link MsgId} 72 | */ 73 | public ActionData sendMsg(WholeMessageEvent event, String msg, boolean autoEscape) { 74 | if ("private".equals(event.getMessageType())) { 75 | return sendPrivateMsg(event.getUserId(), msg, autoEscape); 76 | } 77 | if ("group".equals(event.getMessageType())) { 78 | return sendGroupMsg(event.getGroupId(), msg, autoEscape); 79 | } 80 | return null; 81 | } 82 | 83 | /** 84 | * 发送消息 85 | * 86 | * @param event {@link WholeMessageEvent} 87 | * @param msg 消息链 88 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 89 | * @return result {@link ActionData} of {@link MsgId} 90 | */ 91 | @Override 92 | public ActionData sendMsg(WholeMessageEvent event, List msg, boolean autoEscape) { 93 | if ("private".equals(event.getMessageType())) { 94 | return sendPrivateMsg(event.getUserId(), msg, autoEscape); 95 | } 96 | if ("group".equals(event.getMessageType())) { 97 | return sendGroupMsg(event.getGroupId(), msg, autoEscape); 98 | } 99 | return null; 100 | } 101 | 102 | /** 103 | * 发送私聊消息 104 | * 105 | * @param userId 对方 QQ 号 106 | * @param msg 要发送的内容(string) 107 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 108 | * @return {@link ActionData} of {@link MsgId} 109 | */ 110 | public ActionData sendPrivateMsg(long userId, String msg, boolean autoEscape) { 111 | val action = ActionType.SEND_PRIVATE_MSG; 112 | val params = new JsonObject(); 113 | params.addProperty("user_id", userId); 114 | params.addProperty("message", msg); 115 | params.addProperty("auto_escape", autoEscape); 116 | val result = actionFactory.action(channel, action, params); 117 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 118 | } 119 | 120 | /** 121 | * 发送私聊消息 122 | * 123 | * @param userId 对方 QQ 号 124 | * @param msg 消息链 125 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 126 | * @return result {@link ActionData} of {@link MsgId} 127 | */ 128 | @Override 129 | public ActionData sendPrivateMsg(long userId, List msg, boolean autoEscape) { 130 | val action = ActionType.SEND_PRIVATE_MSG; 131 | val params = new JsonObject(); 132 | params.addProperty("user_id", userId); 133 | params.addProperty("message", GsonUtils.getGson().toJson(msg)); 134 | params.addProperty("auto_escape", autoEscape); 135 | val result = actionFactory.action(channel, action, params); 136 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 137 | } 138 | 139 | /** 140 | * 临时会话 141 | * 142 | * @param groupId 主动发起临时会话群号(机器人本身必须是管理员/群主) 143 | * @param userId 对方 QQ 号 144 | * @param msg 要发送的内容 145 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 146 | * @return result {@link ActionData} of {@link MsgId} 147 | */ 148 | @Override 149 | public ActionData sendPrivateMsg(long groupId, long userId, String msg, boolean autoEscape) { 150 | val action = ActionType.SEND_PRIVATE_MSG; 151 | val params = new JsonObject(); 152 | params.addProperty("group_id", groupId); 153 | params.addProperty("user_id", userId); 154 | params.addProperty("message", msg); 155 | params.addProperty("auto_escape", autoEscape); 156 | val result = actionFactory.action(channel, action, params); 157 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 158 | } 159 | 160 | /** 161 | * 临时会话 162 | * 163 | * @param groupId 主动发起临时会话群号(机器人本身必须是管理员/群主) 164 | * @param userId 对方 QQ 号 165 | * @param msg 消息链 166 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 167 | * @return result {@link ActionData} of {@link MsgId} 168 | */ 169 | @Override 170 | public ActionData sendPrivateMsg(long groupId, long userId, List msg, boolean autoEscape) { 171 | val action = ActionType.SEND_PRIVATE_MSG; 172 | val params = new JsonObject(); 173 | params.addProperty("group_id", groupId); 174 | params.addProperty("user_id", userId); 175 | params.addProperty("message", GsonUtils.getGson().toJson(msg)); 176 | params.addProperty("auto_escape", autoEscape); 177 | val result = actionFactory.action(channel, action, params); 178 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 179 | } 180 | 181 | /** 182 | * 发送私聊消息 183 | * 184 | * @param userId 对方 QQ 号 185 | * @param msg 要发送的内容(array) 186 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 187 | * @return {@link ActionData} of {@link MsgId} 188 | */ 189 | public ActionData sendPrivateMsg(long userId, JsonArray msg, boolean autoEscape) { 190 | val action = ActionType.SEND_PRIVATE_MSG; 191 | val params = new JsonObject(); 192 | params.addProperty("user_id", userId); 193 | params.add("message", msg); 194 | params.addProperty("auto_escape", autoEscape); 195 | val result = actionFactory.action(channel, action, params); 196 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 197 | } 198 | 199 | /** 200 | * 发送群消息 201 | * 202 | * @param groupId 群号 203 | * @param msg 要发送的内容(string) 204 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 205 | * @return {@link ActionData} of {@link MsgId} 206 | */ 207 | public ActionData sendGroupMsg(long groupId, String msg, boolean autoEscape) { 208 | val action = ActionType.SEND_GROUP_MSG; 209 | val params = new JsonObject(); 210 | params.addProperty("group_id", groupId); 211 | params.addProperty("message", msg); 212 | params.addProperty("auto_escape", autoEscape); 213 | val result = actionFactory.action(channel, action, params); 214 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 215 | } 216 | 217 | @Override 218 | public ActionData sendGroupMsg(long groupId, List msg, boolean autoEscape) { 219 | val action = ActionType.SEND_GROUP_MSG; 220 | val params = new JsonObject(); 221 | params.addProperty("group_id", groupId); 222 | params.addProperty("message", GsonUtils.getGson().toJson(msg)); 223 | params.addProperty("auto_escape", autoEscape); 224 | val result = actionFactory.action(channel, action, params); 225 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 226 | } 227 | 228 | @Override 229 | public ActionData sendGroupMsg(long groupId, long userId, String msg, boolean autoEscape) { 230 | val action = ActionType.SEND_GROUP_MSG; 231 | val params = new JsonObject(); 232 | params.addProperty("group_id", groupId); 233 | params.addProperty("user_id", userId); 234 | params.addProperty("message", msg); 235 | params.addProperty("auto_escape", autoEscape); 236 | val result = actionFactory.action(channel, action, params); 237 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 238 | } 239 | 240 | @Override 241 | public ActionData sendGroupMsg(long groupId, long userId, List msg, boolean autoEscape) { 242 | val action = ActionType.SEND_GROUP_MSG; 243 | val params = new JsonObject(); 244 | params.addProperty("group_id", groupId); 245 | params.addProperty("user_id", userId); 246 | params.addProperty("message", GsonUtils.getGson().toJson(msg)); 247 | params.addProperty("auto_escape", autoEscape); 248 | val result = actionFactory.action(channel, action, params); 249 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 250 | } 251 | 252 | /** 253 | * 发送群消息 254 | * 255 | * @param groupId 群号 256 | * @param msg 要发送的内容(array) 257 | * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 258 | * @return {@link ActionData} of {@link MsgId} 259 | */ 260 | public ActionData sendGroupMsg(long groupId, JsonArray msg, boolean autoEscape) { 261 | val action = ActionType.SEND_GROUP_MSG; 262 | val params = new JsonObject(); 263 | params.addProperty("group_id", groupId); 264 | params.add("message", msg); 265 | params.addProperty("auto_escape", autoEscape); 266 | 267 | val result = actionFactory.action(channel, action, params); 268 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() {}.getType()) : null; 269 | 270 | } 271 | 272 | /** 273 | * 获取频道成员列表 274 | * 由于频道人数较多(数万), 请尽量不要全量拉取成员列表, 这将会导致严重的性能问题 275 | * 尽量使用 getGuildMemberProfile 接口代替全量拉取 276 | * nextToken 为空的情况下, 将返回第一页的数据, 并在返回值附带下一页的 token 277 | * 278 | * @param guildId 频道ID 279 | * @param nextToken 翻页Token 280 | * @return {@link ActionData} of {@link GuildMemberListResp} 281 | */ 282 | public ActionData getGuildMemberList(String guildId, String nextToken) { 283 | val action = ActionType.GET_GUILD_LIST; 284 | val params = new JsonObject(); 285 | params.addProperty("guild_id", guildId); 286 | params.addProperty("next_token", nextToken); 287 | 288 | val result = actionFactory.action(channel, action, params); 289 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 290 | }.getType()) : null; 291 | } 292 | 293 | /** 294 | * 发送信息到子频道 295 | * 296 | * @param guildId 频道 ID 297 | * @param channelId 子频道 ID 298 | * @param msg 要发送的内容(string) 299 | * @return {@link ActionData} of {@link GuildMsgId} 300 | */ 301 | public ActionData sendGuildMsg(String guildId, String channelId, String msg) { 302 | val action = ActionType.SEND_GUILD_CHANNEL_MSG; 303 | val params = new JsonObject(); 304 | params.addProperty("guild_id", guildId); 305 | params.addProperty("channel_id", channelId); 306 | params.addProperty("message", msg); 307 | 308 | val result = actionFactory.action(channel, action, params); 309 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 310 | }.getType()) : null; 311 | } 312 | 313 | /** 314 | * 发送信息到子频道 315 | * 316 | * @param guildId 频道 ID 317 | * @param channelId 子频道 ID 318 | * @param msg 要发送的内容(array) 319 | * @return {@link ActionData} of {@link GuildMsgId} 320 | */ 321 | public ActionData sendGuildMsg(String guildId, String channelId, JsonArray msg) { 322 | val action = ActionType.SEND_GUILD_CHANNEL_MSG; 323 | val params = new JsonObject(); 324 | params.addProperty("guild_id", guildId); 325 | params.addProperty("channel_id", channelId); 326 | params.add("message", msg); 327 | 328 | val result = actionFactory.action(channel, action, params); 329 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 330 | }.getType()) : null; 331 | } 332 | 333 | /** 334 | * 获取频道消息 335 | * 336 | * @param guildMsgId 频道 ID 337 | * @param noCache 是否使用缓存 338 | * @return {@link ActionData} of {@link GetGuildMsgResp} 339 | */ 340 | public ActionData getGuildMsg(String guildMsgId, boolean noCache) { 341 | val action = ActionType.GET_GUILD_MSG; 342 | val params = new JsonObject(); 343 | params.addProperty("message_id", guildMsgId); 344 | params.addProperty("no_cache", noCache); 345 | 346 | val result = actionFactory.action(channel, action, params); 347 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 348 | }.getType()) : null; 349 | } 350 | 351 | /** 352 | * 获取频道系统内 BOT 的资料 353 | * 354 | * @return {@link ActionData} of {@link GuildServiceProfileResp} 355 | */ 356 | public ActionData getGuildServiceProfile() { 357 | val action = ActionType.GET_GUILD_SERVICE_PROFILE; 358 | val result = actionFactory.action(channel, action, null); 359 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 360 | }.getType()) : null; 361 | } 362 | 363 | /** 364 | * 获取频道列表 365 | * 366 | * @return {@link ActionList} of {@link GuildListResp} 367 | */ 368 | public ActionList getGuildList() { 369 | val action = ActionType.GET_GUILD_LIST; 370 | val result = actionFactory.action(channel, action, null); 371 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 372 | }.getType()) : null; 373 | } 374 | 375 | /** 376 | * 通过访客获取频道元数据 377 | * 378 | * @param guildId 频道 ID 379 | * @return {@link ActionData} of {@link GuildMetaByGuestResp} 380 | */ 381 | public ActionData getGuildMetaByGuest(String guildId) { 382 | val action = ActionType.GET_GUILD_META_BY_GUEST; 383 | val params = new JsonObject(); 384 | params.addProperty("guild_id", guildId); 385 | 386 | val result = actionFactory.action(channel, action, params); 387 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 388 | }.getType()) : null; 389 | } 390 | 391 | /** 392 | * 获取子频道列表 393 | * 394 | * @param guildId 频道 ID 395 | * @param noCache 是否无视缓存 396 | * @return {@link ActionList} of {@link ChannelInfoResp} 397 | */ 398 | public ActionList getGuildChannelList(String guildId, boolean noCache) { 399 | val action = ActionType.GET_GUILD_CHANNEL_LIST; 400 | val params = new JsonObject(); 401 | params.addProperty("guild_id", guildId); 402 | params.addProperty("no_cache", noCache); 403 | 404 | val result = actionFactory.action(channel, action, params); 405 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 406 | }.getType()) : null; 407 | } 408 | 409 | /** 410 | * 单独获取频道成员信息 411 | * 412 | * @param guildId 频道ID 413 | * @param userId 用户ID 414 | * @return {@link ActionData} of {@link GuildMemberProfileResp} 415 | */ 416 | public ActionData getGuildMemberProfile(String guildId, String userId) { 417 | val action = ActionType.GET_GUILD_MEMBER_PROFILE; 418 | val params = new JsonObject(); 419 | params.addProperty("guild_id", guildId); 420 | params.addProperty("user_id", userId); 421 | 422 | val result = actionFactory.action(channel, action, params); 423 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 424 | }.getType()) : null; 425 | } 426 | 427 | /** 428 | * 获取消息 429 | * 430 | * @param msgId 消息 ID 431 | * @return {@link ActionData} of {@link GetMsgResp} 432 | */ 433 | public ActionData getMsg(int msgId) { 434 | val action = ActionType.GET_MSG; 435 | val params = new JsonObject(); 436 | params.addProperty("message_id", msgId); 437 | 438 | val result = actionFactory.action(channel, action, params); 439 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 440 | }.getType()) : null; 441 | } 442 | 443 | /** 444 | * 撤回消息 445 | * 446 | * @param msgId 消息 ID 447 | * @return {@link ActionRaw} 448 | */ 449 | public ActionRaw deleteMsg(int msgId) { 450 | val action = ActionType.DELETE_MSG; 451 | val params = new JsonObject(); 452 | params.addProperty("message_id", msgId); 453 | 454 | val result = actionFactory.action(channel, action, params); 455 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 456 | } 457 | 458 | @Override 459 | public ActionRaw deleteMsg(long groupId, long userId, int msgId) { 460 | val action = ActionType.DELETE_MSG; 461 | val params = new JsonObject(); 462 | params.addProperty("message_id", msgId); 463 | params.addProperty("user_id", userId); 464 | params.addProperty("group_id", groupId); 465 | val result = actionFactory.action(channel, action, params); 466 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 467 | } 468 | 469 | /** 470 | * 群组踢人 471 | * 472 | * @param groupId 群号 473 | * @param userId 要踢的 QQ 号 474 | * @param rejectAddRequest 拒绝此人的加群请求 (默认false) 475 | * @return {@link ActionRaw} 476 | */ 477 | public ActionRaw setGroupKick(long groupId, long userId, boolean rejectAddRequest) { 478 | val action = ActionType.SET_GROUP_KICK; 479 | val params = new JsonObject(); 480 | params.addProperty("group_id", groupId); 481 | params.addProperty("user_id", userId); 482 | params.addProperty("reject_add_request", rejectAddRequest); 483 | 484 | val result = actionFactory.action(channel, action, params); 485 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 486 | } 487 | 488 | /** 489 | * 群组单人禁言 490 | * 491 | * @param groupId 群号 492 | * @param userId 要禁言的 QQ 号 493 | * @param duration 禁言时长, 单位秒, 0 表示取消禁言 (默认30 * 60) 494 | * @return {@link ActionRaw} 495 | */ 496 | public ActionRaw setGroupBan(long groupId, long userId, int duration) { 497 | val action = ActionType.SET_GROUP_BAN; 498 | val params = new JsonObject(); 499 | params.addProperty("group_id", groupId); 500 | params.addProperty("user_id", userId); 501 | params.addProperty("duration", duration); 502 | 503 | val result = actionFactory.action(channel, action, params); 504 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 505 | } 506 | 507 | /** 508 | * 全体禁言 509 | * 510 | * @param groupId 群号 511 | * @param enable 是否禁言(默认True,False为取消禁言) 512 | * @return {@link ActionRaw} 513 | */ 514 | public ActionRaw setGroupWholeBan(long groupId, boolean enable) { 515 | val action = ActionType.SET_GROUP_WHOLE_BAN; 516 | val params = new JsonObject(); 517 | params.addProperty("group_id", groupId); 518 | params.addProperty("enable", enable); 519 | 520 | val result = actionFactory.action(channel, action, params); 521 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 522 | } 523 | 524 | /** 525 | * 群组设置管理员 526 | * 527 | * @param groupId 群号 528 | * @param userId 要设置管理员的 QQ 号 529 | * @param enable true 为设置,false 为取消 530 | * @return {@link ActionRaw} 531 | */ 532 | public ActionRaw setGroupAdmin(long groupId, long userId, boolean enable) { 533 | val action = ActionType.SET_GROUP_ADMIN; 534 | val params = new JsonObject(); 535 | params.addProperty("group_id", groupId); 536 | params.addProperty("user_id", userId); 537 | params.addProperty("enable", enable); 538 | 539 | val result = actionFactory.action(channel, action, params); 540 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 541 | } 542 | 543 | /** 544 | * 群组匿名 545 | * 546 | * @param groupId 群号 547 | * @param enable 是否允许匿名聊天 548 | * @return {@link ActionRaw} 549 | */ 550 | public ActionRaw setGroupAnonymous(long groupId, boolean enable) { 551 | val action = ActionType.SET_GROUP_ANONYMOUS; 552 | val params = new JsonObject(); 553 | params.addProperty("group_id", groupId); 554 | params.addProperty("enable", enable); 555 | 556 | val result = actionFactory.action(channel, action, params); 557 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 558 | } 559 | 560 | /** 561 | * 设置群名片(群备注) 562 | * 563 | * @param groupId 群号 564 | * @param userId 要设置的 QQ 号 565 | * @param card 群名片内容,不填或空字符串表示删除群名片 566 | * @return {@link ActionRaw} 567 | */ 568 | public ActionRaw setGroupCard(long groupId, long userId, String card) { 569 | val action = ActionType.SET_GROUP_CARD; 570 | val params = new JsonObject(); 571 | params.addProperty("group_id", groupId); 572 | params.addProperty("user_id", userId); 573 | params.addProperty("card", card); 574 | 575 | val result = actionFactory.action(channel, action, params); 576 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 577 | } 578 | 579 | /** 580 | * 设置群名 581 | * 582 | * @param groupId 群号 583 | * @param groupName 新群名 584 | * @return {@link ActionRaw} 585 | */ 586 | public ActionRaw setGroupName(long groupId, String groupName) { 587 | val action = ActionType.SET_GROUP_NAME; 588 | val params = new JsonObject(); 589 | params.addProperty("group_id", groupId); 590 | params.addProperty("group_name", groupName); 591 | 592 | val result = actionFactory.action(channel, action, params); 593 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 594 | } 595 | 596 | /** 597 | * 退出群组 598 | * 599 | * @param groupId 群号 600 | * @param isDismiss 是否解散, 如果登录号是群主, 则仅在此项为 true 时能够解散 601 | * @return {@link ActionRaw} 602 | */ 603 | public ActionRaw setGroupLeave(long groupId, boolean isDismiss) { 604 | val action = ActionType.SET_GROUP_LEAVE; 605 | val params = new JsonObject(); 606 | params.addProperty("group_id", groupId); 607 | params.addProperty("is_dismiss", isDismiss); 608 | 609 | val result = actionFactory.action(channel, action, params); 610 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 611 | } 612 | 613 | /** 614 | * 设置群组专属头衔 615 | * 616 | * @param groupId 群号 617 | * @param userId 要设置的 QQ 号 618 | * @param specialTitle 专属头衔,不填或空字符串表示删除专属头衔 619 | * @param duration 专属头衔有效期,单位秒,-1 表示永久,不过此项似乎没有效果,可能是只有某些特殊的时间长度有效,有待测试 620 | * @return {@link ActionRaw} 621 | */ 622 | public ActionRaw setGroupSpecialTitle(long groupId, long userId, String specialTitle, int duration) { 623 | val action = ActionType.SET_GROUP_SPECIAL_TITLE; 624 | val params = new JsonObject(); 625 | params.addProperty("group_id", groupId); 626 | params.addProperty("user_id", userId); 627 | params.addProperty("special_title", specialTitle); 628 | params.addProperty("duration", duration); 629 | 630 | val result = actionFactory.action(channel, action, params); 631 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 632 | } 633 | 634 | /** 635 | * 处理加好友请求 636 | * 637 | * @param flag 加好友请求的 flag(需从上报的数据中获得) 638 | * @param approve 是否同意请求(默认为true) 639 | * @param remark 添加后的好友备注(仅在同意时有效) 640 | * @return {@link ActionRaw} 641 | */ 642 | public ActionRaw setFriendAddRequest(String flag, boolean approve, String remark) { 643 | val action = ActionType.SET_FRIEND_ADD_REQUEST; 644 | val params = new JsonObject(); 645 | params.addProperty("flag", flag); 646 | params.addProperty("approve", approve); 647 | params.addProperty("remark", remark); 648 | 649 | val result = actionFactory.action(channel, action, params); 650 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 651 | } 652 | 653 | /** 654 | * 处理加群请求/邀请 655 | * 656 | * @param flag 加群请求的 flag(需从上报的数据中获得) 657 | * @param subType add 或 invite,请求类型(需要和上报消息中的 sub_type 字段相符) 658 | * @param approve 是否同意请求/邀请 659 | * @param reason 拒绝理由(仅在拒绝时有效) 660 | * @return {@link ActionRaw} 661 | */ 662 | public ActionRaw setGroupAddRequest(String flag, String subType, boolean approve, String reason) { 663 | val action = ActionType.SET_GROUP_ADD_REQUEST; 664 | val params = new JsonObject(); 665 | params.addProperty("flag", flag); 666 | params.addProperty("sub_type", subType); 667 | params.addProperty("approve", approve); 668 | params.addProperty("reason", reason); 669 | 670 | val result = actionFactory.action(channel, action, params); 671 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 672 | } 673 | 674 | /** 675 | * 获取登录号信息 676 | * 677 | * @return {@link ActionData} of @{@link LoginInfoResp} 678 | */ 679 | public ActionData getLoginInfo() { 680 | val action = ActionType.GET_LOGIN_INFO; 681 | val result = actionFactory.action(channel, action, null); 682 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 683 | }.getType()) : null; 684 | } 685 | 686 | /** 687 | * 获取陌生人信息 688 | * 689 | * @param userId QQ 号 690 | * @param noCache 是否不使用缓存(使用缓存可能更新不及时,但响应更快) 691 | * @return {@link ActionData} of {@link StrangerInfoResp} 692 | */ 693 | public ActionData getStrangerInfo(long userId, boolean noCache) { 694 | val action = ActionType.GET_STRANGER_INFO; 695 | val params = new JsonObject(); 696 | params.addProperty("user_id", userId); 697 | params.addProperty("no_cache", noCache); 698 | 699 | val result = actionFactory.action(channel, action, params); 700 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 701 | }.getType()) : null; 702 | } 703 | 704 | /** 705 | * 获取好友列表 706 | * 707 | * @return {@link ActionList} of {@link FriendInfoResp} 708 | */ 709 | public ActionList getFriendList() { 710 | val action = ActionType.GET_FRIEND_LIST; 711 | val result = actionFactory.action(channel, action, null); 712 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 713 | }.getType()) : null; 714 | } 715 | 716 | /** 717 | * 删除好友 718 | * 719 | * @param friendId 好友 QQ 号 720 | * @return {@link ActionRaw} 721 | */ 722 | public ActionRaw deleteFriend(long friendId) { 723 | val action = ActionType.DELETE_FRIEND; 724 | val params = new JsonObject(); 725 | params.addProperty("friend_id", friendId); 726 | 727 | val result = actionFactory.action(channel, action, params); 728 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 729 | } 730 | 731 | /** 732 | * 获取群信息 733 | * 734 | * @param groupId 群号 735 | * @param noCache 是否不使用缓存(使用缓存可能更新不及时,但响应更快) 736 | * @return {@link ActionData} of {@link GroupInfoResp} 737 | */ 738 | public ActionData getGroupInfo(long groupId, boolean noCache) { 739 | val action = ActionType.GET_GROUP_INFO; 740 | val params = new JsonObject(); 741 | params.addProperty("group_id", groupId); 742 | params.addProperty("no_cache", noCache); 743 | 744 | val result = actionFactory.action(channel, action, params); 745 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 746 | }.getType()) : null; 747 | } 748 | 749 | /** 750 | * 获取群列表 751 | * 752 | * @return {@link ActionList} of {@link GroupInfoResp} 753 | */ 754 | public ActionList getGroupList() { 755 | val action = ActionType.GET_GROUP_LIST; 756 | val result = actionFactory.action(channel, action, null); 757 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 758 | }.getType()) : null; 759 | } 760 | 761 | /** 762 | * 获取群成员信息 763 | * 764 | * @param groupId 群号 765 | * @param userId QQ 号 766 | * @param noCache 是否不使用缓存(使用缓存可能更新不及时,但响应更快) 767 | * @return {@link ActionData} of {@link GroupMemberInfoResp} 768 | */ 769 | public ActionData getGroupMemberInfo(long groupId, long userId, boolean noCache) { 770 | val action = ActionType.GET_GROUP_MEMBER_INFO; 771 | val params = new JsonObject(); 772 | params.addProperty("group_id", groupId); 773 | params.addProperty("user_id", userId); 774 | params.addProperty("no_cache", noCache); 775 | 776 | val result = actionFactory.action(channel, action, params); 777 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 778 | }.getType()) : null; 779 | } 780 | 781 | /** 782 | * 获取群成员列表 783 | * 784 | * @param groupId 群号 785 | * @return {@link ActionList} of {@link GroupMemberInfoResp} 786 | */ 787 | public ActionList getGroupMemberList(long groupId) { 788 | val action = ActionType.GET_GROUP_MEMBER_LIST; 789 | val params = new JsonObject(); 790 | params.addProperty("group_id", groupId); 791 | 792 | val result = actionFactory.action(channel, action, params); 793 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 794 | }.getType()) : null; 795 | } 796 | 797 | @Override 798 | public ActionList getGroupMemberList(long groupId, boolean noCache) { 799 | val action = ActionType.GET_GROUP_MEMBER_LIST; 800 | val params = new JsonObject(); 801 | params.addProperty("group_id", groupId); 802 | params.addProperty("no_cache", noCache); 803 | val result = actionFactory.action(channel, action, params); 804 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 805 | }.getType()) : null; 806 | } 807 | 808 | /** 809 | * 获取群荣誉信息 810 | * 811 | * @param groupId 群号 812 | * @param type 要获取的群荣誉类型, 可传入 talkative performer legend strong_newbie emotion 以分别获取单个类型的群荣誉数据, 或传入 all 获取所有数据 813 | * @return {@link ActionData} of {@link GroupHonorInfoResp} 814 | */ 815 | public ActionData getGroupHonorInfo(long groupId, String type) { 816 | val action = ActionType.GET_GROUP_HONOR_INFO; 817 | val params = new JsonObject(); 818 | params.addProperty("group_id", groupId); 819 | params.addProperty("type", type); 820 | 821 | val result = actionFactory.action(channel, action, params); 822 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 823 | }.getType()) : null; 824 | } 825 | 826 | /** 827 | * 检查是否可以发送图片 828 | * 829 | * @return {@link ActionData} of {@link BooleanResp} 830 | */ 831 | public ActionData canSendImage() { 832 | val action = ActionType.CAN_SEND_IMAGE; 833 | val result = actionFactory.action(channel, action, null); 834 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 835 | }.getType()) : null; 836 | } 837 | 838 | /** 839 | * 检查是否可以发送语音 840 | * 841 | * @return {@link ActionData} of {@link BooleanResp} 842 | */ 843 | public ActionData canSendRecord() { 844 | val action = ActionType.CAN_SEND_RECORD; 845 | val result = actionFactory.action(channel, action, null); 846 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 847 | }.getType()) : null; 848 | } 849 | 850 | /** 851 | * 设置群头像 852 | * 目前这个API在登录一段时间后因cookie失效而失效, 请考虑后使用 853 | * 854 | * @param groupId 群号 855 | * @param file 图片文件名(支持绝对路径,网络URL,Base64编码) 856 | * @param cache 表示是否使用已缓存的文件 (通过网络URL发送时有效, 1表示使用缓存, 0关闭关闭缓存, 默认为1) 857 | * @return {@link ActionRaw} 858 | */ 859 | public ActionRaw setGroupPortrait(long groupId, String file, int cache) { 860 | val action = ActionType.SET_GROUP_PORTRAIT; 861 | val params = new JsonObject(); 862 | params.addProperty("group_id", groupId); 863 | params.addProperty("file", file); 864 | params.addProperty("cache", cache); 865 | 866 | val result = actionFactory.action(channel, action, params); 867 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 868 | } 869 | 870 | /** 871 | * 检查链接安全性 872 | * 安全等级, 1: 安全 2: 未知 3: 危险 873 | * 874 | * @param url 需要检查的链接 875 | * @return {@link ActionData} of {@link CheckUrlSafelyResp} 876 | */ 877 | public ActionData checkUrlSafely(String url) { 878 | val action = ActionType.CHECK_URL_SAFELY; 879 | val params = new JsonObject(); 880 | params.addProperty("url", url); 881 | 882 | val result = actionFactory.action(channel, action, params); 883 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 884 | }.getType()) : null; 885 | } 886 | 887 | /** 888 | * 发送群公告 889 | * 890 | * @param groupId 群号 891 | * @param content 公告内容 892 | * @return {@link ActionRaw} 893 | */ 894 | public ActionRaw sendGroupNotice(long groupId, String content) { 895 | val action = ActionType.SEN_GROUP_NOTICE; 896 | val params = new JsonObject(); 897 | params.addProperty("group_id", groupId); 898 | params.addProperty("content", content); 899 | 900 | val result = actionFactory.action(channel, action, params); 901 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 902 | } 903 | 904 | /** 905 | * 获取群 @全体成员 剩余次数 906 | * 907 | * @param groupId 群号 908 | * @return {@link ActionData} of {@link GroupAtAllRemainResp} 909 | */ 910 | public ActionData getGroupAtAllRemain(long groupId) { 911 | val action = ActionType.GET_GROUP_AT_ALL_REMAIN; 912 | val params = new JsonObject(); 913 | params.addProperty("group_id", groupId); 914 | 915 | val result = actionFactory.action(channel, action, params); 916 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 917 | }.getType()) : null; 918 | } 919 | 920 | /** 921 | * 上传群文件 922 | * 在不提供 folder 参数的情况下默认上传到根目录 923 | * 只能上传本地文件, 需要上传 http 文件的话请先下载到本地 924 | * 925 | * @param groupId 群号 926 | * @param file 本地文件路径 927 | * @param name 储存名称 928 | * @param folder 父目录ID 929 | * @return {@link ActionRaw} 930 | */ 931 | public ActionRaw uploadGroupFile(long groupId, String file, String name, String folder) { 932 | val action = ActionType.UPLOAD_GROUP_FILE; 933 | val params = new JsonObject(); 934 | params.addProperty("group_id", groupId); 935 | params.addProperty("file", file); 936 | params.addProperty("name", name); 937 | params.addProperty("folder", folder); 938 | 939 | val result = actionFactory.action(channel, action, params); 940 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 941 | } 942 | 943 | /** 944 | * 上传群文件 945 | * 在不提供 folder 参数的情况下默认上传到根目录 946 | * 只能上传本地文件, 需要上传 http 文件的话请先下载到本地 947 | * 948 | * @param groupId 群号 949 | * @param file 本地文件路径 950 | * @param name 储存名称 951 | * @return {@link ActionRaw} 952 | */ 953 | public ActionRaw uploadGroupFile(long groupId, String file, String name) { 954 | val action = ActionType.UPLOAD_GROUP_FILE; 955 | val params = new JsonObject(); 956 | params.addProperty("group_id", groupId); 957 | params.addProperty("file", file); 958 | params.addProperty("name", name); 959 | 960 | val result = actionFactory.action(channel, action, params); 961 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 962 | } 963 | 964 | /** 965 | * 群组匿名用户禁言 966 | * 967 | * @param groupId 群号 968 | * @param anonymous 要禁言的匿名用户对象(群消息上报的 anonymous 字段) 969 | * @param duration 禁言时长,单位秒,无法取消匿名用户禁言 970 | * @return {@link ActionRaw} 971 | */ 972 | public ActionRaw setGroupAnonymousBan(long groupId, Anonymous anonymous, int duration) { 973 | val action = ActionType.SET_GROUP_ANONYMOUS_BAN; 974 | String an = GsonUtils.getGson().toJson(anonymous); 975 | val params = new JsonObject(); 976 | params.addProperty("group_id", groupId); 977 | params.add("anonymous", GsonUtils.parse(an)); 978 | params.addProperty("duration", duration); 979 | 980 | val result = actionFactory.action(channel, action, params); 981 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 982 | } 983 | 984 | 985 | /** 986 | * 群组匿名用户禁言 987 | * 988 | * @param groupId 群号 989 | * @param flag 要禁言的匿名用户的 flag(需从群消息上报的数据中获得) 990 | * @param duration 禁言时长,单位秒,无法取消匿名用户禁言 991 | * @return {@link ActionRaw} 992 | */ 993 | public ActionRaw setGroupAnonymousBan(long groupId, String flag, int duration) { 994 | val action = ActionType.SET_GROUP_ANONYMOUS_BAN; 995 | val params = new JsonObject(); 996 | params.addProperty("group_id", groupId); 997 | params.addProperty("flag", flag); 998 | params.addProperty("duration", duration); 999 | 1000 | val result = actionFactory.action(channel, action, params); 1001 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1002 | } 1003 | 1004 | /** 1005 | * 调用 go cq http 下载文件 1006 | * 1007 | * @param url 链接地址 1008 | * @param threadCount 下载线程数 1009 | * @param headers 自定义请求头 1010 | * @return {@link ActionData} of {@link DownloadFileResp} 1011 | */ 1012 | public ActionData downloadFile(String url, int threadCount, String headers) { 1013 | val action = ActionType.DOWNLOAD_FILE; 1014 | val params = new JsonObject(); 1015 | params.addProperty("url", url); 1016 | params.addProperty("thread_count", threadCount); 1017 | params.addProperty("headers", headers); 1018 | 1019 | val result = actionFactory.action(channel, action, params); 1020 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1021 | }.getType()) : null; 1022 | } 1023 | 1024 | /** 1025 | * 调用 go cq http 下载文件 1026 | * 1027 | * @param url 链接地址 1028 | * @return {@link ActionData} of {@link DownloadFileResp} 1029 | */ 1030 | public ActionData downloadFile(String url) { 1031 | val action = ActionType.DOWNLOAD_FILE; 1032 | val params = new JsonObject(); 1033 | params.addProperty("url", url); 1034 | 1035 | val result = actionFactory.action(channel, action, params); 1036 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1037 | }.getType()) : null; 1038 | 1039 | } 1040 | 1041 | 1042 | 1043 | /** 1044 | * 获取群根目录文件列表 1045 | * 1046 | * @param groupId 群号 1047 | * @return {@link ActionData} of {@link GroupFilesResp} 1048 | */ 1049 | public ActionData getGroupRootFiles(long groupId) { 1050 | val action = ActionType.GET_GROUP_ROOT_FILES; 1051 | val params = new JsonObject(); 1052 | params.addProperty("group_id", groupId); 1053 | 1054 | val result = actionFactory.action(channel, action, params); 1055 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1056 | }.getType()) : null; 1057 | } 1058 | 1059 | /** 1060 | * 获取群子目录文件列表 1061 | * 1062 | * @param groupId 群号 1063 | * @param folderId 文件夹ID 参考 Folder 对象 1064 | * @return {@link ActionData} of {@link GroupFilesResp} 1065 | */ 1066 | public ActionData getGroupFilesByFolder(long groupId, String folderId) { 1067 | val action = ActionType.GET_GROUP_FILES_BY_FOLDER; 1068 | val params = new JsonObject(); 1069 | params.addProperty("group_id", groupId); 1070 | params.addProperty("folder_id", folderId); 1071 | 1072 | val result = actionFactory.action(channel, action, params); 1073 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1074 | }.getType()) : null; 1075 | } 1076 | 1077 | /** 1078 | * 自定义请求 1079 | * 1080 | * @param action 请求路径 1081 | * @param params 请求参数 1082 | * @return {@link ActionData} 1083 | */ 1084 | @SuppressWarnings("rawtypes") 1085 | public ActionData customRequest(ActionPath action, JsonObject params) { 1086 | val result = actionFactory.action(channel, action, params); 1087 | return result != null ? GsonUtils.fromJson(result.toString(),ActionData.class) : null; 1088 | } 1089 | 1090 | /** 1091 | * 获取精华消息列表 1092 | * 1093 | * @param groupId 群号 1094 | * @return {@link ActionList} of {@link EssenceMsgResp} 1095 | */ 1096 | public ActionList getEssenceMsgList(long groupId) { 1097 | val action = ActionType.GET_ESSENCE_MSG_LIST; 1098 | val params = new JsonObject(); 1099 | params.addProperty("group_id", groupId); 1100 | 1101 | val result = actionFactory.action(channel, action, params); 1102 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1103 | }.getType()) : null; 1104 | } 1105 | 1106 | /** 1107 | * 设置精华消息 1108 | * 1109 | * @param msgId 消息 ID 1110 | * @return {@link ActionRaw} 1111 | */ 1112 | public ActionRaw setEssenceMsg(int msgId) { 1113 | val action = ActionType.SET_ESSENCE_MSG; 1114 | val params = new JsonObject(); 1115 | params.addProperty("message_id", msgId); 1116 | 1117 | val result = actionFactory.action(channel, action, params); 1118 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1119 | } 1120 | 1121 | /** 1122 | * 移出精华消息 1123 | * 1124 | * @param msgId 消息 ID 1125 | * @return {@link ActionRaw} 1126 | */ 1127 | public ActionRaw deleteEssenceMsg(int msgId) { 1128 | val action = ActionType.DELETE_ESSENCE_MSG; 1129 | val params = new JsonObject(); 1130 | params.addProperty("message_id", msgId); 1131 | 1132 | val result = actionFactory.action(channel, action, params); 1133 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1134 | } 1135 | 1136 | /** 1137 | * 设置机器人账号资料 1138 | * 1139 | * @param nickname 昵称 1140 | * @param company 公司 1141 | * @param email 邮箱 1142 | * @param college 学校 1143 | * @param personalNote 个性签名 1144 | * @return {@link ActionRaw} 1145 | */ 1146 | public ActionRaw setBotProfile(String nickname, String company, String email, String college, String personalNote) { 1147 | val action = ActionType.SET_QQ_PROFILE; 1148 | val params = new JsonObject(); 1149 | params.addProperty("nickname", nickname); 1150 | params.addProperty("company", company); 1151 | params.addProperty("email", email); 1152 | params.addProperty("college", college); 1153 | params.addProperty("personalNote", personalNote); 1154 | 1155 | val result = actionFactory.action(channel, action, params); 1156 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1157 | } 1158 | 1159 | 1160 | /** 1161 | * 发送合并转发 (群) 1162 | * 1163 | * @param groupId 群号 1164 | * @param msg 自定义转发消息 (可使用 BotUtils.generateForwardMsg() 方法创建) 1165 | * 参考文档 1166 | * @return {@link ActionRaw} 1167 | */ 1168 | public ActionData sendGroupForwardMsg(long groupId, List> msg) { 1169 | val action = ActionType.SEND_GROUP_FORWARD_MSG; 1170 | val params = new JsonObject(); 1171 | params.addProperty("group_id", groupId); 1172 | params.addProperty("messages", GsonUtils.getGson().toJson(msg)); 1173 | val result = actionFactory.action(channel, action, params); 1174 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1175 | }.getType()) : null; 1176 | } 1177 | 1178 | /** 1179 | * 发送合并转发 (私聊) 1180 | * 1181 | * @param userId 目标用户 1182 | * @param msg 自定义转发消息 (可使用 BotUtils.generateForwardMsg() 方法创建) 1183 | * 参考文档 1184 | * @return {@link ActionRaw} 1185 | */ 1186 | public ActionData sendPrivateForwardMsg(long userId, List> msg) { 1187 | val action = ActionType.SEND_PRIVATE_FORWARD_MSG; 1188 | val params = new JsonObject(); 1189 | params.addProperty("user_id", userId); 1190 | params.addProperty("messages", GsonUtils.getGson().toJson(msg)); 1191 | val result = actionFactory.action(channel, action, params); 1192 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1193 | }.getType()) : null; 1194 | } 1195 | 1196 | 1197 | /** 1198 | * 发送合并转发 1199 | * 1200 | * @param event 事件 1201 | * @param msg 自定义转发消息 1202 | * 参考文档 1203 | * @return {@link ActionRaw} 1204 | */ 1205 | public ActionData sendForwardMsg(WholeMessageEvent event, List> msg) { 1206 | val action = ActionType.SEND_FORWARD_MSG; 1207 | val params = new JsonObject(); 1208 | params.addProperty("messages", GsonUtils.getGson().toJson(msg)); 1209 | 1210 | switch (event.getMessageType()) { 1211 | case "private": { 1212 | params.addProperty("user_id", event.getUserId()); 1213 | break; 1214 | } 1215 | case "group": { 1216 | params.addProperty("group_id", event.getGroupId()); 1217 | break; 1218 | } 1219 | } 1220 | val result = actionFactory.action(channel, action, params); 1221 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1222 | }.getType()) : null; 1223 | } 1224 | 1225 | /** 1226 | * 获取中文分词 1227 | * 1228 | * @param content 内容 1229 | * @return {@link ActionData} of {@link WordSlicesResp} 1230 | */ 1231 | public ActionData getWordSlices(String content) { 1232 | val action = ActionType.GET_WORD_SLICES; 1233 | val params = new JsonObject(); 1234 | params.addProperty("content", content); 1235 | 1236 | val result = actionFactory.action(channel, action, params); 1237 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1238 | }.getType()) : null; 1239 | } 1240 | 1241 | /** 1242 | * 获取当前账号在线客户端列表 1243 | * 1244 | * @param noCache 是否无视缓存 1245 | * @return {@link ActionData} of {@link ClientsResp} 1246 | */ 1247 | public ActionData getOnlineClients(boolean noCache) { 1248 | val action = ActionType.GET_ONLINE_CLIENTS; 1249 | val params = new JsonObject(); 1250 | params.addProperty("no_cache", noCache); 1251 | 1252 | val result = actionFactory.action(channel, action, params); 1253 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1254 | }.getType()) : null; 1255 | } 1256 | 1257 | /** 1258 | * 图片 OCR 1259 | * 1260 | * @param image 图片ID 1261 | * @return {@link ActionData} of {@link OcrResp} 1262 | */ 1263 | public ActionData ocrImage(String image) { 1264 | val action = ActionType.OCR_IMAGE; 1265 | val params = new JsonObject(); 1266 | params.addProperty("image", image); 1267 | 1268 | val result = actionFactory.action(channel, action, params); 1269 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1270 | }.getType()) : null; 1271 | } 1272 | 1273 | /** 1274 | * 私聊发送文件 1275 | * 1276 | * @param userId 目标用户 1277 | * @param file 本地文件路径 1278 | * @param name 文件名 1279 | * @return {@link ActionRaw} 1280 | */ 1281 | public ActionRaw uploadPrivateFile(long userId, String file, String name) { 1282 | val action = ActionType.UPLOAD_PRIVATE_FILE; 1283 | val params = new JsonObject(); 1284 | params.addProperty("user_id", userId); 1285 | params.addProperty("file", file); 1286 | params.addProperty("name", name); 1287 | 1288 | val result = actionFactory.action(channel, action, params); 1289 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1290 | } 1291 | 1292 | /** 1293 | * 群打卡 1294 | * 1295 | * @param groupId 群号 1296 | * @return {@link ActionRaw} 1297 | */ 1298 | public ActionRaw sendGroupSign(long groupId) { 1299 | val action = ActionType.SEND_GROUP_SIGN; 1300 | val params = new JsonObject(); 1301 | params.addProperty("group_id", groupId); 1302 | 1303 | val result = actionFactory.action(channel, action, params); 1304 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1305 | } 1306 | 1307 | /** 1308 | * 删除单向好友 1309 | * 1310 | * @param userId QQ号 1311 | * @return {@link ActionRaw} 1312 | */ 1313 | public ActionRaw deleteUnidirectionalFriend(long userId) { 1314 | val action = ActionType.DELETE_UNIDIRECTIONAL_FRIEND; 1315 | val params = new JsonObject(); 1316 | params.addProperty("user_id", userId); 1317 | 1318 | val result = actionFactory.action(channel, action, params); 1319 | return result != null ? GsonUtils.fromJson(result.toString(),ActionRaw.class) : null; 1320 | } 1321 | 1322 | /** 1323 | * 获取单向好友列表 1324 | * 1325 | * @return {@link ActionList} of {@link UnidirectionalFriendListResp} 1326 | */ 1327 | public ActionList getUnidirectionalFriendList() { 1328 | val action = ActionType.GET_UNIDIRECTIONAL_FRIEND_LIST; 1329 | val result = actionFactory.action(channel, action, null); 1330 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1331 | }.getType()) : null; 1332 | } 1333 | 1334 | /** 1335 | * 获取群文件资源链接 1336 | * 1337 | * @param groupId 群号 1338 | * @param fileId 文件ID 1339 | * @param busId 文件类型 1340 | * @return result {@link ActionData} of {@link UrlResp} 1341 | */ 1342 | @Override 1343 | public ActionData getGroupFileUrl(long groupId, String fileId, int busId) { 1344 | val action = ActionType.GET_GROUP_FILE_URL; 1345 | val params = new JsonObject(); 1346 | params.addProperty("group_id", groupId); 1347 | params.addProperty("file_id", fileId); 1348 | params.addProperty("busid", busId); 1349 | val result = actionFactory.action(channel, action, null); 1350 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1351 | }.getType()) : null; 1352 | } 1353 | 1354 | /** 1355 | * 获取群文件资源链接 1356 | * 1357 | * @param groupId 群号 1358 | * @param fileId 文件ID 1359 | * @param busId 文件类型 1360 | * @return result {@link ActionData} of {@link UrlResp} 1361 | */ 1362 | @Override 1363 | public ActionData getFile(long groupId, String fileId, int busId) { 1364 | val action = ActionType.GET_GROUP_FILE_URL; 1365 | val params = new JsonObject(); 1366 | params.addProperty("group_id", groupId); 1367 | params.addProperty("file_id", fileId); 1368 | params.addProperty("busid", busId); 1369 | val result = actionFactory.action(channel, action, null); 1370 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1371 | }.getType()) : null; 1372 | } 1373 | 1374 | /** 1375 | * 创建群文件文件夹 1376 | * 1377 | * @param groupId 群号 1378 | * @param folderName 文件夹名 1379 | * @return result {@link ActionRaw} 1380 | */ 1381 | @Override 1382 | public ActionRaw createGroupFileFolder(long groupId, String folderName) { 1383 | val action = ActionType.CREATE_GROUP_FILE_FOLDER; 1384 | val params = new JsonObject(); 1385 | params.addProperty("group_id", groupId); 1386 | params.addProperty("name", folderName); 1387 | // 仅能在根目录创建文件夹 1388 | params.addProperty("parent_id", "/"); 1389 | val result = actionFactory.action(channel, action, params); 1390 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 1391 | } 1392 | 1393 | /** 1394 | * 删除群文件文件夹 1395 | * 1396 | * @param groupId 群号 1397 | * @param folderId 文件夹ID 1398 | * @return result {@link ActionRaw} 1399 | */ 1400 | @Override 1401 | public ActionRaw deleteGroupFileFolder(long groupId, String folderId) { 1402 | val action = ActionType.DELETE_GROUP_FOLDER; 1403 | val params = new JsonObject(); 1404 | params.addProperty("group_id", groupId); 1405 | params.addProperty("folder_id", folderId); 1406 | val result = actionFactory.action(channel, action, params); 1407 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 1408 | } 1409 | 1410 | /** 1411 | * 删除群文件 1412 | * 1413 | * @param groupId 群号 1414 | * @param fileId 文件ID 1415 | * @param busId 文件类型 1416 | * @return result {@link ActionRaw} 1417 | */ 1418 | @Override 1419 | public ActionRaw deleteGroupFile(long groupId, String fileId, int busId) { 1420 | val action = ActionType.DELETE_GROUP_FILE; 1421 | val params = new JsonObject(); 1422 | params.addProperty("group_id", groupId); 1423 | params.addProperty("file_id", fileId); 1424 | params.addProperty("busid", busId); 1425 | val result = actionFactory.action(channel, action, params); 1426 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 1427 | } 1428 | 1429 | /** 1430 | * 好友点赞 1431 | * 1432 | * @param userId 目标用户 1433 | * @param times 点赞次数(每个好友每天最多 10 次,机器人为 Super VIP 则提高到 20次) 1434 | * @return result {@link ActionRaw} 1435 | */ 1436 | @Override 1437 | public ActionRaw sendLike(long userId, int times) { 1438 | val action = ActionType.SEND_LIKE; 1439 | val params = new JsonObject(); 1440 | params.addProperty("user_id", userId); 1441 | params.addProperty("times", times); 1442 | val result = actionFactory.action(channel, action, null); 1443 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 1444 | } 1445 | 1446 | @Override 1447 | public GetStatusResp getStatus() { 1448 | val action = ActionType.GET_STATUS; 1449 | val result = actionFactory.action(channel, action, null); 1450 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1451 | }.getType()) : null; 1452 | } 1453 | 1454 | /** 1455 | * 获取状态 1456 | * 1457 | * @return result {@link GetStatusResp} 1458 | */ 1459 | @Override 1460 | public ActionData getVersionInfo() { 1461 | val action = ActionType.GET_VERSION_INFO; 1462 | val result = actionFactory.action(channel, action, null); 1463 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1464 | }.getType()) : null; 1465 | } 1466 | 1467 | /** 1468 | * 获取收藏表情 1469 | * 1470 | * @return 表情的下载 URL 1471 | */ 1472 | @Override 1473 | public ActionList fetchCustomFace() { 1474 | val action = ActionType.FETCH_CUSTOM_FACE; 1475 | val result = actionFactory.action(channel, action, null); 1476 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1477 | }.getType()) : null; 1478 | } 1479 | 1480 | /** 1481 | * 获取合并转发消息Id 1482 | * 1483 | * @param msg 自定义转发消息 (可使用 BotUtils.generateForwardMsg() 方法创建) 1484 | * @return result {@link ActionData} of {@link String} 合并转发的消息Id 1485 | */ 1486 | @Override 1487 | public ActionData sendForwardMsg(List> msg) { 1488 | val action = ActionType.SEND_FORWARD_MSG; 1489 | val params = new JsonObject(); 1490 | /** 1491 | * 将msg转成string存到params中 1492 | */ 1493 | //params.addProperty("messages", msg); 1494 | val result = actionFactory.action(channel, action, null); 1495 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1496 | }.getType()) : null; 1497 | } 1498 | 1499 | /** 1500 | * 设置群消息表情回应 1501 | * 1502 | * @param groupId 群号 1503 | * @param msgId 消息 ID 1504 | * @param code 表情 ID 1505 | * @param isAdd 添加/取消 回应 1506 | * @return result {@link ActionRaw} 1507 | */ 1508 | @Override 1509 | public ActionRaw setGroupReaction(long groupId, int msgId, String code, boolean isAdd) { 1510 | val action = ActionType.SET_GROUP_REACTION; 1511 | val params = new JsonObject(); 1512 | params.addProperty("group_id", groupId); 1513 | params.addProperty("message_id", msgId); 1514 | params.addProperty("code", code); 1515 | params.addProperty("is_add", isAdd); 1516 | val result = actionFactory.action(channel, action, null); 1517 | return result != null ? GsonUtils.fromJson(result.toString(), ActionRaw.class) : null; 1518 | } 1519 | 1520 | 1521 | /** 1522 | * 自定义请求 1523 | * 1524 | * @param action 请求路径 1525 | * @param params 请求参数 1526 | * @return result {@link ActionData} 1527 | */ 1528 | @SuppressWarnings("rawtypes") 1529 | public ActionData customRequest(ActionPath action, Map params) { 1530 | val result = actionFactory.action(channel, action, GsonUtils.parse(GsonUtils.getGson().toJson(params))); 1531 | return result != null ? GsonUtils.fromJson(result.toString(), ActionData.class) : null; 1532 | } 1533 | 1534 | /** 1535 | * 自定义请求 1536 | * 1537 | * @param action 请求路径 1538 | * @param params 请求参数 1539 | * @return result {@link ActionData} 1540 | */ 1541 | public ActionData customRequest(ActionPath action, Map params, Class clazz) { 1542 | val result = actionFactory.action(channel, action, GsonUtils.parse(GsonUtils.getGson().toJson(params, clazz))); 1543 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1544 | }.getType()) : null; 1545 | } 1546 | 1547 | /** 1548 | * 自定义请求 1549 | * 1550 | * @param action 请求路径 1551 | * @param params 请求参数 1552 | * @return result {@link ActionData} 1553 | */ 1554 | @SuppressWarnings("rawtypes") 1555 | public ActionData customRawRequest(ActionPath action, Map params) { 1556 | val result = actionFactory.action(channel, action, GsonUtils.parse(GsonUtils.getGson().toJson(params))); 1557 | return result != null ? GsonUtils.fromJson(result.toString(), ActionData.class) : null; 1558 | } 1559 | 1560 | /** 1561 | * 自定义请求 1562 | * 1563 | * @param action 请求路径 1564 | * @param params 请求参数 1565 | * @return result {@link ActionData} 1566 | */ 1567 | public ActionData customRawRequest(ActionPath action, Map params, Class clazz) { 1568 | val result = actionFactory.action(channel, action, GsonUtils.parse(GsonUtils.getGson().toJson(params, clazz))); 1569 | return result != null ? GsonUtils.fromJson(result.toString(), new TypeToken>() { 1570 | }.getType()) : null; 1571 | } 1572 | 1573 | 1574 | } 1575 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/core/BotConfig.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.core; 2 | 3 | import com.google.gson.annotations.Expose; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | /** 9 | * @Project: onebot-client 10 | * @Author: cnlimiter 11 | * @CreateTime: 2022/10/1 17:05 12 | * @Description: 13 | */ 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | public class BotConfig { 18 | @Expose 19 | private String url = "ws://127.0.0.1:8080";//websocket地址 20 | @Expose 21 | private String token = "";//token鉴权 22 | @Expose 23 | private long botId = 0; 24 | @Expose 25 | private boolean mirai = false;//是否开启mirai,否则请使用onebot-mirai 26 | @Expose 27 | private boolean reconnect = true;//是否开启重连 28 | @Expose 29 | private int reconnectInterval = 5;//重连间隔 30 | @Expose 31 | private int reconnectMaxTimes = 3;//重连次数 32 | public BotConfig(String url, String token){ 33 | this(url, token, 0, false, true, 5, 3); 34 | } 35 | 36 | public BotConfig(String url){ 37 | this(url, "", 0, false, true, 5, 3); 38 | } 39 | 40 | public BotConfig(String url, long botId){ 41 | this(url, "", botId, false, true, 5, 3); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/action/ActionFactory.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.action; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import cn.evole.onebot.sdk.action.misc.ActionPath; 5 | import cn.evole.onebot.sdk.util.GsonUtils; 6 | import com.google.gson.JsonObject; 7 | import lombok.val; 8 | import org.java_websocket.WebSocket; 9 | 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | 14 | /** 15 | * @Project: onebot-client 16 | * @Author: cnlimiter 17 | * @CreateTime: 2022/9/14 15:05 18 | * @Description: 19 | */ 20 | 21 | public class ActionFactory { 22 | private final OneBotClient client; 23 | /** 24 | * 请求回调数据 25 | */ 26 | private final Map apiCallbackMap = new HashMap<>(); 27 | /** 28 | * 用于标识请求,可以是任何类型的数据,OneBot 将会在调用结果中原样返回 29 | */ 30 | private int echo = 0; 31 | 32 | public ActionFactory(OneBotClient client){ 33 | this.client = client; 34 | } 35 | 36 | /** 37 | * 处理响应结果 38 | * 39 | * @param respJson 回调结果 40 | */ 41 | public void onReceiveActionResp(JsonObject respJson) { 42 | String echo = GsonUtils.getAsString(respJson, "echo"); 43 | ActionSendUnit actionSendUnit = apiCallbackMap.get(echo); 44 | if (actionSendUnit != null) { 45 | // 唤醒挂起的线程 46 | actionSendUnit.onCallback(respJson); 47 | apiCallbackMap.remove(echo); 48 | } 49 | } 50 | 51 | /** 52 | * @param ws Session 53 | * @param action 请求路径 54 | * @param params 请求参数 55 | * @return 请求结果 56 | */ 57 | public JsonObject action(WebSocket ws, ActionPath action, JsonObject params) { 58 | if (!ws.isOpen()) { 59 | return null; 60 | } 61 | val reqJson = generateReqJson(action, params); 62 | ActionSendUnit actionSendUnit = new ActionSendUnit(client, ws); 63 | apiCallbackMap.put(reqJson.get("echo").getAsString(), actionSendUnit); 64 | JsonObject result = new JsonObject(); 65 | try { 66 | result = actionSendUnit.send(reqJson); 67 | } catch (Exception e) { 68 | client.getLogger().warn("Request failed: {}", e.getMessage()); 69 | result.addProperty("status", "failed"); 70 | result.addProperty("retcode", -1); 71 | } 72 | return result; 73 | } 74 | 75 | /** 76 | * 构建请求数据 77 | * {"action":"send_private_msg","params":{"user_id":10001000,"message":"你好"},"echo":"123"} 78 | * 79 | * @param action 请求路径 80 | * @param params 请求参数 81 | * @return 请求数据结构 82 | */ 83 | private JsonObject generateReqJson(ActionPath action, JsonObject params) { 84 | val json = new JsonObject(); 85 | json.addProperty("action", action.getPath()); 86 | json.add("params", params); 87 | json.addProperty("echo", echo++); 88 | return json; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/action/ActionSendUnit.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.action; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import com.google.gson.JsonObject; 5 | import org.java_websocket.WebSocket; 6 | 7 | /** 8 | * @Project: onebot-client 9 | * @Author: cnlimiter 10 | * @CreateTime: 2022/9/14 15:06 11 | * @Description: 12 | */ 13 | public class ActionSendUnit { 14 | private final OneBotClient client; 15 | private final WebSocket channel; 16 | private final long requestTimeout; 17 | protected final Object lck = new Object(); 18 | private JsonObject resp; 19 | 20 | 21 | public ActionSendUnit(OneBotClient client, WebSocket channel) { 22 | this(client, channel, 3000L); 23 | } 24 | 25 | /** 26 | * @param channel {@link WebSocket} 27 | * @param requestTimeout Request Timeout 28 | */ 29 | public ActionSendUnit(OneBotClient client, WebSocket channel, long requestTimeout) { 30 | this.client = client; 31 | this.channel = channel; 32 | this.requestTimeout = requestTimeout; 33 | } 34 | 35 | /** 36 | * @param req Request json data 37 | * @return Response json data 38 | * @throws InterruptedException exception 39 | */ 40 | public JsonObject send(JsonObject req) throws InterruptedException { 41 | synchronized (channel) { 42 | client.getLogger().debug("[Action] {}", req.toString()); 43 | channel.send(req.toString()); 44 | } 45 | synchronized (this) { 46 | this.wait(requestTimeout); 47 | } 48 | return resp; 49 | } 50 | 51 | /** 52 | * @param resp Response json data 53 | */ 54 | public void onCallback(JsonObject resp) { 55 | this.resp = resp; 56 | synchronized (lck) { 57 | lck.notify(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/event/EventExecutorFactoryImpl.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.event; 2 | 3 | import cn.evole.onebot.client.interfaces.Listener; 4 | import cn.evole.onebot.sdk.event.Event; 5 | import net.kyori.event.method.EventExecutor; 6 | import org.checkerframework.checker.nullness.qual.NonNull; 7 | 8 | import java.lang.invoke.MethodHandle; 9 | import java.lang.invoke.MethodHandles; 10 | import java.lang.reflect.Method; 11 | import java.lang.reflect.Modifier; 12 | 13 | /** 14 | * @Project: onebot-client 15 | * @Author: cnlimiter 16 | * @CreateTime: 2024/1/26 23:08 17 | * @Description: 18 | */ 19 | 20 | public class EventExecutorFactoryImpl implements EventExecutor.Factory { 21 | public static final EventExecutorFactoryImpl INSTANCE = new EventExecutorFactoryImpl(); 22 | 23 | private EventExecutorFactoryImpl() { 24 | } 25 | 26 | @Override 27 | public @NonNull EventExecutor create(@NonNull Object object, @NonNull Method method) throws Exception { 28 | method.setAccessible(true); 29 | final Class actualEventType = method.getParameterTypes()[0].asSubclass(Event.class); 30 | if (Modifier.isAbstract(actualEventType.getModifiers())) { 31 | throw new IllegalArgumentException("▌ 不能为抽象事件类型创建侦听器"); 32 | } 33 | final MethodHandle handle = MethodHandles.lookup().unreflect(method).bindTo(object); 34 | return (listener, event) -> { 35 | if (!actualEventType.isInstance(event)) 36 | return; 37 | handle.invoke(event); 38 | }; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/event/EventFactory.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.event; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import cn.evole.onebot.client.utils.TransUtils; 5 | import cn.evole.onebot.sdk.event.Event; 6 | import cn.evole.onebot.sdk.event.EventMap; 7 | import cn.evole.onebot.sdk.event.message.GroupMessageEvent; 8 | import cn.evole.onebot.sdk.event.message.GuildMessageEvent; 9 | import cn.evole.onebot.sdk.event.message.PrivateMessageEvent; 10 | import cn.evole.onebot.sdk.event.message.WholeMessageEvent; 11 | import cn.evole.onebot.sdk.util.GsonUtils; 12 | import com.google.gson.JsonObject; 13 | import lombok.val; 14 | 15 | /** 16 | * @Project: onebot-client 17 | * @Author: cnlimiter 18 | * @CreateTime: 2024/1/26 23:32 19 | * @Description: 20 | */ 21 | 22 | public class EventFactory { 23 | protected final OneBotClient client; 24 | protected final EventsBusImpl eventManager; 25 | 26 | public EventFactory(OneBotClient client) { 27 | this.client = client; 28 | this.eventManager = ((EventsBusImpl) client.getEventsBus()); 29 | } 30 | 31 | 32 | public Event createEvent(JsonObject json) { 33 | final Class eventType = parseEventType(json); 34 | if (eventType == null) { 35 | return null; // 未知的消息类型 36 | } 37 | if (!eventManager.isSubscribed(eventType)) { 38 | // 如果不是消息事件,请确保命令系统可以接收事件。 39 | if (eventType != GroupMessageEvent.class 40 | && eventType != PrivateMessageEvent.class 41 | && eventType != WholeMessageEvent.class 42 | && eventType != GuildMessageEvent.class 43 | ) { 44 | client.getLogger().warn("▌ 命令系统尚未支持"); 45 | return null; 46 | } 47 | } 48 | 49 | return GsonUtils.fromJson(json.toString(), eventType); 50 | } 51 | 52 | protected Class parseEventType(JsonObject rawJson) { 53 | String type; 54 | if (!rawJson.has("post_type")) return null; 55 | String postType = GsonUtils.getAsString(rawJson, "post_type"); 56 | switch (postType){ 57 | case "message": { 58 | //消息类型 59 | val json = TransUtils.toArray(rawJson); 60 | switch (GsonUtils.getAsString(json, "message_type")){ 61 | case "group": { 62 | //群聊消息类型 63 | type = "groupMessage"; 64 | break; 65 | } 66 | case "private": { 67 | //私聊消息类型 68 | type = "privateMessage"; 69 | break; 70 | } 71 | case "guild": { 72 | //频道消息,暂不支持私信 73 | type = "guildMessage"; 74 | break; 75 | } 76 | default: { 77 | type = "wholeMessage"; 78 | break; 79 | } 80 | } 81 | break; 82 | } 83 | case "request": { 84 | //请求类型 85 | type = GsonUtils.getAsString(rawJson, "request_type"); 86 | break; 87 | } 88 | case "notice": { 89 | //通知类型 90 | type = GsonUtils.getAsString(rawJson,"notice_type"); 91 | break; 92 | } 93 | case "meta_event": { 94 | //周期类型 95 | type = GsonUtils.getAsString(rawJson,"meta_event_type"); 96 | break; 97 | } 98 | default: { 99 | type = ""; 100 | break; 101 | } 102 | } 103 | if (type.isEmpty()) { 104 | client.getLogger().warn("▌ 未知消息类型"); 105 | return null; 106 | } 107 | return EventMap.messageMap.get(type); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/event/EventsBusImpl.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.event; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import cn.evole.onebot.client.interfaces.EventsBus; 5 | import cn.evole.onebot.client.interfaces.Listener; 6 | import cn.evole.onebot.sdk.event.Event; 7 | import lombok.Getter; 8 | import net.kyori.event.PostResult; 9 | import net.kyori.event.SimpleEventBus; 10 | import net.kyori.event.method.MethodSubscriptionAdapter; 11 | import net.kyori.event.method.SimpleMethodSubscriptionAdapter; 12 | 13 | import java.util.List; 14 | import java.util.concurrent.CopyOnWriteArrayList; 15 | 16 | /** 17 | * @Project: onebot-client 18 | * @Author: cnlimiter 19 | * @CreateTime: 2024/1/26 22:57 20 | * @Description: 21 | */ 22 | 23 | public class EventsBusImpl implements EventsBus { 24 | private final OneBotClient client; 25 | private final net.kyori.event.EventBus bus; 26 | private final MethodSubscriptionAdapter msa; 27 | @Getter private final List listeners = new CopyOnWriteArrayList<>(); 28 | 29 | public EventsBusImpl(OneBotClient client) { 30 | this.client = client; 31 | this.bus = new SimpleEventBus<>(Event.class); 32 | this.msa = new SimpleMethodSubscriptionAdapter<>(bus, EventExecutorFactoryImpl.INSTANCE, MethodScannerImpl.INSTANCE); 33 | } 34 | 35 | @Override 36 | public void callEvent(Event event) { 37 | final PostResult result = bus.post(event); 38 | if (!result.wasSuccessful()) { 39 | client.getLogger().error("▌ 发布事件时出现意外异常"); 40 | for (final Throwable t : result.exceptions().values()) { 41 | client.getLogger().warn(t.getMessage()); 42 | } 43 | } 44 | } 45 | 46 | @Override 47 | public void register(Listener listener) { 48 | try { 49 | msa.register(listener); 50 | } catch (SimpleMethodSubscriptionAdapter.SubscriberGenerationException e) { 51 | msa.unregister(listener); // 取消订阅 52 | throw e; // 抛出错误 53 | } 54 | listeners.add(listener); 55 | } 56 | 57 | @Override 58 | public void unregister(Listener listener) { 59 | msa.unregister(listener); 60 | listeners.remove(listener); 61 | } 62 | 63 | public boolean isSubscribed(Class type) { 64 | return bus.hasSubscribers(type);//是否被EventHandler注解 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/event/MethodScannerImpl.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.event; 2 | 3 | import cn.evole.onebot.client.annotations.SubscribeEvent; 4 | import cn.evole.onebot.client.interfaces.Listener; 5 | import net.kyori.event.PostOrders; 6 | import net.kyori.event.method.MethodScanner; 7 | import org.checkerframework.checker.nullness.qual.NonNull; 8 | 9 | import java.lang.reflect.Method; 10 | import java.lang.reflect.Modifier; 11 | 12 | /** 13 | * @Project: onebot-client 14 | * @Author: cnlimiter 15 | * @CreateTime: 2024/1/26 23:10 16 | * @Description: 17 | */ 18 | 19 | public final class MethodScannerImpl implements MethodScanner { 20 | public static final MethodScannerImpl INSTANCE = new MethodScannerImpl(); 21 | 22 | private MethodScannerImpl() { 23 | } 24 | 25 | @Override 26 | public boolean shouldRegister(@NonNull Listener listener, @NonNull Method method) { 27 | return Modifier.isPublic(method.getModifiers()) && method.isAnnotationPresent(SubscribeEvent.class); 28 | } 29 | 30 | @Override 31 | public int postOrder(@NonNull Listener listener, @NonNull Method method) { 32 | return method.getAnnotation(SubscribeEvent.class).internal() ? PostOrders.EARLY : PostOrders.NORMAL; 33 | } 34 | 35 | @Override 36 | public boolean consumeCancelledEvents(@NonNull Listener listener, @NonNull Method method) { 37 | return false; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/instances/event/MsgHandlerImpl.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.instances.event; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import cn.evole.onebot.client.interfaces.MsgHandler; 5 | import cn.evole.onebot.client.utils.TransUtils; 6 | import cn.evole.onebot.sdk.event.Event; 7 | import cn.evole.onebot.sdk.event.message.GroupMessageEvent; 8 | import cn.evole.onebot.sdk.event.message.GuildMessageEvent; 9 | import cn.evole.onebot.sdk.event.message.PrivateMessageEvent; 10 | import cn.evole.onebot.sdk.util.GsonUtils; 11 | import com.google.gson.JsonObject; 12 | import com.google.gson.JsonSyntaxException; 13 | import lombok.val; 14 | 15 | /** 16 | * @Project: onebot-client 17 | * @Author: cnlimiter 18 | * @CreateTime: 2024/1/27 0:04 19 | * @Description: 20 | */ 21 | 22 | public class MsgHandlerImpl implements MsgHandler { 23 | private final static String API_RESULT_KEY = "echo"; 24 | 25 | private static final String RESULT_STATUS_KEY = "status"; 26 | private static final String RESULT_STATUS_FAILED = "failed"; 27 | 28 | public static final String META_EVENT = "meta_event_type"; 29 | private static final String META_HEART_BEAT = "heartbeat"; 30 | private static final String META_LIFE_CYCLE = "lifecycle"; 31 | 32 | protected final OneBotClient client; 33 | protected final Object lck = new Object(); 34 | 35 | public MsgHandlerImpl(OneBotClient client) { 36 | this.client = client; 37 | } 38 | 39 | @Override 40 | public void handle(String msg) { 41 | if (msg == null) { 42 | client.getLogger().warn("▌ §c消息体为空"); 43 | return; 44 | } 45 | try { 46 | val json2 = TransUtils.toArray(GsonUtils.parse(msg)); 47 | client.getLogger().debug(json2.toString()); 48 | client.getEventExecutor().execute(() -> { 49 | synchronized (lck) { 50 | event(json2); 51 | } 52 | }); 53 | 54 | } catch ( 55 | JsonSyntaxException e) { 56 | client.getLogger().error("▌ §cJson语法错误:{}", msg); 57 | } 58 | 59 | } 60 | 61 | /** 62 | * 处理接收到的JSON对象形式的事件 63 | * 此方法首先尝试根据JSON对象执行一个动作,然后根据JSON对象创建一个事件对象 64 | * 如果创建的事件对象不为空,则根据条件判断是否执行命令,或将其发布到事件总线 65 | * 66 | * @param json 包含事件信息的JSON对象 67 | */ 68 | protected void event(JsonObject json) { 69 | // 执行与JSON对象关联的动作 70 | executeAction(json); 71 | 72 | // 根据JSON对象创建Event实例 73 | Event event = client.getEventFactory().createEvent(json); 74 | 75 | // 如果创建的事件为空,则直接返回,不再进行后续处理 76 | if (event == null) { 77 | return; 78 | } 79 | 80 | // 尝试执行命令,如果执行失败,则将事件发布到事件总线上 81 | if (!executeCommand(event)) { 82 | client.getEventsBus().callEvent(event); 83 | } 84 | } 85 | 86 | 87 | 88 | /** 89 | * 执行一个JSON对象所代表的动作 90 | * 此方法主要用于处理和执行通过JSON对象描述的动作,根据JSON中的内容决定如何处理 91 | * 92 | * @param json 包含动作信息的JSON对象 93 | */ 94 | protected void executeAction(JsonObject json) { 95 | // 检查JSON对象中是否包含API结果键 96 | if (json.has(API_RESULT_KEY)) { 97 | // 判断动作执行结果是否为失败 98 | if (RESULT_STATUS_FAILED.equals(GsonUtils.getAsString(json, RESULT_STATUS_KEY))) { 99 | // 如果执行失败,记录警告日志 100 | client.getLogger().warn("▌ §c请求失败: {}", GsonUtils.getAsString(json, "wording")); 101 | } else { 102 | // 如果执行成功,调用动作工厂的回调方法处理接收到的动作响应 103 | client.getActionFactory().onReceiveActionResp(json);//请求执行 104 | } 105 | } 106 | } 107 | 108 | //todo 命令系统 109 | protected boolean executeCommand(Event event) { 110 | if (!( 111 | event instanceof GroupMessageEvent 112 | || event instanceof PrivateMessageEvent 113 | || event instanceof GuildMessageEvent 114 | )) 115 | return false; 116 | 117 | return false; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/interfaces/EventsBus.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.interfaces; 2 | 3 | 4 | import cn.evole.onebot.sdk.event.Event; 5 | 6 | /** 7 | * @Project: onebot-client 8 | * @Author: cnlimiter 9 | * @CreateTime: 2024/1/26 22:32 10 | * @Description: 11 | */ 12 | 13 | public interface EventsBus { 14 | void callEvent(Event event); 15 | 16 | void register(Listener listener); 17 | 18 | void unregister(Listener listener); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/interfaces/Listener.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.interfaces; 2 | 3 | /** 4 | * @Project: onebot-client 5 | * @Author: cnlimiter 6 | * @CreateTime: 2024/1/26 22:56 7 | * @Description: 8 | */ 9 | 10 | public interface Listener { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/interfaces/MsgHandler.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.interfaces; 2 | 3 | /** 4 | * @Project: onebot-client 5 | * @Author: cnlimiter 6 | * @CreateTime: 2024/1/27 0:06 7 | * @Description: 8 | */ 9 | 10 | public interface MsgHandler { 11 | void handle(String msg); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/internal/TestHandler.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.internal; 2 | 3 | import cn.evole.onebot.client.OneBotClient; 4 | import cn.evole.onebot.client.annotations.SubscribeEvent; 5 | import cn.evole.onebot.client.interfaces.Listener; 6 | import cn.evole.onebot.sdk.event.message.GroupMessageEvent; 7 | 8 | /** 9 | * @Project: onebot-client 10 | * @Author: cnlimiter 11 | * @CreateTime: 2024/2/20 9:57 12 | * @Description: 13 | */ 14 | 15 | public class TestHandler implements Listener { 16 | OneBotClient client; 17 | public TestHandler(OneBotClient client){ 18 | this.client = client; 19 | } 20 | 21 | @SubscribeEvent(internal = true) 22 | public void msg1(GroupMessageEvent event){ 23 | client.getLogger().info(event); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/utils/ConnectionUtils.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.utils; 2 | 3 | import org.java_websocket.WebSocket; 4 | import org.java_websocket.handshake.ClientHandshake; 5 | 6 | /** 7 | * @Project: onebot-client 8 | * @Author: cnlimiter 9 | * @CreateTime: 2024/8/8 下午7:44 10 | * @Description: 11 | */ 12 | public class ConnectionUtils { 13 | 14 | /** 15 | * 获取连接的 QQ 号 16 | * 17 | * @param session {@link WebSocket} 18 | * @return QQ 号 19 | */ 20 | public static long parseSelfId(ClientHandshake session) { 21 | String selfIdStr = session.getFieldValue("x-self-id"); 22 | try { 23 | return Long.parseLong(selfIdStr); 24 | } catch (NumberFormatException e) { 25 | return 0L; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/utils/IOUtils.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.utils; 2 | 3 | import java.io.*; 4 | import java.nio.file.Files; 5 | 6 | /** 7 | * @Project: CmdKey 8 | * @Author: cnlimiter 9 | * @CreateTime: 2025/3/16 01:47 10 | * @Description: 11 | */ 12 | public class IOUtils { 13 | public static void writeFile(String data, File file){ 14 | OutputStream out = null; 15 | try { 16 | out = Files.newOutputStream(file.toPath()); 17 | out.write(data.getBytes()); 18 | out.flush(); 19 | } catch (IOException e) {} 20 | finally { 21 | close(out); 22 | } 23 | } 24 | 25 | public static String readFile(File file){ 26 | InputStream in = null; 27 | ByteArrayOutputStream out = null; 28 | try { 29 | in = Files.newInputStream(file.toPath()); 30 | out = new ByteArrayOutputStream(); 31 | byte[] buf = new byte[1024]; 32 | int len = -1; 33 | while ((len = in.read(buf)) != -1) { 34 | out.write(buf, 0, len); 35 | } 36 | out.flush(); 37 | return out.toString(); 38 | } catch (IOException e) { 39 | return ""; 40 | } 41 | finally { 42 | close(in); 43 | close(out); 44 | } 45 | } 46 | 47 | public static void close(Closeable c) { 48 | if (c != null) { 49 | try { 50 | c.close(); 51 | } catch (IOException e) { 52 | // nothing 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/utils/ReflectionUtils.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.utils; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.URL; 6 | import java.util.ArrayList; 7 | import java.util.Enumeration; 8 | import java.util.List; 9 | 10 | /** 11 | * @Project: onebot-client 12 | * @Author: cnlimiter 13 | * @CreateTime: 2025/2/11 19:25 14 | * @Description: 15 | */ 16 | public class ReflectionUtils { 17 | public static List> getClasses(String packageName) { 18 | ArrayList> classes = new ArrayList<>(); 19 | try { 20 | ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 21 | String path = packageName.replace('.', '/'); 22 | Enumeration resources = classLoader.getResources(path); 23 | List dirs = new ArrayList<>(); 24 | while (resources.hasMoreElements()) { 25 | URL resource = resources.nextElement(); 26 | dirs.add(new File(resource.getFile())); 27 | } 28 | for (File directory : dirs) { 29 | classes.addAll(findClasses(directory, packageName)); 30 | } 31 | } catch (IOException ignored){ 32 | 33 | } 34 | 35 | return classes; 36 | } 37 | 38 | private static List> findClasses(File directory, String packageName){ 39 | List> classes = new ArrayList<>(); 40 | if (!directory.exists()) { 41 | return classes; 42 | } 43 | File[] files = directory.listFiles(); 44 | if (files != null) { 45 | for (File file : files) { 46 | if (file.isDirectory()) { 47 | assert !file.getName().contains("."); 48 | classes.addAll(findClasses(file, packageName + "." + file.getName())); 49 | } else if (file.getName().endsWith(".class")) { 50 | try { 51 | classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); 52 | } catch (ClassNotFoundException e) { 53 | System.out.print(e.getMessage()); 54 | } 55 | } 56 | } 57 | } 58 | return classes; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cn/evole/onebot/client/utils/TransUtils.java: -------------------------------------------------------------------------------- 1 | package cn.evole.onebot.client.utils; 2 | 3 | import cn.evole.onebot.sdk.util.GsonUtils; 4 | import com.google.gson.JsonObject; 5 | 6 | import static cn.evole.onebot.client.instances.event.MsgHandlerImpl.META_EVENT; 7 | 8 | /** 9 | * Name: onebot-client / TransUtils 10 | * Author: cnlimiter 11 | * CreateTime: 2023/11/22 11:24 12 | * Description: 13 | */ 14 | 15 | public class TransUtils { 16 | 17 | public static JsonObject toArray(JsonObject json){ 18 | if (json.has(META_EVENT)) return json; 19 | if (json.has("message") && GsonUtils.isArrayNode(json, "message")){ 20 | json.addProperty("message", GsonUtils.getAsJsonArray(json, "message").toString()); 21 | } 22 | return json; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/ApiTest.java: -------------------------------------------------------------------------------- 1 | import cn.evole.onebot.client.OneBotClient; 2 | import cn.evole.onebot.client.core.BotConfig; 3 | import cn.evole.onebot.sdk.action.misc.ActionData; 4 | import cn.evole.onebot.sdk.entity.MsgId; 5 | import cn.evole.onebot.sdk.util.MsgUtils; 6 | 7 | /** 8 | * @Project: onebot-client 9 | * @Author: cnlimiter 10 | * @CreateTime: 2024/1/27 1:45 11 | * @Description: 12 | */ 13 | 14 | public class ApiTest { 15 | 16 | 17 | 18 | public static void main(String[] args) throws InterruptedException { 19 | BotConfig config = new BotConfig("ws://192.168.1.25:5800", "123456"); 20 | OneBotClient client = OneBotClient.create(config).open(); 21 | 22 | Thread.sleep(1000); 23 | 24 | ActionData back = client.getBot().sendGroupMsg(337631140L, MsgUtils.builder().text("123").build(), true);//发送群消息 25 | 26 | System.out.println(back.toString()); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/HandlerTest.java: -------------------------------------------------------------------------------- 1 | import cn.evole.onebot.client.OneBotClient; 2 | import cn.evole.onebot.client.annotations.EventBus; 3 | import cn.evole.onebot.client.annotations.SubscribeEvent; 4 | import cn.evole.onebot.client.core.BotConfig; 5 | import cn.evole.onebot.client.interfaces.Listener; 6 | import cn.evole.onebot.sdk.event.message.GroupMessageEvent; 7 | import org.apache.logging.log4j.LogManager; 8 | import org.apache.logging.log4j.Logger; 9 | 10 | /** 11 | * @Project: onebot-client 12 | * @Author: cnlimiter 13 | * @CreateTime: 2024/1/27 14:59 14 | * @Description: 15 | */ 16 | 17 | @EventBus 18 | public class HandlerTest implements Listener { 19 | static OneBotClient client; 20 | static Logger logger; 21 | 22 | public static void main(String[] args) throws InterruptedException { 23 | logger = LogManager.getLogger("OneBot Client1"); 24 | BotConfig config = new BotConfig("ws://192.168.1.25:5800", "123456"); 25 | client = OneBotClient.create(config, new HandlerTest()).open(); 26 | //client.getEventsBus().register(new HandlerTest()); 27 | } 28 | 29 | @SubscribeEvent(internal = true) 30 | public void msg1(GroupMessageEvent event){ 31 | System.out.println(event.getMessage()); 32 | System.out.println(event.getRawMessage()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/JsonTest.java: -------------------------------------------------------------------------------- 1 | import cn.evole.onebot.client.OneBotClient; 2 | import cn.evole.onebot.client.core.BotConfig; 3 | import cn.evole.onebot.sdk.action.misc.ActionData; 4 | import cn.evole.onebot.sdk.entity.ArrayMsg; 5 | import cn.evole.onebot.sdk.entity.MsgId; 6 | import cn.evole.onebot.sdk.enums.MsgType; 7 | import cn.evole.onebot.sdk.util.GsonUtils; 8 | import cn.evole.onebot.sdk.util.MsgUtils; 9 | 10 | import java.util.ArrayList; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | /** 16 | * @Project: onebot-client 17 | * @Author: cnlimiter 18 | * @CreateTime: 2024/1/27 1:45 19 | * @Description: 20 | */ 21 | 22 | public class JsonTest { 23 | 24 | 25 | 26 | public static void main(String[] args) { 27 | List msg = new ArrayList<>(); 28 | Map data = new HashMap<>(); 29 | data.put("file", "123"); 30 | msg.add(new ArrayMsg().setType(MsgType.text).setData(data)); 31 | 32 | System.out.println(GsonUtils.getGson().toJson(msg)); 33 | 34 | Map msg2 = new HashMap<>(); 35 | Map msg3 = new HashMap<>(); 36 | msg2.put("message_type", "private"); 37 | msg3.put("message_type", "group"); 38 | List> msgList = new ArrayList<>(); 39 | msgList.add(msg2); 40 | msgList.add(msg3); 41 | System.out.println(GsonUtils.getGson().toJson(msgList)); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/server/AbstractWsEchoServer.java: -------------------------------------------------------------------------------- 1 | package server; 2 | 3 | import org.apache.logging.log4j.Logger; 4 | import org.java_websocket.WebSocket; 5 | import org.java_websocket.handshake.ClientHandshake; 6 | import org.java_websocket.server.WebSocketServer; 7 | 8 | import java.net.InetSocketAddress; 9 | import java.nio.charset.StandardCharsets; 10 | 11 | public abstract class AbstractWsEchoServer extends WebSocketServer { 12 | 13 | Logger log; 14 | 15 | public AbstractWsEchoServer(Logger log, InetSocketAddress address) { 16 | super(address); 17 | this.log = log; 18 | } 19 | 20 | @Override 21 | public void onOpen(WebSocket conn, ClientHandshake handshake) { 22 | log.info("onOpen: {} " , new String(handshake.getContent(), StandardCharsets.UTF_8)); 23 | } 24 | 25 | @Override 26 | public void onClose(WebSocket conn, int code, String reason, boolean remote) { 27 | log.info(""); 28 | } 29 | 30 | @Override 31 | public void onMessage(WebSocket conn, String message) { 32 | log.info("received message: {} ", message); 33 | conn.send(handleMessage(message)); 34 | } 35 | 36 | protected abstract String handleMessage(String inputMsg); 37 | @Override 38 | public void onError(WebSocket conn, Exception ex) { 39 | 40 | } 41 | 42 | @Override 43 | public void onStart() { 44 | log.info("onStart() "); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/server/impl/SimpleWsEchoServer.java: -------------------------------------------------------------------------------- 1 | package server.impl; 2 | 3 | import org.apache.logging.log4j.Logger; 4 | import org.java_websocket.WebSocket; 5 | import org.java_websocket.handshake.ClientHandshake; 6 | import server.AbstractWsEchoServer; 7 | 8 | import java.net.InetSocketAddress; 9 | 10 | public class SimpleWsEchoServer extends AbstractWsEchoServer { 11 | 12 | public SimpleWsEchoServer(Logger logger, InetSocketAddress address) { 13 | super(logger, address); 14 | } 15 | 16 | @Override 17 | public void onOpen(WebSocket conn, ClientHandshake handshake) { 18 | super.onOpen(conn, handshake); 19 | } 20 | 21 | @Override 22 | protected String handleMessage(String inputMsg) { 23 | return inputMsg; 24 | } 25 | } 26 | --------------------------------------------------------------------------------