├── .gitignore
├── LICENSE
├── Readme.md
├── bot
├── bot.go
└── client.go
├── func.go
├── go.mod
├── go.sum
├── message
├── chain.go
├── event.go
└── message.go
├── test
└── main.go
└── tools
├── json.go
└── log.go
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 |
3 | test.http
--------------------------------------------------------------------------------
/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 | # 建议使用 [MiraiGo-Template](https://github.com/Logiase/MiraiGo-Template)
2 |
3 | 目前gomirai已经有段时间没有维护,并且Mirai-Api-Http也在重构中,可能有不兼容的情况
4 |
5 | 建议使用基于[Mirai](https://github.com/mamoe/mirai)与[MiraiGo](https://github.com/Mrs4s/MiraiGo)的便于开发的[MiraiGo-Template](https://github.com/Logiase/MiraiGo-Template)
6 |
7 | # Go-Mirai
8 |
9 | [](https://goreportcard.com/report/github.com/Logiase/gomirai)
10 |
11 | 适配[MiraiHttpApi](https://github.com/project-mirai/mirai-api-http)的Go SDK
12 |
13 | 已完成所有基本功能
14 |
15 | 已完成所有基础功能,但随着日后更新及优化,目前API仍有可能发生变化
16 |
17 | ## 目前工作
18 |
19 | 为使用者提供更加方便的事件处理函数
20 |
21 | ## 如何使用
22 |
23 | 请参照[example](/test/main.go)
24 |
25 | 所有导出函数、变量、结构均有详细注释
26 |
27 | ### 不了解Go?
28 |
29 | (安利狂魔) [Go急速入门](https://learn.go.dev/)
30 |
31 | ### 目前问题
32 |
33 | 暂无
34 |
35 | ## 仍未实现
36 |
37 | - websocket
38 | - 上报
39 | - 心跳
40 |
41 | ## 维护者
42 |
43 | [Logiase](https://github.com/Logiase)
44 |
45 | ## 许可证
46 |
47 | [AGPL-3.0](LICENSE) © Logiase
48 |
--------------------------------------------------------------------------------
/bot/bot.go:
--------------------------------------------------------------------------------
1 | package bot
2 |
3 | import (
4 | "errors"
5 | "os"
6 | "strconv"
7 | "time"
8 |
9 | "github.com/sirupsen/logrus"
10 |
11 | "github.com/Logiase/gomirai/message"
12 | "github.com/Logiase/gomirai/tools"
13 | )
14 |
15 | // Bot 对应一个机器人账号
16 | // 进行所有对账号相关操作
17 | type Bot struct {
18 | QQ uint
19 | SessionKey string
20 |
21 | Client *Client
22 |
23 | Logger *logrus.Entry
24 |
25 | fetchTime time.Duration
26 | size int
27 | currentSize int
28 | Chan chan message.Event
29 |
30 | Friends []message.Friend
31 | Groups []message.Group
32 | }
33 |
34 | // --- Bot 设置 ---
35 |
36 | // SetChannel Channel相关设置
37 | func (b *Bot) SetChannel(time time.Duration, size int) {
38 | b.Chan = make(chan message.Event, size)
39 | b.size = size
40 | b.currentSize = 0
41 | b.fetchTime = time
42 | }
43 |
44 | // --- 消息相关 ---
45 |
46 | // SendFriendMessage 使用此方法向指定好友发送消息
47 | // qq 好友qq
48 | // quote 引用消息id 0为不引用
49 | // msg 消息内容
50 | func (b *Bot) SendFriendMessage(qq, quote uint, msg ...message.Message) (uint, error) {
51 | data := map[string]interface{}{"sessionKey": b.SessionKey, "qq": qq, "messageChain": msg}
52 | if quote != 0 {
53 | data["quote"] = quote
54 | }
55 | res, err := b.Client.doPost("/sendFriendMessage", data)
56 | if err != nil {
57 | return 0, err
58 | }
59 | b.Logger.Info("Send FriendMessage to ", qq)
60 | return tools.Json.Get([]byte(res), "messageId").ToUint(), nil
61 | }
62 |
63 | // SendTempMessage 使用此方法向临时会话对象发送消息
64 | // qq 好友qq
65 | // group 群qq
66 | // msg 消息内容
67 | func (b *Bot) SendTempMessage(group, qq uint, msg ...message.Message) (uint, error) {
68 | data := map[string]interface{}{"sessionKey": b.SessionKey, "qq": qq, "group": group, "messageChain": msg}
69 | res, err := b.Client.doPost("/sendTempMessage", data)
70 | if err != nil {
71 | return 0, err
72 | }
73 | b.Logger.Info("Send TempMessage to ", qq)
74 | return tools.Json.Get([]byte(res), "messageId").ToUint(), nil
75 | }
76 |
77 | // SendGroupMessage 使用此方法向指定群发送消息
78 | // group 群qq
79 | // quote 引用消息id 0为不引用
80 | // msg 消息内容
81 | func (b *Bot) SendGroupMessage(group, quote uint, msg ...message.Message) (uint, error) {
82 | data := map[string]interface{}{"sessionKey": b.SessionKey, "group": group, "messageChain": msg}
83 | if quote != 0 {
84 | data["quote"] = quote
85 | }
86 | res, err := b.Client.doPost("/sendGroupMessage", data)
87 | if err != nil {
88 | return 0, err
89 | }
90 | b.Logger.Info("Send FriendMessage to", group)
91 | return tools.Json.Get([]byte(res), "messageId").ToUint(), nil
92 | }
93 |
94 | // SendImageMessage 使用此方法向指定对象(群或好友)发送图片消息
95 | // 除非需要通过此手段获取imageId,否则不推荐使用该接口
96 | // 请保证 qq group 不同时有值
97 | func (b *Bot) SendImageMessage(qq, group int64, urls ...string) (imageIds []string, err error) {
98 | if qq*group == 0 {
99 | return nil, errors.New("非法参数")
100 | }
101 | data := map[string]interface{}{"sessionKey": b.SessionKey, "urls": urls}
102 | if qq == 0 {
103 | data["group"] = group
104 | } else {
105 | data["qq"] = qq
106 | }
107 | res, err := b.Client.doPost("sendImageMessage", data)
108 | if err != nil {
109 | return nil, err
110 | }
111 | b.Logger.Info("Send Images")
112 | err = tools.Json.UnmarshalFromString(res, &imageIds)
113 | return
114 | }
115 |
116 | // UploadImage 使用此方法上传图片文件至服务器并返回ImageId
117 | func (b *Bot) UploadImage(t string, imgFilepath string) (string, error) {
118 | imgReader, err := os.Open(imgFilepath)
119 | if err != nil {
120 | return "", err
121 | }
122 | defer imgReader.Close()
123 |
124 | data := map[string]interface{}{"sessionKey": b.SessionKey, "type": t, "img": imgReader}
125 | res, err := b.Client.doPostWithFormData("/uploadImage", data)
126 | if err != nil {
127 | return "", err
128 | }
129 | b.Logger.Info("UploadFriendImage ", imgFilepath)
130 | return tools.Json.Get([]byte(res), "imageId").ToString(), nil
131 | }
132 |
133 | // Recall 使用此方法撤回指定消息
134 | // 对于bot发送的消息,有2分钟时间限制。对于撤回群聊中群员的消息,需要有相应权限
135 | // target 消息id
136 | func (b *Bot) Recall(target int64) error {
137 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target}
138 | _, err := b.Client.doPost("/recall", data)
139 | return err
140 | }
141 |
142 | // FetchMessages 获取消息
143 | func (b *Bot) FetchMessages() error {
144 | t := time.NewTicker(b.fetchTime)
145 |
146 | for {
147 | res, err := b.Client.doGet("/fetchMessage", map[string]string{
148 | "sessionKey": b.SessionKey,
149 | "count": strconv.Itoa(b.size),
150 | })
151 | if err != nil {
152 | return err
153 | }
154 | var tc []message.Event
155 | tools.Json.Get([]byte(res), "data").ToVal(&tc)
156 | for _, v := range tc {
157 | if len(b.Chan) == b.size {
158 | <-b.Chan
159 | }
160 | b.Chan <- v
161 | }
162 |
163 | <-t.C
164 | }
165 | }
166 |
167 | // --- 管理相关 ---
168 |
169 | // FriendList 使用此方法获取bot的好友列表
170 | func (b *Bot) FriendList() error {
171 | data := map[string]string{"sessionKey": b.SessionKey}
172 | res, err := b.Client.doGet("/friendList", data)
173 | if err != nil {
174 | return err
175 | }
176 | return tools.Json.UnmarshalFromString(res, &b.Friends)
177 | }
178 |
179 | // GroupList 使用此方法获取bot的群列表
180 | func (b *Bot) GroupList() error {
181 | data := map[string]string{"sessionKey": b.SessionKey}
182 | res, err := b.Client.doGet("/groupList", data)
183 | if err != nil {
184 | return err
185 | }
186 | return tools.Json.UnmarshalFromString(res, &b.Groups)
187 | }
188 |
189 | // MemberList 使用此方法获取bot指定群种的成员列表
190 | func (b *Bot) MemberList(target int64) ([]message.Sender, error) {
191 | data := map[string]string{"sessionKey": b.SessionKey, "target": strconv.FormatInt(target, 10)}
192 | res, err := b.Client.doGet("/memberList", data)
193 | if err != nil {
194 | return nil, err
195 | }
196 | var list []message.Sender
197 | err = tools.Json.UnmarshalFromString(res, &list)
198 | return list, err
199 | }
200 |
201 | // MuteAll 使用此方法令指定群进行全体禁言(需要有相关限权)
202 | func (b *Bot) MuteAll(target int64) error {
203 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target}
204 | _, err := b.Client.doPost("/muteAll", data)
205 | return err
206 | }
207 |
208 | // UnMuteAll 使用此方法令指定群解除全体禁言(需要有相关限权)
209 | func (b *Bot) UnMuteAll(target int64) error {
210 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target}
211 | _, err := b.Client.doPost("/unmuteAll", data)
212 | return err
213 | }
214 |
215 | // Mute 使用此方法指定群禁言指定群员(需要有相关限权)
216 | func (b *Bot) Mute(target, memberID, time int64) error {
217 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target, "memberId": memberID, "time": time}
218 | _, err := b.Client.doPost("/mute", data)
219 | return err
220 | }
221 |
222 | // UnMute 使用此方法指定群解除群成员禁言(需要有相关限权)
223 | func (b *Bot) UnMute(target, memberID int64) error {
224 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target, "memberId": memberID}
225 | _, err := b.Client.doPost("/unmute", data)
226 | return err
227 | }
228 |
229 | // Kick 使用此方法移除指定群成员(需要有相关限权)
230 | func (b *Bot) Kick(target, memberID int64, msg string) error {
231 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target, "memberId": memberID, "msg": msg}
232 | _, err := b.Client.doPost("/kick", data)
233 | return err
234 | }
235 |
236 | // Quit 使用此方法使Bot退出群聊
237 | func (b *Bot) Quit(target int64) error {
238 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target}
239 | _, err := b.Client.doPost("/quit", data)
240 | return err
241 | }
242 |
243 | // GroupConfig 使用此方法修改群设置(需要有相关限权)
244 | func (b *Bot) GroupConfig(target int64, config message.GroupConfig) error {
245 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target, "config": config}
246 | _, err := b.Client.doPost("/groupConfig", data)
247 | return err
248 | }
249 |
250 | // GetGroupConfig 使用此方法获取群设置
251 | func (b *Bot) GetGroupConfig(target int64) (message.GroupConfig, error) {
252 | r := message.GroupConfig{}
253 | data := map[string]string{"sessionKey": b.SessionKey, "target": strconv.FormatInt(target, 10)}
254 | res, err := b.Client.doGet("/groupConfig", data)
255 | if err != nil {
256 | return r, err
257 | }
258 | err = tools.Json.UnmarshalFromString(res, &r)
259 | return r, err
260 | }
261 |
262 | // MemberInfo 使用此方法修改群员资料(需要有相关限权)
263 | func (b *Bot) MemberInfo(target, memberID int64, info message.MemberInfo) error {
264 | data := map[string]interface{}{"sessionKey": b.SessionKey, "target": target, "memberId": memberID, "info": info}
265 | _, err := b.Client.doPost("/memberInfo", data)
266 | return err
267 | }
268 |
269 | // GetMemberInfo 使用此方法获取群员资料
270 | func (b *Bot) GetMemberInfo(target, memberID int64) (message.MemberInfo, error) {
271 | r := message.MemberInfo{}
272 | data := map[string]string{"sessionKey": b.SessionKey, "target": strconv.FormatInt(target, 10), "memberId": strconv.FormatInt(memberID, 10)}
273 | res, err := b.Client.doGet("/groupConfig", data)
274 | if err != nil {
275 | return r, err
276 | }
277 | err = tools.Json.UnmarshalFromString(res, &r)
278 | return r, err
279 | }
280 |
281 | // --- 相应 ---
282 |
283 | // RespondMemberJoinRequest 响应用户加群请求
284 | // operate 说明
285 | // 0 同意入群
286 | // 1 拒绝入群
287 | // 2 忽略请求
288 | // 3 拒绝入群并添加黑名单,不再接收该用户的入群申请
289 | // 4 忽略入群并添加黑名单,不再接收该用户的入群申请
290 | func (b *Bot) RespondMemberJoinRequest(eventID, fromID, groupID int64, operate int, message string) error {
291 | data := map[string]interface{}{"sessionKey": b.SessionKey, "eventId": eventID, "fromId": fromID, "groupId": groupID, "operate": operate, "message": message}
292 | _, err := b.Client.doPost("/resp/memberJoinRequestEvent", data)
293 | if err != nil {
294 | return err
295 | }
296 | b.Logger.Info("Respond Member Join Request ", fromID, " join ", groupID, " operate: ", operate)
297 | return nil
298 | }
299 |
300 | // --- Handler ---
301 |
302 | // UseHandler 使用选定的 EventHandler 进行事件响应
303 | // 未实装
304 | //func (b *Bot) UseHandler(handler helper.EventHandler) {
305 | // b.handlers = handler
306 | //}
307 |
308 | // Run 使用 eventHandler 进行事件相应
309 | // 与使用 FetchMessage 方法有所冲突
310 | // 未实装
311 | func (b *Bot) run() {
312 | go func() {
313 | err := b.FetchMessages()
314 | if err != nil {
315 | b.Client.Logger.Panic(err)
316 | }
317 | }()
318 |
319 | for {
320 | e := <-b.Chan
321 | switch e.Type {
322 | case message.EventReceiveGroupMessage:
323 |
324 | }
325 | }
326 | }
327 |
--------------------------------------------------------------------------------
/bot/client.go:
--------------------------------------------------------------------------------
1 | package bot
2 |
3 | import (
4 | "errors"
5 | "io"
6 | "strconv"
7 | "time"
8 |
9 | "gopkg.in/h2non/gentleman.v2/plugins/multipart"
10 |
11 | "gopkg.in/h2non/gentleman.v2"
12 | "gopkg.in/h2non/gentleman.v2/plugins/body"
13 |
14 | "github.com/sirupsen/logrus"
15 |
16 | "github.com/Logiase/gomirai/tools"
17 | )
18 |
19 | // Client 与Mirai进行沟通
20 | type Client struct {
21 | Name string
22 | AuthKey string
23 |
24 | HttpClient *gentleman.Client
25 | Bots map[uint]*Bot
26 |
27 | Logger *logrus.Entry
28 | }
29 |
30 | // NewClient 新建Client
31 | func NewClient(name, url, authKey string) *Client {
32 | c := gentleman.New()
33 | c.URL(url)
34 |
35 | return &Client{
36 | AuthKey: authKey,
37 | HttpClient: c,
38 | Bots: make(map[uint]*Bot),
39 | Logger: logrus.New().WithFields(logrus.Fields{
40 | "client": name,
41 | }),
42 | }
43 | }
44 |
45 | // --- API-HTTP插件相关 ---
46 |
47 | // About 使用此方法获取插件的信息,如版本号
48 | func (c *Client) About() (string, error) {
49 | res, err := c.doGet("/about", nil)
50 | if err != nil {
51 | return "", err
52 | }
53 | return tools.Json.Get([]byte(res), "data").Get("version").ToString(), nil
54 | }
55 |
56 | // --- 认证相关 ---
57 |
58 | // Auth 使用此方法验证你的身份,并返回一个会话
59 | func (c *Client) Auth() (string, error) {
60 | data := map[string]string{"authKey": c.AuthKey}
61 | res, err := c.doPost("/auth", data)
62 | if err != nil {
63 | return "", err
64 | }
65 | c.Logger.Info("Authed")
66 | return tools.Json.Get([]byte(res), "session").ToString(), nil
67 | }
68 |
69 | // Verify 使用此方法校验并激活你的Session,同时将Session与一个已登录的Bot绑定
70 | func (c *Client) Verify(qq uint, sessionKey string) (*Bot, error) {
71 | data := map[string]interface{}{"sessionKey": sessionKey, "qq": qq}
72 | _, err := c.doPost("/verify", data)
73 | if err != nil {
74 | return nil, err
75 | }
76 | c.Bots[qq] = &Bot{QQ: qq, SessionKey: sessionKey, Client: c, Logger: c.Logger.WithField("qq", qq)}
77 | c.Bots[qq].SetChannel(time.Second, 10)
78 | c.Logger.Info("Verified")
79 | return c.Bots[qq], nil
80 | }
81 |
82 | // Release 使用此方式释放session及其相关资源(Bot不会被释放)
83 | // 不使用的Session应当被释放,长时间(30分钟)未使用的Session将自动释放,否则Session持续保存Bot收到的消息,将会导致内存泄露(开启websocket后将不会自动释放)
84 | func (c *Client) Release(qq uint) error {
85 | data := map[string]interface{}{"sessionKey": c.Bots[qq].SessionKey, "qq": qq}
86 | _, err := c.doPost("release", data)
87 | if err != nil {
88 | return err
89 | }
90 | delete(c.Bots, qq)
91 | c.Logger.Info("Released")
92 | return nil
93 | }
94 |
95 | // --- internal ---
96 |
97 | func (c *Client) doPost(path string, data interface{}) (string, error) {
98 | c.Logger.Trace("POST:"+path+" Data:", data)
99 | res, err := c.HttpClient.Request().
100 | Path(path).
101 | Method("POST").
102 | Use(body.JSON(data)).
103 | SetHeader("Content-Type", "application/json;charset=utf-8").
104 | Send()
105 | if err != nil {
106 | c.Logger.Warn("POST Failed")
107 | return "", err
108 | }
109 | c.Logger.Trace("result StatusCode:", res.StatusCode)
110 | if !res.Ok {
111 | return res.String(), errors.New("Http: " + strconv.Itoa(res.StatusCode))
112 | }
113 | if tools.Json.Get([]byte(res.String()), "code").ToInt() != 0 {
114 | return res.String(), getErrByCode(tools.Json.Get([]byte(res.String()), "code").ToUint())
115 | }
116 | return res.String(), nil
117 | }
118 |
119 | func (c *Client) doPostWithFormData(path string, fields map[string]interface{}) (string, error) {
120 | data := make(multipart.DataFields)
121 | files := make([]multipart.FormFile, 0)
122 |
123 | for key, value := range fields {
124 | if unbox, ok := value.(string); ok {
125 | data[key] = append(data[key], unbox)
126 | } else if unbox, ok := value.(io.Reader); ok {
127 | files = append(files, multipart.FormFile{Name: key, Reader: unbox})
128 | }
129 | }
130 |
131 | formData := multipart.FormData{Data: data, Files: files}
132 |
133 | c.Logger.Trace("POST:"+path+" FormData:", formData)
134 | res, err := c.HttpClient.Request().
135 | Path(path).
136 | Method("POST").
137 | Use(multipart.Data(formData)).
138 | Send()
139 | if err != nil {
140 | c.Logger.Warn("POST Failed")
141 | return "", err
142 | }
143 | c.Logger.Trace("result StatusCode:", res.StatusCode)
144 | if !res.Ok {
145 | return res.String(), errors.New("Http: " + strconv.Itoa(res.StatusCode))
146 | }
147 | if tools.Json.Get([]byte(res.String()), "code").ToInt() != 0 {
148 | return res.String(), getErrByCode(tools.Json.Get([]byte(res.String()), "code").ToUint())
149 | }
150 | return res.String(), nil
151 | }
152 |
153 | func (c *Client) doGet(path string, params map[string]string) (string, error) {
154 | c.Logger.Trace("GET:" + path)
155 | res, err := c.HttpClient.Request().
156 | Path(path).
157 | SetQueryParams(params).
158 | Method("GET").
159 | SetHeader("Content-Type", "application/json;charset=utf-8").
160 | Send()
161 | if err != nil {
162 | c.Logger.Warn("GET Failed")
163 | return "", err
164 | }
165 | c.Logger.Trace("result StatusCode:", res.StatusCode)
166 | if !res.Ok {
167 | return res.String(), errors.New("Http: " + strconv.Itoa(res.StatusCode))
168 | }
169 | if tools.Json.Get([]byte(res.String()), "code").ToInt() != 0 {
170 | return res.String(), getErrByCode(tools.Json.Get([]byte(res.String()), "code").ToUint())
171 | }
172 | return res.String(), nil
173 | }
174 |
175 | func getErrByCode(code uint) error {
176 | switch code {
177 | case 0:
178 | return nil
179 | case 1:
180 | return errors.New("错误的auth key")
181 | case 2:
182 | return errors.New("指定的Bot不存在")
183 | case 3:
184 | return errors.New("Session失效或不存在")
185 | case 4:
186 | return errors.New("Session未认证(未激活)")
187 | case 5:
188 | return errors.New("发送消息目标不存在(指定对象不存在)")
189 | case 6:
190 | return errors.New("指定文件不存在,出现于发送本地图片")
191 | case 10:
192 | return errors.New("无操作权限,指Bot没有对应操作的限权")
193 | case 20:
194 | return errors.New("Bot被禁言,指Bot当前无法向指定群发送消息")
195 | case 30:
196 | return errors.New("消息过长")
197 | case 400:
198 | return errors.New("错误的访问,如参数错误等")
199 | default:
200 | return errors.New("未知错误,Code:" + string(code))
201 | }
202 | }
203 |
--------------------------------------------------------------------------------
/func.go:
--------------------------------------------------------------------------------
1 | package gomirai
2 |
3 | import (
4 | "github.com/Logiase/gomirai/bot"
5 | "github.com/Logiase/gomirai/message"
6 | )
7 |
8 | func SendGroupMessageWithBot(b *bot.Bot, qq, quote uint, msg ...message.Message) (uint, error) {
9 | return b.SendGroupMessage(qq, quote, msg...)
10 | }
11 |
12 | func SendFriendMessageWithBot(b *bot.Bot, group, quote uint, msg ...message.Message) (uint, error) {
13 | return b.SendGroupMessage(group, quote, msg...)
14 | }
15 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/Logiase/gomirai
2 |
3 | go 1.14
4 |
5 | require (
6 | github.com/json-iterator/go v1.1.10
7 | github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 // indirect
8 | github.com/sirupsen/logrus v1.6.0
9 | golang.org/x/net v0.0.0-20200625001655-4c5254603344 // indirect
10 | gopkg.in/h2non/gentleman.v2 v2.0.4
11 | )
12 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
5 | github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68=
6 | github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
7 | github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
8 | github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
9 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
10 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
11 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
12 | github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
13 | github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
14 | github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
15 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
16 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
17 | github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
18 | github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
19 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
20 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
21 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
22 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
23 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
24 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
25 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
26 | golang.org/x/net v0.0.0-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrSV+Z2tcbze+pEc3v5W4=
27 | golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
28 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
29 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
30 | golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
31 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
32 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
33 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
34 | gopkg.in/h2non/gentleman.v2 v2.0.4 h1:9R3K6CFYd/RdXDLi0pGXwaPnRx/pn5EZlrN3VkNygWc=
35 | gopkg.in/h2non/gentleman.v2 v2.0.4/go.mod h1:A1c7zwrTgAyyf6AbpvVksYtBayTB4STBUGmdkEtlHeA=
36 |
--------------------------------------------------------------------------------
/message/chain.go:
--------------------------------------------------------------------------------
1 | package message
2 |
3 | type Chain struct {
4 | Msg []Message
5 | }
6 |
7 | func GenChain(args ...Message) Chain {
8 | return Chain{
9 | Msg: args,
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/message/event.go:
--------------------------------------------------------------------------------
1 | package message
2 |
3 | const (
4 | EventReceiveFriendMessage = "FriendMessage"
5 | EventReceiveGroupMessage = "GroupMessage"
6 | EventReceiveTempMessage = "TempMessage"
7 | EventBotOnline = "BotOnlineEvent"
8 | EventBotOfflineActive = "BotOfflineEventActive"
9 | EventBotOfflineForce = "BotOfflineEventForce"
10 | EventBotOfflineDropped = "BotOfflineEventDropped"
11 | EventBotRelogin = "BotReloginEvent"
12 | EventGroupRecall = "GroupRecallEvent"
13 | EventFriendRecall = "FriendRecallEvent"
14 | EventBotGroupPermissionChange = "BotGroupPermissionChangeEvent"
15 | EventBotMute = "BotMuteEvent"
16 | EventBotUnmute = "BotUnmuteEvent"
17 | EventBotJoinGroup = "BotJoinGroupEvent"
18 | EventBotLeaveActive = "BotLeaveEventActive"
19 | EventBotLeaveKick = "BotLeaveEventKick"
20 | EventGroupNameChange = "GroupNameChangeEvent"
21 | EventGroupEntranceAnnouncementChange = "GroupEntranceAnnouncementChangeEvent"
22 | EventGroupMuteAll = "GroupMuteAllEvent"
23 | EventGroupAllowAnonymousChat = "GroupAllowAnonymousChatEvent"
24 | EventGroupAllowConfessTalk = "GroupAllowConfessTalkEvent"
25 | EventGroupAllowMemberInvite = "GroupAllowMemberInviteEvent"
26 | EventMemberJoin = "MemberJoinEvent"
27 | EventMemberLeaveKick = "MemberLeaveEventKick"
28 | EventMemberLeaveQuit = "MemberLeaveEventQuit"
29 | EventMemberCardChange = "MemberCardChangeEvent"
30 | EventMemberSpecialTitleChange = "MemberSpecialTitleChangeEvent"
31 | EventMemberPermissionChange = "MemberPermissionChangeEvent"
32 | EventMemberMute = "MemberMuteEvent"
33 | EventMemberUnmute = "MemberUnmuteEvent"
34 | EventNewFriendRequest = "NewFriendRequestEvent"
35 | EventMemberJoinRequest = "MemberJoinRequestEvent"
36 | EventBotInvitedJoinGroupRequest = "BotInvitedJoinGroupRequestEvent"
37 | )
38 |
39 | type Event struct {
40 | Type string `json:"type"` //事件类型
41 | MessageChain []Message `json:"messageChain"` //(ReceiveMessage)消息链
42 | Sender Sender `json:"sender"` //(ReceiveMessage)发送者信息
43 | EventId uint `json:"eventId"` //事件ID
44 | FromId uint `json:"fromId"` //操作人
45 | GroupId uint `json:"groupId"` //群号
46 | }
47 |
48 | type Group struct {
49 | Id uint `json:"id,omitempty"` //消息来源群号
50 | Name string `json:"name,omitempty"` //消息来源群名
51 | Permisson string `json:"permisson,omitempty"` //bot在群中的角色
52 | }
53 |
54 | type Friend struct {
55 | Id uint `json:"id,omitempty"` //QQ
56 | NickName string `json:"memberName,omitempty"` //昵称
57 | Remark string `json:"remark,omitempty"` //备注
58 | }
59 |
60 | type Sender struct {
61 | Friend
62 | MemberName string `json:"memberName,omitempty"` //(GroupMessage)发送者群昵称
63 | Permission string `json:"permission,omitempty"` //(GroupMessage)发送者在群中的角色
64 | Group Group `json:"group,omitempty"` //(GroupMessage)消息来源群信息
65 | }
66 |
67 | type GroupConfig struct {
68 | Name string
69 | Announcement string
70 | ConfessTalk bool
71 | AllowMemberInvite bool
72 | AutoApprove bool
73 | AnonymousChat bool
74 | }
75 |
76 | type MemberInfo struct {
77 | Name string
78 | SpecialTitle string
79 | }
80 |
--------------------------------------------------------------------------------
/message/message.go:
--------------------------------------------------------------------------------
1 | package message
2 |
3 | const (
4 | MsgType_Source = "Source"
5 | MsgType_Quote = "Quote"
6 | MsgType_At = "At"
7 | MsgType_AtAll = "AtAll"
8 | MsgType_Face = "Face"
9 | MsgType_Plain = "Plain"
10 | MsgType_Image = "Image"
11 | MsgType_FlashImage = "FlashImage"
12 | MsgType_Xml = "Xml"
13 | MsgType_Json = "Json"
14 | MsgType_App = "App"
15 | MsgType_Poke = "Poke"
16 | )
17 |
18 | type Message struct {
19 | Type string `json:"type,omitempty"`
20 | Id uint `json:"id,omitempty"` //(Source,Quote)Source中表示消息id,Quote中表示被引用回复的原消息的id
21 | Time int64 `json:"time,omitempty"` //(Source) 发送时间
22 | GroupId uint `json:"groupId,omitempty"` //(Quote)Quote中表示被引用回复的原消息的群号
23 | SenderId uint `json:"senderId,omitempty"` //(Quote)Quote中表示被引用回复的原消息的发送者QQ号
24 | TargetId uint `json:"targetId,omitempty"` //(Quote)Quote中表示被引用回复的原消息的接收者群号或QQ号
25 | Origin []Message `json:"origin,omitempty"` //(Quote)Quote中表示被引用回复的原消息的消息链对象
26 | Target uint `json:"target,omitempty"` //(At)@的群员QQ号
27 | Display string `json:"display,omitempty"` //(At)@的显示文本
28 | FaceId int `json:"faceId,omitempty"` //(Face)QQ表情的ID,发送时优先级比Name高
29 | Name string `json:"name,omitempty"` //(Face,Poke)Face中为QQ表情的拼音,Poke中为戳一戳的类型
30 | Text string `json:"text,omitempty"` //(Plain)纯文本
31 | ImageId string `json:"imageId,omitempty"` //(Image,FlashImage)图片ID,注意消息类型,群图片和好友图片格式不一样,发送时优先级比ImageUrl高
32 | ImageUrl string `json:"url,omitempty"` //(Image,FlashImage)图片url,发送时可使用网络图片的链接,优先级比ImagePath高;接收时为腾讯图片服务器的链接
33 | ImagePath string `json:"path,omitempty"` //(Image,FlashImage)图片的路径,发送本地图片,相对路径于plugins/MiraiAPIHTTP/images
34 | Xml string `json:"xml,omitempty"` //(Xml) xml消息本体
35 | Json string `json:"json,omitempty"` //(Json) json消息本体
36 | Content string `json:"content,omitempty"` //(App) 不知道干嘛的,mirai也没有说明,估计是小程序连接?
37 | }
38 |
39 | func PlainMessage(text string) Message {
40 | return Message{Type: MsgType_Plain, Text: text}
41 | }
42 |
43 | func AtMessage(target uint) Message {
44 | if target == 0 {
45 | return Message{Type: MsgType_AtAll}
46 | }
47 | return Message{Type: MsgType_At, Target: target}
48 | }
49 |
50 | func FaceMessage(faceID int) Message {
51 | return Message{Type: MsgType_Face, FaceId: faceID}
52 | }
53 |
54 | func ImageMessage(t, v string) Message {
55 | m := Message{Type: MsgType_Image}
56 | switch t {
57 | case "id":
58 | m.ImageId = v
59 | case "url":
60 | m.ImageUrl = v
61 | case "path":
62 | m.ImagePath = v
63 | default:
64 | return Message{}
65 | }
66 | return m
67 | }
68 |
69 | func FlashImageMessage(t, v string) Message {
70 | m := Message{Type: MsgType_FlashImage}
71 | switch t {
72 | case "id":
73 | m.ImageId = v
74 | case "url":
75 | m.ImageUrl = v
76 | case "path":
77 | m.ImagePath = v
78 | default:
79 | return Message{}
80 | }
81 | return m
82 | }
83 |
84 | func RichMessage(t, content string) Message {
85 | m := Message{}
86 | switch t {
87 | case MsgType_Json:
88 | m.Type = t
89 | m.Json = content
90 | case MsgType_Xml:
91 | m.Type = t
92 | m.Xml = content
93 | case MsgType_App:
94 | m.Type = t
95 | m.Content = content
96 | default:
97 | return Message{}
98 | }
99 | return m
100 | }
101 |
102 | func PokeMessage(name string) Message {
103 | return Message{Type: MsgType_Poke, Name: name}
104 | }
105 |
--------------------------------------------------------------------------------
/test/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/signal"
7 |
8 | "github.com/sirupsen/logrus"
9 |
10 | "github.com/Logiase/gomirai/bot"
11 | "github.com/Logiase/gomirai/message"
12 | )
13 |
14 | func main() {
15 | var qq uint = 2662969831
16 |
17 | interrupt := make(chan os.Signal, 1)
18 | signal.Notify(interrupt, os.Interrupt)
19 |
20 | c := bot.NewClient("default", "http://124.70.68.221:8001", "12345678")
21 | c.Logger.Level = logrus.TraceLevel
22 | key, err := c.Auth()
23 | if err != nil {
24 | c.Logger.Fatal(err)
25 | }
26 | b, err := c.Verify(qq, key)
27 | if err != nil {
28 | c.Logger.Fatal(err)
29 | }
30 | //defer c.Release(qq)
31 |
32 | go func() {
33 | err = b.FetchMessages()
34 | if err != nil {
35 | c.Logger.Fatal(err)
36 | }
37 | }()
38 |
39 | for {
40 | select {
41 | case e := <-b.Chan:
42 | switch e.Type {
43 | case message.EventReceiveGroupMessage:
44 | _, err = b.SendGroupMessage(e.Sender.Group.Id, 0, message.PlainMessage("中文消息"))
45 | if err != nil {
46 | fmt.Println(err)
47 | }
48 | }
49 | case <-interrupt:
50 | fmt.Println("######")
51 | fmt.Println("interrupt")
52 | fmt.Println("######")
53 | //c.Release(qq)
54 | c.Release(qq)
55 | return
56 | }
57 |
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/tools/json.go:
--------------------------------------------------------------------------------
1 | package tools
2 |
3 | import jsoniter "github.com/json-iterator/go"
4 |
5 | var Json = jsoniter.ConfigFastest
6 |
--------------------------------------------------------------------------------
/tools/log.go:
--------------------------------------------------------------------------------
1 | package tools
2 |
3 | import "github.com/sirupsen/logrus"
4 |
5 | var DefaultLogger *logrus.Logger = logrus.New()
6 |
7 | func init() {
8 | DefaultLogger.SetFormatter(&logrus.JSONFormatter{})
9 | }
10 |
--------------------------------------------------------------------------------