diff --git a/.gitignore b/.gitignore index 93f7660..4695bd5 100644 --- a/.gitignore +++ b/.gitignore @@ -35,7 +35,8 @@ lerna-debug.log* go-cqhttp +config.json src/koishi.config.ts src/koishi.config.prod.ts src/el.config.ts -src/el.config.prod.ts \ No newline at end of file +src/el.config.prod.ts diff --git a/README.md b/README.md index 455ec87..f29538e 100644 --- a/README.md +++ b/README.md @@ -2,26 +2,30 @@ ## 前置说明 ### 关于QQ机器人 -想要使用QQ机器人,首先需要安装go-cqhttp。 -- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp):是一个用来连接QQ并且会将消息通过http或websocket的方式上报给koishi程序。以达到让程序接收消息和发送消息 -- [Koishi](https://www.npmjs.com/package/koishi):是一个接入类似go-cqhttp平台的一个机器人nodejs库,用来方便我们使用nodejs制作qq机器人 +QQ机器人使用了el-bot的js库 +- [mirai-console-loader](https://github.com/iTXTech/mirai-console-loader) 帮助你搭建mirai所需要的环境 +- [el-bot](https://docs.bot.elpsy.cn):是一个接入mirai平台的一个机器人nodejs库,用来方便我们使用nodejs制作qq机器人 ### 关于Discord机器人 Discord制作机器人不需要类似go-cqhttp的中转程序。官方已经提供了相关api和开发者平台,让开发人员方便的制作机器人 -使用[discord.js](https://www.npmjs.com/package/discord.js)库就可以方便的使用 +使用[discord.js](https://www.npmjs.com/package/discord.js) 库就可以方便的使用 ## 本库安装使用方式 -### 一、下载安装go-cqhttp -[详细步骤](https://github.com/Mrs4s/go-cqhttp/blob/master/docs/quick_start.md) +### 一、启动MCL (mirai一键安装环境工具) +> 使用Docker的方式 +1. 修改文件 `mcl-1.1.0-beta.1/config/Console/AutoLogin.yml` 添加属于你的qq账号 +2. 直接运行命令 `docker-compose up` +正常情况,bot收到消息后,控制台会看的到就成功了 -1. 将对应操作系统的go-cqhttp下载到go-cqhttp目录 -2. 将go-cqhttp/config.sample.json 复制拷贝成 config.json 并配置 -```shell script -"uin": 0, <--- qq号 -"password": "", <--- 密码 -``` -3. 启动go-cqhttp +> 非Docker的方式 + +1. 安装java jdk 并且11以上的版本,配置好java环境变量, 控制台输入`java --version` 能看到版本信息就正常 +2. 修改文件 `mcl-1.1.0-beta.1/config/Console/AutoLogin.yml` 添加属于你的qq账号 +3. 进入`mcl-1.1.0-beta.1`目录,运行`./mcl` +正常情况,bot收到消息后,控制台会看的到就成功了 + +> 注: 推荐使用docker的方式,不只是本地,部署到云环境也方便 ### 二、配置 将koishi.sample.ts 复制拷贝成 koishi.config.ts, 并配置下面几项 @@ -54,7 +58,7 @@ discordBotToken: '', ### 三、运行 ```shell script npm install -npm start +npm run start:dev ``` ## 支持功能 @@ -65,7 +69,7 @@ npm start ### Discord -> QQ - [x] 回复消息同步至Discord -- [x] 支持图片和gif消息同步至Discord (gif暂不支持) +- [x] 支持图片和gif消息同步至Discord - [x] 支持回复消息同步至Discord ## 文档相关 @@ -73,3 +77,7 @@ npm start - https://discordjs.guide/#before-you-begin - https://discord.com/developers/applications/781193252094476360/bot - https://link.zhihu.com/?target=https%3A//amazonaws-china.com/cn/ + + +# ElBot +/autoLogin add diff --git a/cache/avatar/.gitkeep b/cache/avatar/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/cache/images/.gitkeep b/cache/images/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..6c06488 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' +services: + mirai-mcl: + ports: + - "8080:8080" + expose: + - "8080" + restart: always + privileged: 'true' + volumes: + - ./mcl-1.1.0-beta.1:/bridge/mcl + - ./cache:/bridge/cache + working_dir: /bridge/mcl + command: ./mcl + image: openjdk:11.0.10-oraclelinux8 +volumes: + logvolume01: {} + diff --git a/el-index.ts b/el-index.ts index b49af3b..8bae6c4 100644 --- a/el-index.ts +++ b/el-index.ts @@ -2,7 +2,7 @@ import * as log from './src/utils/log5'; import {DatabaseService} from "./src/database.service"; -import {ElAndDiscordService} from "./src/elAndDiscord.service"; +import {BotService} from "./src/el-bot/bot.service"; import bridgeQQToDiscord from './src/bridge-qq-to-discord.el'; @@ -11,12 +11,12 @@ import bridgeDiscordToQQ from './src/bridge-discord-to-qq.el'; async function main() { await DatabaseService.init(); log.message('🌈', `数据库连接成功`); - await ElAndDiscordService.initQQBot(); + await BotService.initQQBot(); log.message('🌈', `QQ 成功连接`); - await ElAndDiscordService.initDiscord(); - log.message('🌈', `Discord 成功登录 ${ElAndDiscordService.discord.user.tag}`); + await BotService.initDiscord(); + log.message('🌈', `Discord 成功登录 ${BotService.discord.user.tag}`); await bridgeQQToDiscord(); await bridgeDiscordToQQ(); } -main().then() \ No newline at end of file +main().then() diff --git a/mcl-1.1.0-beta.1/LICENSE b/mcl-1.1.0-beta.1/LICENSE new file mode 100644 index 0000000..bae94e1 --- /dev/null +++ b/mcl-1.1.0-beta.1/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. \ No newline at end of file diff --git a/mcl-1.1.0-beta.1/README.md b/mcl-1.1.0-beta.1/README.md new file mode 100644 index 0000000..aabe41d --- /dev/null +++ b/mcl-1.1.0-beta.1/README.md @@ -0,0 +1,58 @@ +# Mirai Console Loader + +模块化、轻量级且支持完全自定义的 [mirai](https://github.com/mamoe/mirai) 加载器。 + +欢迎阅读自带脚本的[说明](scripts/README.md),它将教会你如何`安装插件`,`禁用和启用脚本`,`修改包的更新频道`等基本操作。 + +## 简介 + +`iTX Technologies Mirai Console Loader`(下简称`MCL`)采用模块化设计,包含以下几个基础模块: + +* `Script` 脚本执行模块,用于加载和执行脚本,`MCL`的主要功能均由脚本实现。脚本执行有各个阶段,详见注释。 +* `Config` 配置文件模块,用于配置的持久化。 +* `Downloader` 下载器模块,用于下载文件,并实时返回进度。 +* `Logger` 日志模块,用于向控制台输出日志。 + +## 使用 `iTXTech MCL` + +### 一键安装 + +[iTXTech MCL Installer](https://github.com/iTXTech/mcl-installer) 能在所有操作系统上一键安装 `iTXTech MCL`。 + +### 手动安装 + +1. 安装 Java 运行时(版本必须 >= 11) +1. 从 [Releases](https://github.com/iTXTech/mirai-console-loader/releases) 下载最新版本的`MCL` +1. 解压到某处 +1. 在命令行中执行`.\mcl`以启动`MCL` + +## `Mirai Repo` 列表 + +* [Gitee](https://gitee.com/peratx/mirai-repo) - **默认**,如要镜像请完整拷贝该仓库文件即可 +* [GitHub](https://github.com/project-mirai/mirai-repo-mirror) - 位于`project-mirai`的镜像,国内首选`Gitee` + +## `Maven Repo` 列表 + +**`Bintray`和`JCenter`即将停止服务,请慎重选择托管服务。** + +* [Bintray - Him188moe](https://dl.bintray.com/him188moe/mirai) - `mamoe` 官方仓库,仅包含`mirai`相关包 +* [JCenter](https://jcenter.bintray.com/) - `mamoe` 官方仓库会自动同步到 `JCenter` +* [Aliyun](https://maven.aliyun.com/repository/public) - **默认**,阿里云`Maven`镜像,国内访问速度快 +* [HuaweiCloud](https://mirrors.huaweicloud.com/repository/maven) - 华为云`Maven`镜像,阿里云不可用时的备选方案 + +## 开源许可证 + + Copyright (C) 2020-2021 iTX Technologies + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . diff --git a/mcl-1.1.0-beta.1/bots/.gitkeep b/mcl-1.1.0-beta.1/bots/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/mcl-1.1.0-beta.1/config.json b/mcl-1.1.0-beta.1/config.json new file mode 100644 index 0000000..8317dcd --- /dev/null +++ b/mcl-1.1.0-beta.1/config.json @@ -0,0 +1,43 @@ +{ + "js_optimization_level": -1, + "mirai_repo": "https://gitee.com/peratx/mirai-repo/raw/master", + "maven_repo": [ + "https://maven.aliyun.com/repository/public" + ], + "packages": [ + { + "id": "org.bouncycastle:bcprov-jdk15on", + "channel": "stable", + "version": "1.64", + "type": "libs" + }, + { + "id": "net.mamoe:mirai-console", + "channel": "beta", + "version": "2.6.3", + "type": "libs" + }, + { + "id": "net.mamoe:mirai-console-terminal", + "channel": "beta", + "version": "2.6.3", + "type": "libs" + }, + { + "id": "net.mamoe:mirai-core-all", + "channel": "beta", + "version": "2.6.3", + "type": "libs" + }, + { + "id": "net.mamoe:mirai-api-http", + "channel": "stable", + "version": "1.10.0", + "type": "plugins" + } + ], + "disabled_scripts": [], + "proxy": "", + "log_level": 0, + "script_props": {} +} \ No newline at end of file diff --git a/mcl-1.1.0-beta.1/config/Console/AutoLogin.yml b/mcl-1.1.0-beta.1/config/Console/AutoLogin.yml new file mode 100644 index 0000000..5560313 --- /dev/null +++ b/mcl-1.1.0-beta.1/config/Console/AutoLogin.yml @@ -0,0 +1,14 @@ +accounts: + - # 账号, 现只支持 QQ 数字账号 + account: 123456 + password: + # 密码种类, 可选 PLAIN 或 MD5 + kind: PLAIN + # 密码内容, PLAIN 时为密码文本, MD5 时为 16 进制 + value: pwd + # 账号配置. 可用配置列表 (注意大小写): + # "protocol": "ANDROID_PHONE" / "ANDROID_PAD" / "ANDROID_WATCH" + # "device": "device.json" + configuration: + protocol: ANDROID_PHONE + device: device.json diff --git a/mcl-1.1.0-beta.1/config/Console/Command.yml b/mcl-1.1.0-beta.1/config/Console/Command.yml new file mode 100644 index 0000000..480f593 --- /dev/null +++ b/mcl-1.1.0-beta.1/config/Console/Command.yml @@ -0,0 +1,2 @@ +# 指令前缀, 默认 "/" +commandPrefix: '/' \ No newline at end of file diff --git a/mcl-1.1.0-beta.1/config/Console/ExtensionSelector.yml b/mcl-1.1.0-beta.1/config/Console/ExtensionSelector.yml new file mode 100644 index 0000000..d983ddd --- /dev/null +++ b/mcl-1.1.0-beta.1/config/Console/ExtensionSelector.yml @@ -0,0 +1 @@ +value: {} diff --git a/mcl-1.1.0-beta.1/config/Console/Logger.yml b/mcl-1.1.0-beta.1/config/Console/Logger.yml new file mode 100644 index 0000000..cdbb717 --- /dev/null +++ b/mcl-1.1.0-beta.1/config/Console/Logger.yml @@ -0,0 +1,7 @@ +# 日志输出等级 可选值: ALL, VERBOSE, DEBUG, INFO, WARNING, ERROR, NONE +defaultPriority: INFO +# 特定日志记录器输出等级 +loggers: + example.logger: NONE + console.debug: NONE + Bot: ALL \ No newline at end of file diff --git a/mcl-1.1.0-beta.1/config/Console/PermissionService.yml b/mcl-1.1.0-beta.1/config/Console/PermissionService.yml new file mode 100644 index 0000000..2346f13 --- /dev/null +++ b/mcl-1.1.0-beta.1/config/Console/PermissionService.yml @@ -0,0 +1,3 @@ +grantedPermissionMap: + '*:*': + - console \ No newline at end of file diff --git a/mcl-1.1.0-beta.1/config/net.mamoe.mirai-api-http/setting.yml b/mcl-1.1.0-beta.1/config/net.mamoe.mirai-api-http/setting.yml new file mode 100644 index 0000000..f0e6f00 --- /dev/null +++ b/mcl-1.1.0-beta.1/config/net.mamoe.mirai-api-http/setting.yml @@ -0,0 +1,28 @@ +cors: + - '*' +host: 0.0.0.0 +port: 8080 +authKey: INITKEYKPRGCLwL +cacheSize: 4096 +enableWebsocket: false +report: + enable: false + groupMessage: + report: true + friendMessage: + report: true + tempMessage: + report: true + eventMessage: + report: true + destinations: [] + extraHeaders: {} + +heartbeat: + enable: false + delay: 1000 + period: 15000 + destinations: [] + extraBody: {} + + extraHeaders: {} diff --git a/mcl-1.1.0-beta.1/data/net.mamoe.mirai-api-http/images/.gitkeep b/mcl-1.1.0-beta.1/data/net.mamoe.mirai-api-http/images/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/mcl-1.1.0-beta.1/data/net.mamoe.mirai-api-http/voices/.gitkeep b/mcl-1.1.0-beta.1/data/net.mamoe.mirai-api-http/voices/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/mcl-1.1.0-beta.1/device.json b/mcl-1.1.0-beta.1/device.json new file mode 100644 index 0000000..81be909 --- /dev/null +++ b/mcl-1.1.0-beta.1/device.json @@ -0,0 +1,354 @@ +{ + "display": [ + 77, + 73, + 82, + 65, + 73, + 46, + 54, + 54, + 49, + 48, + 54, + 49, + 46, + 48, + 48, + 49 + ], + "product": [ + 109, + 105, + 114, + 97, + 105 + ], + "device": [ + 109, + 105, + 114, + 97, + 105 + ], + "board": [ + 109, + 105, + 114, + 97, + 105 + ], + "brand": [ + 109, + 97, + 109, + 111, + 101 + ], + "model": [ + 109, + 105, + 114, + 97, + 105 + ], + "bootloader": [ + 117, + 110, + 107, + 110, + 111, + 119, + 110 + ], + "fingerprint": [ + 109, + 97, + 109, + 111, + 101, + 47, + 109, + 105, + 114, + 97, + 105, + 47, + 109, + 105, + 114, + 97, + 105, + 58, + 49, + 48, + 47, + 77, + 73, + 82, + 65, + 73, + 46, + 50, + 48, + 48, + 49, + 50, + 50, + 46, + 48, + 48, + 49, + 47, + 54, + 56, + 50, + 54, + 55, + 57, + 54, + 58, + 117, + 115, + 101, + 114, + 47, + 114, + 101, + 108, + 101, + 97, + 115, + 101, + 45, + 107, + 101, + 121, + 115 + ], + "bootId": [ + 69, + 65, + 51, + 69, + 52, + 51, + 49, + 50, + 45, + 68, + 55, + 48, + 48, + 45, + 48, + 50, + 56, + 48, + 45, + 53, + 65, + 49, + 55, + 45, + 66, + 48, + 67, + 56, + 70, + 51, + 66, + 55, + 52, + 69, + 70, + 51 + ], + "procVersion": [ + 76, + 105, + 110, + 117, + 120, + 32, + 118, + 101, + 114, + 115, + 105, + 111, + 110, + 32, + 51, + 46, + 48, + 46, + 51, + 49, + 45, + 76, + 68, + 111, + 56, + 54, + 87, + 49, + 53, + 32, + 40, + 97, + 110, + 100, + 114, + 111, + 105, + 100, + 45, + 98, + 117, + 105, + 108, + 100, + 64, + 120, + 120, + 120, + 46, + 120, + 120, + 120, + 46, + 120, + 120, + 120, + 46, + 120, + 120, + 120, + 46, + 99, + 111, + 109, + 41 + ], + "baseBand": [ + ], + "version": { + "incremental": [ + 53, + 56, + 57, + 49, + 57, + 51, + 56 + ], + "release": [ + 49, + 48 + ], + "codename": [ + 82, + 69, + 76 + ] + }, + "simInfo": [ + 84, + 45, + 77, + 111, + 98, + 105, + 108, + 101 + ], + "osType": [ + 97, + 110, + 100, + 114, + 111, + 105, + 100 + ], + "macAddress": [ + 48, + 50, + 58, + 48, + 48, + 58, + 48, + 48, + 58, + 48, + 48, + 58, + 48, + 48, + 58, + 48, + 48 + ], + "wifiBSSID": [ + 48, + 50, + 58, + 48, + 48, + 58, + 48, + 48, + 58, + 48, + 48, + 58, + 48, + 48, + 58, + 48, + 48 + ], + "wifiSSID": [ + 60, + 117, + 110, + 107, + 110, + 111, + 119, + 110, + 32, + 115, + 115, + 105, + 100, + 62 + ], + "imsiMd5": [ + 60, + 39, + -81, + -127, + -112, + -13, + -31, + 21, + -82, + -107, + 31, + -109, + -111, + 41, + -80, + 72 + ], + "imei": "434330071354167", + "apn": [ + 119, + 105, + 102, + 105 + ] +} \ No newline at end of file diff --git a/mcl-1.1.0-beta.1/libs/.gitkeep b/mcl-1.1.0-beta.1/libs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/mcl-1.1.0-beta.1/mcl b/mcl-1.1.0-beta.1/mcl new file mode 100644 index 0000000..af9842e --- /dev/null +++ b/mcl-1.1.0-beta.1/mcl @@ -0,0 +1,3 @@ +#!/usr/bin/env sh +export JAVA_BINARY=java +$JAVA_BINARY -jar mcl.jar $* diff --git a/mcl-1.1.0-beta.1/mcl.cmd b/mcl-1.1.0-beta.1/mcl.cmd new file mode 100644 index 0000000..149da3a --- /dev/null +++ b/mcl-1.1.0-beta.1/mcl.cmd @@ -0,0 +1,3 @@ +@echo off +set JAVA_BINARY=java +%JAVA_BINARY% -jar mcl.jar %* diff --git a/mcl-1.1.0-beta.1/mcl.jar b/mcl-1.1.0-beta.1/mcl.jar new file mode 100644 index 0000000..c0caf7c Binary files /dev/null and b/mcl-1.1.0-beta.1/mcl.jar differ diff --git a/mcl-1.1.0-beta.1/plugins/.gitkeep b/mcl-1.1.0-beta.1/plugins/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/mcl-1.1.0-beta.1/scripts/README.md b/mcl-1.1.0-beta.1/scripts/README.md new file mode 100644 index 0000000..a75dd8b --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/README.md @@ -0,0 +1,87 @@ +# 官方提供的脚本 + +* `config.js` - 通过命令行传入配置 +* `updater.js` - 用于校验和下载`mirai`文件 +* `boot.js` - 用于启动`mirai console` +* `repo.js` - 用于获取`mirai repo`仓库中的信息 + +## 使用样例 + +* 修改某个包的更新频道 + +`.\mcl --update-package 包名 --channel 频道名` + +* 安装 `Mirai Native` + +`.\mcl --update-package org.itxtech:mirai-native --type plugin --channel stable` + +* 安装 `Chat Command` + +`.\mcl --update-package net.mamoe:chat-command --type plugin --channel stable` + +* 指定 `mirai-console` 版本(指定的版本必须为该`Channel`中存在的版本) + +`.\mcl --update-package net.mamoe:mirai-console --channel stable --version 1.0.0` + +* 忽略版本更新 + +`.\mcl -u` + +* 禁用`updater`脚本 + +`.\mcl --disable-script updater` + +* 启用 `updater` 脚本 + +`.\mcl --enable-script updater` + +* 更新运行库但不启动 + +`.\mcl --dry-run` + +* 查看帮助 + +``` +PS > .\mcl -h + +usage: mcl + -a,--update-package Add or update package + -b,--show-boot-props Show Mirai Console boot properties + -c,--log-level Set log level + -d,--disable-script Disable script (exclude ".js") + -e,--enable-script Enable script (exclude ".js") + -f,--set-boot-entry Set Mirai Console boot entry + -g,--set-boot-args Set Mirai Console boot arguments + -i,--package-info Fetch info for specified package + -j,--list-repo-packages List available packages in Mirai Repo + -l,--list-disabled-scripts List disabled scripts + -m,--set-mirai-repo
Set Mirai Repo address + -n,--channel Set update channel of package + -o,--show-repos Show Mirai Repo and Maven Repo + -p,--proxy
Set HTTP proxy + -r,--remove-package Remove package + -s,--list-packages List configured packages + -t,--type Set type of package + -u,--disable-update Disable auto update + -v,--set-maven-repo
Set Maven Repo address + -w,--version Set version of package + -x,--force-version Force download specified version + -z,--dry-run Skip boot phase +``` + +## 开源许可证 + + Copyright (C) 2020-2021 iTX Technologies + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . diff --git a/mcl-1.1.0-beta.1/scripts/announcement.js b/mcl-1.1.0-beta.1/scripts/announcement.js new file mode 100644 index 0000000..80d19e7 --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/announcement.js @@ -0,0 +1,34 @@ +/* + * + * Mirai Console Loader + * + * Copyright (C) 2020-2021 iTX Technologies + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * @author PeratX + * @website https://github.com/iTXTech/mirai-console-loader + * + */ + +phase.load = () => { + logger.info("Fetching Mirai Console Loader Announcement..."); + try { + let pkg = loader.repo.fetchPackage("org.itxtech:mcl"); + logger.info("Mirai Console Loader Announcement:"); + logger.println(pkg.announcement); + } catch (e) { + logger.error("Failed to fetch announcement."); + } +} diff --git a/mcl-1.1.0-beta.1/scripts/boot.js b/mcl-1.1.0-beta.1/scripts/boot.js new file mode 100644 index 0000000..5c9ae77 --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/boot.js @@ -0,0 +1,98 @@ +/* + * + * Mirai Console Loader + * + * Copyright (C) 2020-2021 iTX Technologies + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * @author PeratX + * @website https://github.com/iTXTech/mirai-console-loader + * + */ + +importPackage(java.io); +importPackage(java.lang); +importPackage(java.util); +importPackage(org.itxtech.mcl); +importPackage(org.itxtech.mcl.component); +importPackage(org.apache.commons.cli); + +loader.options.addOption(Option.builder("b").desc("Show Mirai Console boot properties") + .longOpt("show-boot-props").build()); +loader.options.addOption(Option.builder("f").desc("Set Mirai Console boot entry") + .longOpt("set-boot-entry").hasArg().argName("EntryClass").build()); +loader.options.addOption(Option.builder("g").desc("Set Mirai Console boot arguments") + .longOpt("set-boot-args").optionalArg(true).hasArg().argName("Arguments").build()); + +phase.cli = () => { + if (loader.cli.hasOption("f")) { + loader.config.scriptProps.put("boot.entry", loader.cli.getOptionValue("f")); + loader.saveConfig(); + } + if (loader.cli.hasOption("g")) { + loader.config.scriptProps.put("boot.args", loader.cli.getOptionValue("g", "")); + loader.saveConfig(); + } + if (loader.cli.hasOption("b")) { + logger.info("Mirai Console boot entry: " + getBootEntry()); + logger.info("Mirai Console boot arguments: " + getBootArgs()); + System.exit(0); + } +} + +function getBootEntry() { + return loader.config.scriptProps.getOrDefault("boot.entry", "net.mamoe.mirai.console.terminal.MiraiConsoleTerminalLoader"); +} + +function getBootArgs() { + return loader.config.scriptProps.getOrDefault("boot.args", ""); +} + +let depMap = new HashMap(); +depMap.put("net.mamoe:mirai-core", "net.mamoe:mirai-core-all"); + +phase.boot = () => { + let files = []; + let pkgs = loader.config.packages; + let pkgMap = new HashMap(); + for (let i in pkgs) { + let pkg = pkgs[i]; + if (pkg.type.equals(Config.Package.TYPE_CORE)) { + files.push(new File(new File(pkg.type), pkg.getBasename() + ".jar")); + pkgMap.put(pkg.id, pkg.version); + } + if (pkg.type.equals(Config.Package.TYPE_PLUGIN)) { + let file = new File(new File(pkg.type), pkg.getBasename() + ".metadata"); + if (file.exists()) { + let deps = loader.repo.getMetadataFromFile(file).dependencies.iterator(); + while (deps.hasNext()) { + let dep = deps.next().split(":"); + let name = dep[0] + ":" + dep[1]; + let version = dep[2]; + let realPkg = depMap.getOrDefault(name, name); + let it = pkgMap.entrySet().iterator(); + while (it.hasNext()) { + let corePkg = it.next(); + if (corePkg.getKey().equals(realPkg) && !corePkg.getValue().equals(version)) { + logger.warning("Package \"" + pkg.id + "\" requires \"" + name + "\" version " + version + ". Current version is " + corePkg.getValue()); + } + } + } + } + } + } + + Utility.bootMirai(files, getBootEntry(), getBootArgs()); +} diff --git a/mcl-1.1.0-beta.1/scripts/config.js b/mcl-1.1.0-beta.1/scripts/config.js new file mode 100644 index 0000000..883bd84 --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/config.js @@ -0,0 +1,132 @@ +/* + * + * Mirai Console Loader + * + * Copyright (C) 2020-2021 iTX Technologies + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * @author PeratX + * @website https://github.com/iTXTech/mirai-console-loader + * + */ + +importPackage(java.net); +importPackage(java.lang); +importPackage(org.itxtech.mcl.component); +importPackage(org.apache.commons.cli); + +loader.options.addOption(Option.builder("p").desc("Set HTTP proxy") + .longOpt("proxy").optionalArg(true).hasArg().argName("address").build()); +loader.options.addOption(Option.builder("o").desc("Show Mirai Repo and Maven Repo") + .longOpt("show-repos").build()); +loader.options.addOption(Option.builder("m").desc("Set Mirai Repo address") + .longOpt("set-mirai-repo").hasArg().argName("Address").build()); +loader.options.addOption(Option.builder("v").desc("Set Maven Repo address") + .longOpt("set-maven-repo").hasArg().argName("Address").build()); +loader.options.addOption(Option.builder("c").desc("Set log level") + .longOpt("log-level").hasArg().argName("level").build()); +let group = new OptionGroup(); +group.addOption(Option.builder("s").desc("List configured packages") + .longOpt("list-packages").build()); +group.addOption(Option.builder("r").desc("Remove package") + .longOpt("remove-package").hasArg().argName("PackageName").build()); +group.addOption(Option.builder("a").desc("Add or update package") + .longOpt("update-package").hasArg().argName("PackageName").build()); +loader.options.addOptionGroup(group); +loader.options.addOption(Option.builder("n").desc("Set update channel of package") + .longOpt("channel").hasArg().argName("Channel").build()); +loader.options.addOption(Option.builder("t").desc("Set type of package") + .longOpt("type").hasArg().argName("Type").build()); +loader.options.addOption(Option.builder("w").desc("Set version of package") + .longOpt("version").hasArg().argName("Version").build()); + +phase.cli = () => { + if (loader.cli.hasOption("p")) { + loader.config.proxy = loader.cli.getOptionValue("p", ""); + loader.saveConfig(); + } + if (loader.cli.hasOption("o")) { + logger.info("Mirai Repo: " + loader.config.miraiRepo); + logger.info("Maven Repo: " + loader.config.mavenRepo); + System.exit(0); + } + if (loader.cli.hasOption("m")) { + loader.config.miraiRepo = loader.cli.getOptionValue("m"); + loader.saveConfig(); + } + if (loader.cli.hasOption("v")) { + loader.config.mavenRepo = loader.cli.getOptionValue("v"); + loader.saveConfig(); + } + if (loader.cli.hasOption("c")) { + let lvl = Integer.parseInt(loader.cli.getOptionValue("c")); + logger.setLogLevel(lvl); + loader.config.logLevel = lvl; + } + if (loader.cli.hasOption("s")) { + let pkgs = loader.config.packages; + for (let i in pkgs) { + let pkg = pkgs[i]; + logger.info("Package: " + pkg.id + " Channel: " + pkg.channel + " Type: " + pkg.type + " Version: " + pkg.version); + } + System.exit(0); + } + if (loader.cli.hasOption("r")) { + let name = loader.cli.getOptionValue("r"); + let pkgs = loader.config.packages; + for (let i in pkgs) { + let pkg = pkgs[i]; + if (pkg.id.equals(name)) { + pkgs.remove(pkg); + logger.info("Package \"" + pkg.id + "\" has been removed."); + loader.saveConfig(); + System.exit(0); + } + } + logger.error("Package \"" + name + "\" not found."); + System.exit(1); + } + if (loader.cli.hasOption("a")) { + let name = loader.cli.getOptionValue("a"); + let pkgs = loader.config.packages; + for (let i in pkgs) { + let pkg = pkgs[i]; + if (pkg.id.equals(name)) { + updatePackage(pkg) + logger.info("Package \"" + pkg.id + "\" has been updated."); + loader.saveConfig(); + System.exit(0); + } + } + let pkg = new Config.Package(name, "stable"); + updatePackage(pkg); + pkgs.add(pkg); + logger.info("Package \"" + pkg.id + "\" has been added."); + loader.saveConfig(); + System.exit(0); + } +} + +function updatePackage(pkg) { + if (loader.cli.hasOption("n")) { + pkg.channel = loader.cli.getOptionValue("n"); + } + if (loader.cli.hasOption("t")) { + pkg.type = Config.Package.getType(loader.cli.getOptionValue("t")); + } + if (loader.cli.hasOption("w")) { + pkg.version = loader.cli.getOptionValue("w"); + } +} diff --git a/mcl-1.1.0-beta.1/scripts/oraclejdk.js b/mcl-1.1.0-beta.1/scripts/oraclejdk.js new file mode 100644 index 0000000..cc9796b --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/oraclejdk.js @@ -0,0 +1,44 @@ +/* + * + * Mirai Console Loader + * + * Copyright (C) 2020-2021 iTX Technologies + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * @author PeratX + * @website https://github.com/iTXTech/mirai-console-loader + * + */ + +importPackage(java.lang); +importPackage(org.itxtech.mcl.component); + +if (System.getProperty("java.vm.vendor").contains("Oracle")) { + let found = false; + let pkgs = loader.config.packages; + for (let i in pkgs) { + let pkg = pkgs[i]; + if (pkg.id.equals("org.bouncycastle:bcprov-jdk15on")) { + found = true; + break; + } + } + if (!found) { + let p = new Config.Package("org.bouncycastle:bcprov-jdk15on", "stable"); + p.type = Config.Package.TYPE_CORE; + loader.config.packages.add(0, p); + logger.info("OracleJDK is detected. MCL will download BouncyCastle automatically."); + } +} diff --git a/mcl-1.1.0-beta.1/scripts/repo.js b/mcl-1.1.0-beta.1/scripts/repo.js new file mode 100644 index 0000000..795f5ff --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/repo.js @@ -0,0 +1,67 @@ +/* + * + * Mirai Console Loader + * + * Copyright (C) 2020-2021 iTX Technologies + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * @author PeratX + * @website https://github.com/iTXTech/mirai-console-loader + * + */ + +importPackage(java.lang); +importPackage(org.itxtech.mcl); +importPackage(org.itxtech.mcl.component); +importPackage(org.apache.commons.cli); + +let group = new OptionGroup(); +group.addOption(Option.builder("i").desc("Fetch info for specified package") + .longOpt("package-info").hasArg().argName("PackageName").build()); +group.addOption(Option.builder("j").desc("List available packages in Mirai Repo") + .longOpt("list-repo-packages").build()); +loader.options.addOptionGroup(group); + +phase.cli = () => { + let repo = new Repository(loader); + if (loader.cli.hasOption("j")) { + logger.info("Fetching packages from " + loader.config.miraiRepo); + let pkgs = repo.fetchPackages().entrySet().iterator(); + while (pkgs.hasNext()) { + let pkg = pkgs.next(); + let info = pkg.getValue(); + logger.info("---------- Package: " + pkg.getKey() + " ----------"); + logger.info("Name: " + info.name); + logger.info("Description: " + info.description); + logger.info("Website: " + info.website); + logger.info("Channels: " + Utility.join(", ", info.channels)); + logger.info(""); + } + System.exit(0); + } + + if (loader.cli.hasOption("i")) { + let pkg = loader.cli.getOptionValue("i"); + logger.info("Fetching channel info for package \"" + pkg + "\""); + let info = repo.fetchPackage(pkg).channels.entrySet().iterator(); + while (info.hasNext()) { + let chan = info.next(); + logger.info("---------- Channel: " + chan.getKey() + " ----------"); + logger.info("Version: " + Utility.join(", ", chan.getValue())); + logger.info(""); + } + System.exit(0); + } +} diff --git a/mcl-1.1.0-beta.1/scripts/updater.js b/mcl-1.1.0-beta.1/scripts/updater.js new file mode 100644 index 0000000..f880f01 --- /dev/null +++ b/mcl-1.1.0-beta.1/scripts/updater.js @@ -0,0 +1,132 @@ +/* + * + * Mirai Console Loader + * + * Copyright (C) 2020-2021 iTX Technologies + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * @author PeratX + * @website https://github.com/iTXTech/mirai-console-loader + * + */ + +importPackage(java.io); +importPackage(java.lang); +importPackage(java.math); +importPackage(org.itxtech.mcl); +importPackage(org.itxtech.mcl.component); +importPackage(org.apache.commons.cli); + +loader.options.addOption(Option.builder("u").desc("Disable auto update").longOpt("disable-update").build()); +loader.options.addOption(Option.builder("x").desc("Force download specified version").longOpt("force-version").build()); + +phase.load = () => { + let packages = loader.config.packages; + for (let i in packages) { + check(packages[i]); + } +}; + +function check(pack) { + logger.info("Verifying \"" + pack.id + "\" version " + pack.version); + let update = loader.cli.hasOption("u"); + let force = loader.cli.hasOption("x"); + let down = false; + if (!Utility.checkLocalFile(pack)) { + logger.info("\"" + pack.id + ":" + pack.version + "\" is corrupted. Start downloading..."); + down = true; + } + let info = loader.repo.fetchPackage(pack.id); + if (!info.channels.containsKey(pack.channel)) { + logger.error("Invalid update channel \"" + pack.channel + "\" for Package \"" + pack.name + "\""); + } else { + let target = info.channels[pack.channel]; + let ver = target[target.size() - 1]; + if ((!update && !pack.version.equals(ver)) || (update && !target.contains(pack.version) && !force)) { + if (pack.type.equals(Config.Package.TYPE_PLUGIN)) { + let dir = new File(pack.type); + pack.getJarFile().renameTo(new File(dir, pack.getBasename() + ".jar.bak")); + } + pack.version = ver; + down = true; + } + if (down) { + downloadFile(pack, info); + if (!Utility.checkLocalFile(pack)) { + logger.warning("The local file \"" + pack.id + "\" is still corrupted, please check the network."); + } + } + } +} + +function downloadFile(pack, info) { + let dir = new File(pack.type); + dir.mkdirs(); + let ver = pack.version; + let jarUrl = loader.repo.getJarUrl(pack, info); + if (!jarUrl.equals("")) { + down(jarUrl, new File(dir, pack.getName() + "-" + ver + ".jar")); + down(jarUrl + ".sha1", new File(dir, pack.getName() + "-" + ver + ".sha1")); + let metadata = loader.repo.getMetadataUrl(pack, info); + if (!metadata.equals("")) { + down(metadata, new File(dir, pack.getName() + "-" + ver + ".metadata")); + } + } else { + logger.error("Cannot download package \"" + pack.id + "\"."); + } +} + +let emptyString = (function () { + let buffer = "", counter = 1024; + while (counter-- > 0) buffer += ' '; + return buffer +})() + +function alignRight(current, total) { + let max = Math.max(current.length, total.length); + return emptyString.substring(0, max - current.length) + current; +} + +function buildDownloadBar(total, current) { + let length = 30; + let bar = Math.floor((current / total) * length); + let buffer = "["; + for (let i = 0; i < bar; i++) { + buffer += '='; + } + if (bar < length) { + buffer += '>'; + for (let i = bar; i < length; i++) { + buffer += ' '; + } + } + return buffer + "]"; +} + +function down(url, file) { + let name = file.name; + var size = 0; + let ttl = ""; + loader.downloader.download(url, file, (total, current) => { + ttl = Utility.humanReadableFileSize(total); + var cur = Utility.humanReadableFileSize(current); + + let line = " Downloading " + name + " " + buildDownloadBar(total, current) + " " + (alignRight(cur, ttl) + " / " + ttl) + " (" + (Math.floor(current * 1000 / total) / 10) + "%)" + " \r"; + logger.print(line); + size = line.length + }); + logger.print(emptyString.substr(0, size) + '\r'); + logger.println(" Downloading " + name + " " + buildDownloadBar(1, 1) + " " + ttl); +} diff --git a/package.json b/package.json index e6888de..1a15fec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "discord-qq-bridge", - "version": "1.5.2", + "version": "1.5.0", "description": "", "main": "index.js", "scripts": { @@ -42,10 +42,13 @@ "@nestjs/core": "^7.6.13", "@nestjs/platform-express": "^7.6.13", "@nestjs/typeorm": "^7.1.5", + "@octokit/webhooks": "^9.4.0", + "@octokit/webhooks-definitions": "^3.67.3", "axios": "^0.21.0", "canvas": "^2.6.1", "dayjs": "^1.9.6", "discord.js": "^12.5.3", + "el-bot": "^0.8.0-beta.5", "fast-xml-parser": "^3.17.6", "file-type": "^16.0.1", "got": "^11.8.1", diff --git a/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.module.ts b/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.module.ts index 30ddcb5..484f286 100644 --- a/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.module.ts +++ b/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.module.ts @@ -1,5 +1,12 @@ import { NgModule } from '@angular/core'; -import { NbCardModule, NbIconModule, NbInputModule, NbSelectModule } from '@nebular/theme'; +import { + NbAlertModule, + NbButtonModule, + NbCardModule, + NbIconModule, + NbInputModule, + NbSelectModule +} from '@nebular/theme'; import { Ng2SmartTableModule } from 'ng2-smart-table'; import { ThemeModule } from '../../@theme/theme.module'; @@ -9,9 +16,15 @@ import { UserSelectRenderComponent } from './user-select-render.component'; import { TableSelectComponent } from './user-select.component'; import { TableEditorNoneComponent } from './table-editor-none.component'; import { GuildSelectRenderComponent } from './guild-select-render.component'; +import { ConfigComponent } from './config.component'; +import { TableEditorInputComponent } from './table-editor-input.component'; +import { FormsModule } from '@angular/forms'; +import { CommonModule } from '@angular/common'; @NgModule({ imports: [ + FormsModule, + CommonModule, NbCardModule, ThemeModule, Ng2SmartTableModule, @@ -19,14 +32,18 @@ import { GuildSelectRenderComponent } from './guild-select-render.component'; NbIconModule, NbInputModule, NbSelectModule, + NbButtonModule, + NbAlertModule, ], declarations: [ AdminComponent, + ConfigComponent, SelectRenderComponent, UserSelectRenderComponent, GuildSelectRenderComponent, TableSelectComponent, TableEditorNoneComponent, + TableEditorInputComponent, ], }) export class AdminModule { } diff --git a/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.service.ts b/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.service.ts index 0161db1..88d5480 100644 --- a/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.service.ts +++ b/projects/ngx-admin-starter-kit/src/app/pages/admin/admin.service.ts @@ -3,6 +3,31 @@ import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Observable, of } from 'rxjs'; + +export interface BridgeConfig { + discord: { + id: string, + token: string, + channelID: string, + }, + qqGroup: number +} +export interface Config { + qqBot: number, + setting: { + host: string, + port: number, + authKey: string, + enableWebsocket: boolean, + }, + discordBot: string; + discordBotToken: string; + bridges: BridgeConfig[]; + autoApproveQQGroup: Array<{qqGroup: number, reg: string}> + proxy: string; +} + + export interface Channel { id: string; name: string; @@ -40,6 +65,18 @@ export class AdminService { constructor(public http: HttpClient) { } + getConfig(): Observable { + return this.http.get<{ data: Config }>('/api/bridge/config').pipe(map((result) => { + return result.data + })); + } + + setConfig(config: Config): Observable { + return this.http.post<{ data: Config }>('/api/bridge/config', config).pipe(map((result) => { + return result.data + })); + } + getGuilds(): Observable { if (this.guilds.length) { return of(this.guilds) @@ -58,7 +95,6 @@ export class AdminService { } - getGuildAllUsers(guild: string): Observable { return this.http.get<{ data: Array }>(`/api/bridge/guilds/${guild}/users`).pipe(map((result) => { this.users = result.data; diff --git a/projects/ngx-admin-starter-kit/src/app/pages/admin/config.component.html b/projects/ngx-admin-starter-kit/src/app/pages/admin/config.component.html new file mode 100644 index 0000000..347964c --- /dev/null +++ b/projects/ngx-admin-starter-kit/src/app/pages/admin/config.component.html @@ -0,0 +1,36 @@ + + + 自动审批同意加群 + + + + + + + + + + + + 正则测试 + + + +
+
+
+ + +
+
+
+
+ + +
+
+
+ {{test.status === 'success' ? '通过' : '不通过' }} +
+
diff --git a/projects/ngx-admin-starter-kit/src/app/pages/admin/config.component.ts b/projects/ngx-admin-starter-kit/src/app/pages/admin/config.component.ts new file mode 100644 index 0000000..184dfe2 --- /dev/null +++ b/projects/ngx-admin-starter-kit/src/app/pages/admin/config.component.ts @@ -0,0 +1,103 @@ +import { Component, OnInit } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { AdminService, Config } from './admin.service'; +import { TableEditorNoneComponent } from './table-editor-none.component'; +import { SelectRenderComponent } from './select-render.component'; +import { TableSelectComponent } from './user-select.component'; +import { UserSelectRenderComponent } from './user-select-render.component'; +import { LocalDataSource } from 'ng2-smart-table'; +import { zip } from 'rxjs'; +import { TableEditorInputComponent } from './table-editor-input.component'; + +@Component({ + selector: 'app-admin', + templateUrl: './config.component.html', + styleUrls: ['./admin.component.less'] +}) +export class ConfigComponent implements OnInit { + test = { + status: 'none', + reg: '', + message: '', + } + + settings = { + add: { + addButtonContent: '', + createButtonContent: '', + cancelButtonContent: '', + confirmCreate: false, + }, + actions: { + edit: true, + position: 'right' + }, + edit: { + editButtonContent: '', + saveButtonContent: '', + cancelButtonContent: '', + }, + delete: { + deleteButtonContent: '', + confirmDelete: false, + }, + columns: { + qqGroup: { + title: 'qq群', + filter: false, + editor: { + type: 'custom', + component: TableEditorInputComponent, + config: {}, + } + }, + reg: { + title: '正则', + filter: false, + editor: { + type: 'custom', + component: TableEditorInputComponent, + config: {}, + } + }, + }, + }; + source: LocalDataSource = new LocalDataSource(); + config: Config; + + constructor(public http: HttpClient, public adminService: AdminService) { + this.adminService.getConfig().subscribe((config) => { + this.config = config; + this.source.load(this.config.autoApproveQQGroup); + }); + } + + ngOnInit(): void { + } + + async onButtonClickSave(): Promise { + const data: Array<{ qqGroup: string, reg: string }> = await this.source.getAll(); + this.config.autoApproveQQGroup = data.map((d) => { + return { + qqGroup: parseInt(d.qqGroup), + reg: d.reg + } + }); + this.adminService.setConfig(this.config).subscribe((config)=>{ + this.config = config; + this.source.load(this.config.autoApproveQQGroup); + }) + } + + onChangeTest() { + if (this.test.reg.trim() && this.test.message.trim()) { + if (new RegExp(this.test.reg).test(this.test.message)) { + this.test.status = 'success' + } else { + this.test.status = 'danger' + } + } else { + this.test.status = 'none'; + } + } +} diff --git a/projects/ngx-admin-starter-kit/src/app/pages/admin/table-editor-input.component.ts b/projects/ngx-admin-starter-kit/src/app/pages/admin/table-editor-input.component.ts new file mode 100644 index 0000000..ff9e091 --- /dev/null +++ b/projects/ngx-admin-starter-kit/src/app/pages/admin/table-editor-input.component.ts @@ -0,0 +1,29 @@ +import { Component, ViewChild, ElementRef, AfterViewInit, OnInit } from '@angular/core'; +import { DefaultEditor } from 'ng2-smart-table'; +import { AdminService } from './admin.service'; + +@Component({ + template: ` + + `, +}) +export class TableEditorInputComponent extends DefaultEditor implements AfterViewInit, OnInit { + options: Array<{ title: string, value: string }> + value: string; + + constructor() { + super(); + } + + ngOnInit() { + this.value = this.cell.getValue(); + } + + ngAfterViewInit() { + } + + onInputValueChange($event) { + this.cell.newValue = $event; + } + +} diff --git a/projects/ngx-admin-starter-kit/src/app/pages/pages-menu.ts b/projects/ngx-admin-starter-kit/src/app/pages/pages-menu.ts index a3e3024..7d0fae2 100644 --- a/projects/ngx-admin-starter-kit/src/app/pages/pages-menu.ts +++ b/projects/ngx-admin-starter-kit/src/app/pages/pages-menu.ts @@ -7,6 +7,12 @@ export const MENU_ITEMS: NbMenuItem[] = [ link: '/pages/dashboard', home: true, }, + { + title: 'QQ群自动同意审批', + icon: 'home-outline', + link: '/pages/config', + home: true, + }, { title: '桥同步设置', icon: 'home-outline', diff --git a/projects/ngx-admin-starter-kit/src/app/pages/pages-routing.module.ts b/projects/ngx-admin-starter-kit/src/app/pages/pages-routing.module.ts index fbf81d1..516351a 100644 --- a/projects/ngx-admin-starter-kit/src/app/pages/pages-routing.module.ts +++ b/projects/ngx-admin-starter-kit/src/app/pages/pages-routing.module.ts @@ -4,6 +4,7 @@ import { NgModule } from '@angular/core'; import { PagesComponent } from './pages.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { AdminComponent } from './admin/admin.component'; +import { ConfigComponent } from './admin/config.component'; const routes: Routes = [{ path: '', @@ -13,6 +14,10 @@ const routes: Routes = [{ path: 'dashboard', component: DashboardComponent, }, + { + path: 'config', + component: ConfigComponent, + }, { path: 'admin', component: AdminComponent, diff --git a/src/bridge-discord-to-qq.el.ts b/src/bridge-discord-to-qq.el.ts new file mode 100644 index 0000000..3c6622c --- /dev/null +++ b/src/bridge-discord-to-qq.el.ts @@ -0,0 +1,246 @@ +import { Message as DiscordMessage, Message } from "discord.js"; +import { Message as MiraiMessage, MessageType } from 'mirai-ts'; +import { CQCode } from 'koishi'; +import config from "./config"; +import * as path from "path"; +import * as fs from "fs"; +import * as log from "./utils/log5"; +import { BridgeConfig } from "./interface"; +import { DatabaseService } from "./database.service"; +import { MessageEntity } from "./entity/message.entity"; +import { createCanvas, loadImage } from "canvas"; +import { downloadDiscordAttachment, downloadImage, imageDiscordAvatarCacheDir } from "./utils/download-file"; +import { BotService } from "./el-bot/bot.service"; + +export default async function () { + BotService.discord.on('message', async (msg) => { + if (msg.content === '!ping') { + msg.channel.send('Pong.'); + } + await toQQ(msg); + }); +} + +// 转发到qq +export async function toQQ(msg: Message) { + // 无视自己的消息 + if (msg.author.id === config.discordBot || (config.bridges.find(opt => opt.discord.id === msg.author.id))) { + return; + } + // 查询这个频道是否需要通知到群 + const bridge: BridgeConfig = config.bridges.find((opt) => opt.discord.channelID === msg.channel.id); + if (!bridge) { + return; + } + try { + let quote = undefined; + const msgChain: MessageType.MessageChain = []; + const temps: any[] = []; + + // 处理回复 + if (msg.reference && msg.reference.messageID) { + const messageRepo = DatabaseService.connection.getRepository(MessageEntity); + const refMsg = await messageRepo.findOne({discordMessageID: msg.reference.messageID}); + // 尝试查找discord对应的qq消息id + if (refMsg) { + quote = refMsg.qqMessageID; + } else { + // 找不到就证明是旧的消息或者某些原因找不到, 那就纯文本当回复吧 + const channel: any = await BotService.discord.channels.fetch(msg.channel.id); + const replyMsg = await channel.messages.fetch(msg.reference.messageID); + msgChain.push(MiraiMessage.Plain(`回复消息:${replyMsg.content}\n`)) + } + } + + // 添加用户名称在信息前面 + const avatar = await handlerUserAvatar(msg) + if (avatar) { + msgChain.push(avatar); + } + msgChain.push(MiraiMessage.Plain(`@${msg.author.username}#${msg.author.discriminator}\n`)); + + // 没有内容时不处理 + if (msg.content.trim()) { + let messageContent = msg.content; + // 处理回复 + messageContent = await parseEmoji(messageContent); + // 处理@ + messageContent = await handlerAt(messageContent, {msg: msg, bridge: bridge}); + messageContent = await handlerAtQQUser(messageContent, {msg: msg, bridge: bridge}); + + const cqMsg = CQCode.parseAll(messageContent); + for (let source of cqMsg) { + if (typeof source === "string") { + msgChain.push(MiraiMessage.Plain(source)) + } else { + switch (source.type) { + case 'at': + msgChain.push(MiraiMessage.At(source.data.qq as any)) + break; + case 'image': + const filePath = await downloadDiscordAttachment({url: source.data.file}); + const relativePath = path.relative(path.join(__dirname, '../mcl/data/net.mamoe.mirai-api-http/images'), filePath); + msgChain.push(MiraiMessage.Image(null, null, relativePath.replace(/\\/g, '/'))) + break; + default: + msgChain.push(MiraiMessage.Plain(JSON.stringify(source))) + } + } + } + } + if (msg.attachments.size > 0) { + const attachments = msg.attachments.array(); + for (let attachment of attachments) { + const filePath = await downloadDiscordAttachment({url: attachment.url}); + const relativePath = path.relative(path.join(__dirname, '../mcl/data/net.mamoe.mirai-api-http/images'), filePath); + msgChain.push(MiraiMessage.Image(null, null, relativePath.replace(/\\/g, '/'))) + } + } + const res = await BotService.qqBot.mirai.api.sendGroupMessage(msgChain, bridge.qqGroup, quote); + const resMessage = await BotService.qqBot.mirai.api.messageFromId(res.messageId); + handlerSaveMessage(resMessage as MessageType.GroupMessage, msg).then(); + log.message('⇿', 'Discord消息已推送到QQ', msg.author.username + '#' + msg.author.discriminator, msg.content) + } catch (error) { + log.error(error); + const res = await BotService.qqBot.mirai.api.sendGroupMessage(`程序出错消息格式化失败 来自${msg.author.username} \n${msg.content}`, bridge.qqGroup); + const resMessage = await BotService.qqBot.mirai.api.messageFromId(res.messageId); + handlerSaveMessage(resMessage as MessageType.GroupMessage, msg).then(); + } +} + +export async function translateCQCodeToMsgChain(cqMsg: string): Promise { + const chain: MessageType.MessageChain = []; + CQCode.parseAll(cqMsg).forEach((source) => { + if (typeof source === "string") { + chain.push(MiraiMessage.Plain(source)) + } else { + switch (source.type) { + } + } + + }) + return chain; +} + +// 把表情解析成cq:image +export async function parseEmoji(message: string): Promise { + let content = message; + // discord的表情图 + const res = message.match(/<:(\w+):(\d+)>/g); + if (res && res.length > 0) { + for (const emojiBlock of res) { + const emojiMatch = emojiBlock.match(/^<:(\w+):(\d+)>/); + if (emojiMatch[2]) { + content = content.replace(emojiBlock, CQCode.stringify('image', {file: `https://cdn.discordapp.com/emojis/${emojiMatch[2]}.png`})); + } + } + } + + // discord的gif图 + const gifMatches = content.match(/https:\/\/tenor\.com\/view\/([\w]+-)+[0-9]+/g); + if (gifMatches && gifMatches.length > 0) { + for (const gifUrl of gifMatches) { + content = content.replace(gifUrl, CQCode.stringify('image', {file: `${gifUrl}.gif`})); + } + } + return content; +} + +// 处理头部消息 +export async function handlerUserAvatar(msg: Message): Promise { + if (!msg.author.avatar) { + return undefined; + } + const filePath = await downloadImage({url: msg.author.avatarURL({format: 'png'})}); + const img = await loadImage(filePath); + const canvas = createCanvas(30, 30) + const canvasCtx = canvas.getContext('2d'); + canvasCtx.arc(15, 15, 15, 0, Math.PI * 2, false) + canvasCtx.clip() + canvasCtx.drawImage(img, 0, 0, 30, 30); + // const imgDataUrl = canvas.toDataURL(); + let stream = fs.createWriteStream(path.join(imageDiscordAvatarCacheDir, path.basename(filePath))); + stream.write(canvas.toBuffer()); + stream.close(); + let relativePath = path.relative(path.join(__dirname, '../mcl/data/net.mamoe.mirai-api-http/images'), path.join(imageDiscordAvatarCacheDir, path.basename(filePath))); + return MiraiMessage.Image(null, null, relativePath.replace(/\\/g, '/')) +} + +// 处理回复消息 +export async function handlerReply(message: string, ctx: { msg: Message, bridge: BridgeConfig }): Promise { + if (ctx.msg.reference && ctx.msg.reference.messageID) { + const messageRepo = DatabaseService.connection.getRepository(MessageEntity); + const refMsg = await messageRepo.findOne({discordMessageID: ctx.msg.reference.messageID}); + // 尝试查找discord对应的qq消息id + if (refMsg) { + const replyCQCODE = CQCode.stringify('reply', {id: refMsg.qqMessageID}); + return `${replyCQCODE}${message}` + } else { + // 找不到就证明是旧的消息或者某些原因找不到, 那就纯文本当回复吧 + const channel: any = await BotService.discord.channels.fetch(ctx.msg.channel.id); + const replyMsg = await channel.messages.fetch(ctx.msg.reference.messageID); + return `回复消息:${replyMsg.content}\n${message}` + } + } + return message; +} + +// 处理at消息 +export async function handlerAt(message: string, ctx: { msg: Message, bridge: BridgeConfig }): Promise { + ctx.msg.mentions.users.forEach((user) => { + message = message.replace(`<@${user.id}>`, `@${user.username}#${user.discriminator}`); + message = message.replace(`<@!${user.id}>`, `@${user.username}#${user.discriminator}`); + }); + return message; +} + +// 处理at discord用户 +export async function handlerAtQQUser(message: string, ctx: { msg: Message, bridge: BridgeConfig }): Promise { + const atList: Array<{ username: string, qq?: string, origin: string }> = []; + // 正则匹配 + const m1 = message.match(/\@([^\n]+) (?:\()([0-9]+)\)(\#0000)?/g); + if (m1) { + m1.forEach((m) => { + atList.push({ + origin: m, + username: m.match(/\@([^\n]+) (?:\()([0-9]+)\)(\#0000)?/)[1], + qq: m.match(/\@([^\n]+) (?:\()([0-9]+)\)(\#0000)?/)[2] + }) + }) + } + // 正则匹配 + const m2 = message.match(/\@([^\n]+)(?:\()([0-9]+)\)(\#0000)?/g); + if (m2) { + m2.forEach((m) => { + atList.push({ + origin: m, + username: m.match(/\@([^\n]+)(?:\()([0-9]+)\)(\#0000)?/)[1], + qq: m.match(/\@([^\n]+)(?:\()([0-9]+)\)(\#0000)?/)[2] + }) + }) + } + if (atList.length === 0) { + return message; + } + atList.forEach((at) => { + message = message.replace(at.origin, CQCode.stringify('at', {qq: at.qq})) + }) + return message; +} + +// 保存关联消息 +async function handlerSaveMessage(qqMessage: MessageType.GroupMessage, discordMessage: Message): Promise { + const messageRepo = DatabaseService.connection.getRepository(MessageEntity); + const messageEntity = new MessageEntity(); + messageEntity.from = "qq"; + messageEntity.qqMessageID = qqMessage.messageChain[0].id.toString(); + messageEntity.qqMessage = { + content: JSON.stringify(qqMessage.messageChain), + } + messageEntity.discordMessageID = discordMessage.id; + messageEntity.discordMessage = { + content: discordMessage.content, + attachments: discordMessage.attachments.array() as any, + } + return messageRepo.save(messageEntity); +} diff --git a/src/bridge-discord-to-qq.ts b/src/bridge-discord-to-qq.ts index a099d5b..47ce10d 100644 --- a/src/bridge-discord-to-qq.ts +++ b/src/bridge-discord-to-qq.ts @@ -92,11 +92,6 @@ export async function toQQ(msg: Message) { } } -function resolveEncoding(msg) { - msg = msg.replace(new RegExp('&', 'g'), '&') - return msg -} - // 把表情解析成cq:image export async function parseEmoji(message: string): Promise { let content = message; diff --git a/src/bridge-qq-to-discord.el.ts b/src/bridge-qq-to-discord.el.ts new file mode 100644 index 0000000..343d8a9 --- /dev/null +++ b/src/bridge-qq-to-discord.el.ts @@ -0,0 +1,221 @@ +import config from "./config"; +import { Config as MiraiConfig, MessageType } from "mirai-ts"; +import {Guild, Message, Message as DiscordMessage, MessageAttachment, Webhook, WebhookMessageOptions} from "discord.js"; +import {BotService} from "./el-bot/bot.service"; +import {downloadQQImage} from "./utils/download-file"; +import {MessageEntity} from "./entity/message.entity"; +import {DatabaseService} from "./database.service"; +import * as log from './utils/log5'; +import * as xmlUtil from 'fast-xml-parser'; + +export default async function () { + BotService.qqBot.mirai.on('GroupMessage', async (qqMsg) => { + await toDiscord(qqMsg); + }); +} + +async function toDiscord(qqMsg: MessageType.GroupMessage) { + const bridge = config.bridges.find(b => b.qqGroup === qqMsg.sender.group.id); + if (!bridge) { + return; + } + let resMessage: DiscordMessage; + try { + // 获取webhook + const webhook = await BotService.discord.fetchWebhook(bridge.discord.id, bridge.discord.token); + // 处理消息 + let messageContent = ''; + const option: WebhookMessageOptions = { + username: `${qqMsg.sender.memberName}(${qqMsg.sender.id})`, + avatarURL: `https://q1.qlogo.cn/g?b=qq&nk=${qqMsg.sender.id}&s=100&t=${Math.random()}`, + // avatarURL: `https://q.qlogo.cn/g?b=qq&nk={uid}&s=100&t={Math.random()} + // avatarURL: `http://q.qlogo.cn/headimg_dl?bs=qq&dst_uin=${qqMessage.sender.userId}&src_uin=www.feifeiboke.com&fid=blog&spec=640&t=${Math.random()}` // 高清地址 + files: [], + } + for (const msg of qqMsg.messageChain) { + switch (msg.type) { + case 'Source': + break; + case 'Quote': + messageContent += await handlerForward(msg); + break; + case 'Plain': + messageContent += msg.text; + break; + case 'At': + const memberInfos = await BotService.qqBot.mirai.api.memberList(qqMsg.sender.group.id); + const memberInfo = memberInfos.find(member => member.id === msg.target); + if(memberInfo){ + messageContent += `\`@${memberInfo.memberName}(${msg.target})\``; + } + break; + case 'AtAll': + messageContent += `@everyone`; + break; + case 'Face': + messageContent += `[Face=${msg.faceId},${msg.name}]`; + break; + case 'Image': + const filePath = await downloadQQImage({url: msg.url}); + const attr = new MessageAttachment(filePath); + option.files.push(attr); + break; + case 'Xml': + messageContent += await handlerXml(msg); + break; + case 'App': + const content = JSON.parse(msg.content) as any; + messageContent += `> ** ${content.prompt} **\n` + messageContent += `> ${content.meta.detail_1.desc}\n` + messageContent += `> ${content.meta.detail_1.qqdocurl}\n` + break; + default: + messageContent += JSON.stringify(msg); + } + } + // 处理@ discord用户 + messageContent = await handlerAtDiscordUser(messageContent, webhook); + // 发送消息 + resMessage = await webhook.send(messageContent, option) as DiscordMessage; + handlerSaveMessage(qqMsg, resMessage).then(); + } catch (error) { + log.error(error); + const webhook = await BotService.discord.fetchWebhook(bridge.discord.id, bridge.discord.token); + const option: WebhookMessageOptions = { + username: `${qqMsg.sender.memberName}(${qqMsg.sender.id})`, + avatarURL: `https://q1.qlogo.cn/g?b=qq&nk=${qqMsg.sender.id}&s=100&t=${Math.random()}`, + // avatarURL: `https://q.qlogo.cn/g?b=qq&nk={uid}&s=100&t={Math.random()} + // avatarURL: `http://q.qlogo.cn/headimg_dl?bs=qq&dst_uin=${qqMessage.sender.userId}&src_uin=www.feifeiboke.com&fid=blog&spec=640&t=${Math.random()}` // 高清地址 + files: [], + } + resMessage = await webhook.send(`程序出错消息格式化失败:QQMsgID=${qqMsg.messageChain[0].id} \n${JSON.stringify(qqMsg.messageChain)}`, option) as DiscordMessage; + handlerSaveMessage(qqMsg, resMessage).then(); + return; + } + +} + +// 处理回复消息 +async function handlerForward(quoteMsg: MessageType.Quote): Promise { + const memberInfo = await BotService.qqBot.mirai.api.memberInfo(quoteMsg.groupId, quoteMsg.senderId) as MiraiConfig.MemberInfo; + let messageContent = `** 回复 @${memberInfo.name} 在 {暂无日期} 的消息 **\n`; + for (const msg of quoteMsg.origin) { + switch (msg.type) { + case 'Source': + break; + case 'Quote': + break; + case 'Plain': + messageContent += msg.text; + break; + case 'At': + const memberInfo = await BotService.qqBot.mirai.api.memberInfo(quoteMsg.groupId, msg.target) as MiraiConfig.MemberInfo;; + messageContent += `\`@${memberInfo.name}(${msg.target})\``; + break; + case 'AtAll': + messageContent += `\`@everyone\``; + break; + case 'Face': + messageContent += `[Face=${msg.faceId},${msg.name}]`; + break; + case 'Image': + messageContent += `:frame_photo:`; + break; + default: + messageContent += JSON.stringify(msg); + } + } + + messageContent = messageContent.split('\n').map((str) => '> ' + str).join('\n') + '\n' + return messageContent; +} +// 处理Xml消息 +async function handlerXml(msg: MessageType.Xml): Promise { + let messageContent = ''; + const xmlData = xmlUtil.parse(msg.xml, { + attributeNamePrefix: '', + attrNodeName: 'attribute', + ignoreAttributes: false, + }); + if(xmlData.msg && xmlData.msg.attribute && xmlData.msg.attribute.serviceID === '1') { + messageContent += `> ** 转发消息 **\n` + messageContent += `> ${xmlData.msg.item.summary}\n` + messageContent += `> ${xmlData.msg.attribute.url}\n` + } else if(xmlData.msg && xmlData.msg.attribute && xmlData.msg.attribute.serviceID === '35') { + messageContent += `> ** 转发消息 **\n` + xmlData.msg.title.forEach((title)=>{ + messageContent += `> ${title['#text']}\n`; + }) + } else { + messageContent = JSON.stringify(msg.xml) + } + + return messageContent; +} + + + +// 处理@ discord用户 +async function handlerAtDiscordUser(message: string, webhook: Webhook): Promise { + const atList: Array<{ username: string, discriminator: string, origin: string }> = []; + // 正则匹配 + [ + /[@([^\n#]+)#(\d\d\d\d)]/, // [@rabbitkiller#7372] + /`@([^\n#]+)#(\d\d\d\d)`/, // `@rabbitkiller#7372` + /@([^\n#]+)#(\d\d\d\d)/, // @rabbitkiller#7372 + // 不需要#号的 + /[@([^\n#]+)]/, // [@rabbitkiller] + /`@([^\n#]+)`/, // `@rabbitkiller` + ].forEach((reg) => { + const gReg = new RegExp(reg.source, 'g'); + const sReg = new RegExp(reg.source); + // 全局匹配满足条件的 + const strList = message.match(gReg); + if (!strList) { + return; + } + strList.forEach((str) => { + // 获取用户名, 保留origin匹配上的字段用来replace + if (str.match(sReg)[1]) { + atList.push( + {origin: str, username: str.match(sReg)[1].trim(), discriminator: str.match(sReg)[2]} + ) + } + }) + }) + if (atList.length === 0) { + return message; + } + // 获取guild, 在通过guild获取所有用户 + const guild: Guild = await BotService.discord.guilds.fetch(webhook.guildID); + const fetchedMembers = await guild.members.fetch(); + fetchedMembers.forEach((member) => { + // 匹配用户名 + const ats = atList.filter(at => at.username === member.user.username); + if (ats.length === 0) { + return; + } + // 替换 + ats.forEach((at) => { + message = message.replace(at.origin, `<@!${member.user.id}>`) + }) + }); + return message; +} + +// 保存关联消息 +async function handlerSaveMessage(qqMessage: MessageType.GroupMessage, discordMessage: Message): Promise { + const messageRepo = DatabaseService.connection.getRepository(MessageEntity); + const messageEntity = new MessageEntity(); + messageEntity.from = "qq"; + messageEntity.qqMessageID = qqMessage.messageChain[0].id.toString(); + messageEntity.qqMessage = { + content: JSON.stringify(qqMessage.messageChain), + } + messageEntity.discordMessageID = discordMessage.id; + messageEntity.discordMessage = { + content: discordMessage.content, + attachments: discordMessage.attachments.array() as any, + } + return messageRepo.save(messageEntity); +} diff --git a/src/bridge-qq-to-discord.ts b/src/bridge-qq-to-discord.ts index 610fdb6..4c87d31 100644 --- a/src/bridge-qq-to-discord.ts +++ b/src/bridge-qq-to-discord.ts @@ -54,7 +54,7 @@ async function toDiscord(qqMessage: RawSession<'message'>) { for (const cqMsg of cqMessages) { // 文字直接发送 if (typeof cqMsg === 'string') { - messageContent += resolveEncoding(cqMsg); + messageContent += resolveBrackets(cqMsg); } else { // 判断类型在发送对应格式 switch (cqMsg.type) { @@ -89,14 +89,14 @@ async function toDiscord(qqMessage: RawSession<'message'>) { // avatarURL: `http://q.qlogo.cn/headimg_dl?bs=qq&dst_uin=${qqMessage.sender.userId}&src_uin=www.feifeiboke.com&fid=blog&spec=640&t=${Math.random()}` // 高清地址 files: [], } - const resMessage = await webhook.send(`发生错误导致消息同步失败:QQMsgID=${qqMessage.messageId} \n${qqMessage.message}`, option) as Message; + const resMessage = await webhook.send(`程序出错消息格式化失败:QQMsgID=${qqMessage.messageId} \n${qqMessage.message}`, option) as Message; handlerSaveMessage(qqMessage, resMessage).then(); } } -function resolveEncoding(msg) { - msg = msg.replace(new RegExp('[', 'g'), '[').replace(new RegExp(']', 'g'), ']').replace(new RegExp('&', 'g'), '&') +function resolveBrackets(msg) { + msg = msg.replace(new RegExp('[', 'g'), '[').replace(new RegExp(']', 'g'), ']') return msg } @@ -119,7 +119,7 @@ async function handlerForward(message: string): Promise { const forwardDate = `${forwardTime.getHours()}:${forwardTime.getMinutes()}:${forwardTime.getSeconds()}`; forwardMsg = result.data.message; - forwardMsg = resolveEncoding(forwardMsg); + forwardMsg = resolveBrackets(forwardMsg); // 回复的消息是否来自discord const messageRepo = DatabaseService.connection.getRepository(MessageEntity); const refMsg = await messageRepo.findOne({qqMessageID: cqMsg.data.id}); @@ -170,7 +170,7 @@ async function handlerReply(message: string): Promise { const replyDate = `${replyTime.getHours()}:${replyTime.getMinutes()}:${replyTime.getSeconds()}`; replyMsg = result.data.message; - replyMsg = resolveEncoding(replyMsg); + replyMsg = resolveBrackets(replyMsg); // 回复的消息是否来自discord const messageRepo = DatabaseService.connection.getRepository(MessageEntity); const refMsg = await messageRepo.findOne({qqMessageID: cqMsg.data.id}); diff --git a/src/bridge/bridge.controller.ts b/src/bridge/bridge.controller.ts index 2d9941a..133c7aa 100644 --- a/src/bridge/bridge.controller.ts +++ b/src/bridge/bridge.controller.ts @@ -4,60 +4,97 @@ import { InjectRepository } from '@nestjs/typeorm'; import { DToQUserLimitEntity } from '../entity/dToQ-user-limit.entity'; import { Repository } from 'typeorm'; import * as shortid from 'shortid'; -import { KoishiAndDiscordService } from '../koishiAndDiscord.service'; +import { BotService } from '../el-bot/bot.service'; +import config, { Config } from '../config'; +import * as fs from 'fs'; +import * as path from 'path'; @Controller('/api/bridge') export class BridgeController { constructor(@InjectRepository(DToQUserLimitEntity) private dToQUserLimitRepository: Repository) { } + + /** + * 获取服务器配置 + */ + @Get('config') + getBridgeConfig(@Res() res: Response) { + res.status(200).json({data: config}); + } + /** + * 保存服务器配置 + */ + @Post('config') + saveBridgeConfig(@Body() body: Config, @Res() res: Response) { + config.autoApproveQQGroup = body.autoApproveQQGroup; + fs.writeFileSync(path.join(__dirname, '../../config.json'), JSON.stringify(config, undefined, ' ')); + res.status(200).json({data: config}); + } + + /** + * 获取Discord所有伺服guilds + */ @Get('guilds') getAllGuilds(@Res() res: Response) { - const channels: Array<{id: string, name: string}> = [] - KoishiAndDiscordService.discord.guilds.cache.forEach((value, key, map)=>{ + const channels: Array<{ id: string, name: string }> = [] + BotService.discord.guilds.cache.forEach((value, key, map) => { channels.push({id: key, name: value.name}) }) - res.status(200).json({ data: channels }); + res.status(200).json({data: channels}); } + /** + * 获取Discord伺服guild所有的频道 + */ @Get('guilds/:guildID/channels') async getAllChannels(@Param('guildID') guildID: string, @Res() res: Response) { - const channels: Array<{id: string, name: string}> = [] - KoishiAndDiscordService.discord.guilds.cache.get(guildID).channels.cache.forEach((value, key, map)=>{ + const channels: Array<{ id: string, name: string }> = [] + BotService.discord.guilds.cache.get(guildID).channels.cache.forEach((value, key, map) => { channels.push({id: key, name: value.name}) }) - res.status(200).json({ data: channels }); + res.status(200).json({data: channels}); } + /** + * 获取Discord伺服guild所有的用户 + */ @Get('guilds/:guildID/users') async getAllUsers(@Param('guildID') guildID: string, @Res() res: Response) { - const users: Array<{id: string, username: string, discriminator: string, bot: boolean}> = [] - const fetchedMembers = await KoishiAndDiscordService.discord.guilds.cache.get(guildID).members.fetch() - KoishiAndDiscordService.discord.guilds.cache.get(guildID).members.cache.forEach((value, key, map)=>{ + const users: Array<{ id: string, username: string, discriminator: string, bot: boolean }> = [] + const fetchedMembers = await BotService.discord.guilds.cache.get(guildID).members.fetch() + BotService.discord.guilds.cache.get(guildID).members.cache.forEach((value, key, map) => { users.push({id: key, username: value.user.username, discriminator: value.user.discriminator, bot: value.user.bot}) }) - res.status(200).json({ data: users }); + res.status(200).json({data: users}); } + /** + * 获取对应伺服的限制同步信息 + */ @Get('guilds/:guildID/DToQUserLimit') async getAllDToQUserLimit(@Param('guildID') guildID: string, @Res() res: Response) { const results = await this.dToQUserLimitRepository.find({guild: guildID}); - res.status(200).json({ data: results }); + res.status(200).json({data: results}); } + /** + * 保存对应伺服的限制同步信息 + */ @Post('DToQUserLimit') async postAllDToQUserLimit(@Body() body: DToQUserLimitEntity, @Res() res: Response) { const result = await this.dToQUserLimitRepository.save(body); - res.status(200).json({ data: result }); + res.status(200).json({data: result}); } - + /** + * 删除对应伺服的限制同步信息 + */ @Delete('DToQUserLimit/:id') async deleteAllDToQUserLimit(@Param('id') id: string, @Res() res: Response) { const result = await this.dToQUserLimitRepository.delete(id) - res.status(200).json({ data: result }); + res.status(200).json({data: result}); } - } diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..1601c20 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,30 @@ +import * as fs from 'fs'; +import * as path from 'path'; + +interface BridgeConfig { + discord: { + id: string, + token: string, + channelID: string, + }, + qqGroup: number +} +export interface Config { + qqBot: number, + setting: { + host: string, + port: number, + authKey: string, + enableWebsocket: boolean, + }, + discordBot: string; + discordBotToken: string; + bridges: BridgeConfig[]; + autoApproveQQGroup: Array<{qqGroup: number, reg: string}> + proxy: string; +} +const config = {} as Config; +const json = JSON.parse(fs.readFileSync(path.join(__dirname, '../config.json')).toString()); +Object.assign(config, json); + +export default config; diff --git a/src/el-bot/auto-approve-qq-group-add.ts b/src/el-bot/auto-approve-qq-group-add.ts new file mode 100644 index 0000000..7127e27 --- /dev/null +++ b/src/el-bot/auto-approve-qq-group-add.ts @@ -0,0 +1,19 @@ +/** + * 自动审批新成员进群 + */ +import { MessageType } from 'mirai-ts'; +import { BotService } from './bot.service'; +import config from '../config'; + +export async function autoApproveQQGroup() { + BotService.qqBot.mirai.on('MemberJoinRequestEvent', (data) => { + const flag = config.autoApproveQQGroup.find(s => s.qqGroup === data.groupId); + // 判断有没有配置自动审批 + if (!flag) { + return; + } + if (data.message && new RegExp(flag.reg).test(data.message)) { + data.respond(0); + } + }) +} diff --git a/src/el-bot/bot.service.ts b/src/el-bot/bot.service.ts new file mode 100644 index 0000000..96bc350 --- /dev/null +++ b/src/el-bot/bot.service.ts @@ -0,0 +1,51 @@ +import {default as Bot} from "el-bot"; +import config from '../config'; +import {Client, Intents} from 'discord.js'; +import * as log from "../utils/log5"; + +class _ElAndDiscordService { + discord: Client; + qqBot: Bot; + + constructor() { + } + + async initQQBot() { + const qqBot = this.qqBot = new Bot({ + qq: config.qqBot, + setting: config.setting, + } as any); + return await qqBot.start(); + } + + async initDiscord() { + return new Promise((resolve, reject) => { + // 需要Intents允许一些行为(要获取频道的用户必须需要) + const intents = new Intents([ + Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need + "GUILD_MEMBERS", // lets you request guild members (i.e. fixes the issue) + ]); + const discord = this.discord = new Client({ws: {intents}}); + + function loginDiscord() { + discord.login(config.discordBotToken).then(() => { + }, (err) => { + log.message(err); + log.message('🌈', `Discord 连接失败, 重新连接...`); + loginDiscord(); + }); + } + + discord.on('ready', () => { + try { + resolve(discord) + } catch (error) { + reject(error); + } + }); + loginDiscord(); + }) + } +} + +export const BotService = new _ElAndDiscordService(); diff --git a/src/main.ts b/src/main.ts index 7720b23..f3c17f3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3,21 +3,23 @@ import 'koishi-adapter-cqhttp'; import * as log from './utils/log5'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; -import bridgeQQToDiscord from './bridge-qq-to-discord'; -import bridgeDiscordToQQ from './bridge-discord-to-qq'; import {DatabaseService} from "./database.service"; -import {KoishiAndDiscordService} from "./koishiAndDiscord.service"; +import { BotService } from './el-bot/bot.service'; +import { autoApproveQQGroup } from './el-bot/auto-approve-qq-group-add'; +import bridgeQQToDiscord from './bridge-qq-to-discord.el'; +import bridgeDiscordToQQ from './bridge-discord-to-qq.el'; async function main() { await DatabaseService.init(); log.message('🌈', `数据库连接成功`); - await KoishiAndDiscordService.initQQBot(); + await BotService.initQQBot(); log.message('🌈', `QQ 成功连接`); - await KoishiAndDiscordService.initDiscord(); - log.message('🌈', `Discord 成功登录 ${KoishiAndDiscordService.discord.user.tag}`); + await BotService.initDiscord(); + log.message('🌈', `Discord 成功登录 ${BotService.discord.user.tag}`); await bridgeQQToDiscord(); await bridgeDiscordToQQ(); + await autoApproveQQGroup(); } main().then()