diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..19a89a7a3d8092bdf6aaf18444d2c89ffe7c4c9d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.ttf filter=lfs diff=lfs merge=lfs -text +Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.woff filter=lfs diff=lfs merge=lfs -text +Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.ttf filter=lfs diff=lfs merge=lfs -text +Yunzai/plugins/ws-plugin/resources/help/icon.png filter=lfs diff=lfs merge=lfs -text diff --git a/Yunzai/.eslintrc.cjs b/Yunzai/.eslintrc.cjs new file mode 100644 index 0000000000000000000000000000000000000000..a9b525032da461f639576fefdc3551565af8f5d6 --- /dev/null +++ b/Yunzai/.eslintrc.cjs @@ -0,0 +1,22 @@ +module.exports = { + env: { + es2021: true, + node: true + }, + extends: ['standard'], + parserOptions: { + ecmaVersion: 'latest', + sourceType: 'module' + }, + globals: { + Bot: true, + redis: true, + logger: true, + plugin: true + }, + rules: { + eqeqeq: ['off'], + 'prefer-const': ['off'], + 'arrow-body-style': 'off' + } +} diff --git a/Yunzai/.gitignore b/Yunzai/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..666c10c1707849efd787e8c65f6cf987899dc314 --- /dev/null +++ b/Yunzai/.gitignore @@ -0,0 +1,149 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vuepress v2.x temp and cache directory +.temp +.cache + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test +.vscode/ + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +# Yunzai data +dump.rdb +config/*.yaml +config/test/* +data/ +!config/test/default.yaml +logs/ +resources/ + +# Docker file +redis +yunzai +/.idea/ +/data/ +/temp/ +/pnpm-lock.yaml +/entrypoint.sh diff --git a/Yunzai/.npmrc b/Yunzai/.npmrc new file mode 100644 index 0000000000000000000000000000000000000000..4bcbc82b1f5cc4fe2ec052bd9c1b8e300648b2c9 --- /dev/null +++ b/Yunzai/.npmrc @@ -0,0 +1,3 @@ +registry=https://registry.npmmirror.com +node_sqlite3_binary_host_mirror=https://npmmirror.com/mirrors/sqlite3 +canvas_binary_host_mirror=https://npmmirror.com/mirrors/canvas \ No newline at end of file diff --git a/Yunzai/.puppeteerrc.cjs b/Yunzai/.puppeteerrc.cjs new file mode 100644 index 0000000000000000000000000000000000000000..8a7762bf1f43c1595f4b1f72f8f9a5ebf3c3c77a --- /dev/null +++ b/Yunzai/.puppeteerrc.cjs @@ -0,0 +1,40 @@ +const os = require("os") +const { existsSync } = require("fs") +const { execSync } = require("child_process") +const arch = os.arch() + +let skipDownload = false +let executablePath + +if (process.platform == "linux" || process.platform == "android") + for (const item of [ + "chromium", + "chromium-browser", + "chrome", + ]) try { + const chromiumPath = execSync(`command -v ${item}`).toString().trim() + if (chromiumPath && existsSync(chromiumPath)) { + executablePath = chromiumPath + break + } + } catch (err) {} + +if (!executablePath) for (const item of [ + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + "/usr/bin/chrome", + "C:/Program Files/Google/Chrome/Application/chrome.exe", + "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", +]) if (existsSync(item)) { + executablePath = item + break +} + +if (executablePath || arch == "arm64" || arch == "aarch64") { + (typeof logger == "object" ? logger : console).info(`[Chromium] ${executablePath}`) + skipDownload = true +} + +module.exports = { skipDownload, executablePath } \ No newline at end of file diff --git a/Yunzai/CHANGELOG.md b/Yunzai/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e215f2d78d015ca94b7d81f8d8662b9bcaa6c9d0 --- /dev/null +++ b/Yunzai/CHANGELOG.md @@ -0,0 +1,32 @@ +# 3.1.1 + +* 支持协议端:米游社大别野Bot +* 初步适配原神4.0版本,增加对应资源及信息展示,感谢**Ca(HCO₃)₂**、**@touchscale**、**@teriri7** +* 升级`#探索`内容,支持更多内容展示 **@bangbanbab** +* 增加 `#全部抽卡记录` **@story-x** + +# 3.1.0 + +* 支持协议端:GSUIDCore、微信 +* 重构CK与UID管理逻辑 + * 支持多UID绑定,可绑定多个UID并进行切换 + * 支持原神与星铁UID共存,可针对查询命令分配对应UID + * 新增`#删除uid1`命令,可对`#uid`列表内的绑定UID进行删除 + * 使用sqlite进行ck与uid存储 +* 底层对星铁查询进行支持 **@cvs** + +# 3.0.2 + +* 支持协议端:ComWeChat、ICQQ、QQ频道、KOOK、Telegram、Discord +* 3.6卡池以及图像武器别名等数据更新 **@cvs** +* 将渲染逻辑独立,支持扩展渲染器 **@ikuaki** + +# 3.0.1 + +* 支持多账号,支持协议端:go-cqhttp + +# 3.0.0 + +* 从 Miao-Yunzai 分支 + +# 3.0.0 \ No newline at end of file diff --git a/Yunzai/LICENSE b/Yunzai/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/Yunzai/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Yunzai/README.md b/Yunzai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4be8ead4323917a017bdeae149dc3b9cda70a85 --- /dev/null +++ b/Yunzai/README.md @@ -0,0 +1,170 @@ +
+ +# TRSS-Yunzai + +Yunzai 应用端,支持多账号,支持协议端:go-cqhttp、ComWeChat、GSUIDCore、ICQQ、QQ频道、微信、KOOK、Telegram、Discord + +[![访问量](https://visitor-badge.glitch.me/badge?page_id=TimeRainStarSky.Yunzai&right_color=red&left_text=访%20问%20量)](https://github.com/TimeRainStarSky/Yunzai) +[![Stars](https://img.shields.io/github/stars/TimeRainStarSky/Yunzai?color=yellow&label=收藏)](../../stargazers) +[![Downloads](https://img.shields.io/github/downloads/TimeRainStarSky/Yunzai/total?color=blue&label=下载)](../../archive/main.tar.gz) +[![Releases](https://img.shields.io/github/v/release/TimeRainStarSky/Yunzai?color=green&label=发行版)](../../releases/latest) + +[![访问量](https://profile-counter.glitch.me/TimeRainStarSky-Yunzai/count.svg)](https://github.com/TimeRainStarSky/Yunzai) + +
+ +- 基于 [Miao-Yunzai](../../../../yoimiya-kokomi/Miao-Yunzai) 改造,需要同时安装 [miao-plugin](../../../../yoimiya-kokomi/miao-plugin) +- 开发文档:[docs 分支](../../tree/docs) + +## TRSS-Yunzai 后续计划 + +先刨坑,但也许会咕咕咕 + +- 完善现有协议端 +- 支持更多协议端 + +项目仅供学习交流使用,严禁用于任何商业用途和非法行为 + +## 使用方法 + +### 建议使用 TRSS Script 一键安装管理 + +- [🌌 TRSS](https://TRSS.me) +- [🔼 Vercel](https://TRSS-Script.Vercel.app) +- [🐱 GitHub](https://TimeRainStarSky.GitHub.io/TRSS_Script) +- [🇬 Gitee](https://Gitee.com/TimeRainStarSky/TRSS_Script) + +### 手动安装 + +> 环境准备: Windows or Linux,Node.js( [版本至少 v18 以上](http://nodejs.cn/download) ), [Redis](https://redis.io/docs/getting-started/installation) + +1.克隆项目并安装 genshin miao-plugin TRSS-Plugin(可选) + +请根据网络情况选择使用 GitHub 或 Gitee 安装 + +``` +git clone --depth 1 https://github.com/TimeRainStarSky/Yunzai +cd Yunzai +git clone --depth 1 https://github.com/TimeRainStarSky/Yunzai-genshin plugins/genshin +git clone --depth 1 https://github.com/yoimiya-kokomi/miao-plugin plugins/miao-plugin +git clone --depth 1 https://github.com/TimeRainStarSky/TRSS-Plugin plugins/TRSS-Plugin +``` + +``` +git clone --depth 1 https://gitee.com/TimeRainStarSky/Yunzai +cd Yunzai +git clone --depth 1 https://gitee.com/TimeRainStarSky/Yunzai-genshin plugins/genshin +git clone --depth 1 https://gitee.com/yoimiya-kokomi/miao-plugin plugins/miao-plugin +git clone --depth 1 https://Yunzai.TRSS.me plugins/TRSS-Plugin +``` + +2.安装 [pnpm](https://pnpm.io/zh/installation) + +``` +npm install -g pnpm +``` + +3.安装依赖 + +``` +pnpm i +``` + +4.运行 + +``` +node app +``` + +5.启动协议端: + +
go-cqhttp + +下载运行 [go-cqhttp](https://docs.go-cqhttp.org),选择反向 WebSocket,修改 `config.yml`,以下为必改项: + +``` +uin: 账号 +password: '密码' +post-format: array +universal: ws://localhost:2536/go-cqhttp +``` + +
+ +
ComWeChat + +下载运行 [ComWeChat](https://justundertaker.github.io/ComWeChatBotClient),修改 `.env`,以下为必改项: + +``` +websocekt_type = "Backward" +websocket_url = ["ws://localhost:2536/ComWeChat"] +``` + +
+ +
GSUIDCore + +下载运行 [GenshinUID 插件](http://docs.gsuid.gbots.work/#/AdapterList),GSUIDCore 连接地址 修改为: + +``` +ws://localhost:2536/GSUIDCore +``` + +
+ +
ICQQ + +[TRSS-Yunzai ICQQ Plugin](../../../Yunzai-ICQQ-Plugin) + +
+ +
QQ频道 + +[TRSS-Yunzai QQGuild Plugin](../../../Yunzai-QQGuild-Plugin) + +
+ +
微信 + +[TRSS-Yunzai WeChat Plugin](../../../Yunzai-WeChat-Plugin) + +
+ +
米游社大别野 + +[TRSS-Yunzai mysVilla Plugin](../../../Yunzai-mysVilla-Plugin) + +
+ +
KOOK + +[TRSS-Yunzai KOOK Plugin](../../../Yunzai-KOOK-Plugin) + +
+ +
Telegram + +[TRSS-Yunzai Telegram Plugin](../../../Yunzai-Telegram-Plugin) + +
+ +
Discord + +[TRSS-Yunzai Discord Plugin](../../../Yunzai-Discord-Plugin) + +
+ +
代理 + +[TRSS-Yunzai Proxy Plugin](../../../Yunzai-Proxy-Plugin) + +
+ +6.设置主人:发送 `#设置主人`,后台日志获取验证码并发送 + +## 致谢 + +| Nickname | Contribution | +| :-----------------------------------------------------------: | -------------------- | +| [Yunzai-Bot](../../../../Le-niao/Yunzai-Bot) | 乐神的 Yunzai-Bot | +| [Miao-Yunzai](../../../../yoimiya-kokomi/Miao-Yunzai) | 喵喵的 Miao-Yunzai | \ No newline at end of file diff --git a/Yunzai/app.js b/Yunzai/app.js new file mode 100644 index 0000000000000000000000000000000000000000..6feed2aa2a5f229da43a369ed249523cfdfe5cfc --- /dev/null +++ b/Yunzai/app.js @@ -0,0 +1,3 @@ +import Yunzai from "./lib/bot.js" +global.Bot = new Yunzai +Bot.run() \ No newline at end of file diff --git a/Yunzai/config/config/.gitignore b/Yunzai/config/config/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c96a04f008ee21e260b28f7701595ed59e2839e3 --- /dev/null +++ b/Yunzai/config/config/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/Yunzai/config/default_config/bot.yaml b/Yunzai/config/default_config/bot.yaml new file mode 100644 index 0000000000000000000000000000000000000000..86c6cf12f0f5539f444993fc96ed9433e3a10986 --- /dev/null +++ b/Yunzai/config/default_config/bot.yaml @@ -0,0 +1,23 @@ +# 日志等级:trace,debug,info,warn,fatal,mark,error,off +# mark时只显示执行命令,不显示聊天记录 +log_level: info +# 服务器端口 +port: 2536 + +# chromium其他路径 +chromium_path: +# puppeteer接口地址 +puppeteer_ws: +# puppeteer截图超时时间 +puppeteer_timeout: + +# 米游社接口代理地址,国际服用 +proxyAddress: + +# 上线时给主人推送帮助 +online_msg: true +# 上线推送通知的冷却时间 +online_msg_exp: 86400 + +# 单条日志长度 +logLength: 1000 \ No newline at end of file diff --git a/Yunzai/config/default_config/group.yaml b/Yunzai/config/default_config/group.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f67819aaee9ca71f02f458898e06e52b1c5b0636 --- /dev/null +++ b/Yunzai/config/default_config/group.yaml @@ -0,0 +1,37 @@ +# 默认设置 +default: + groupCD: 500 # 群聊中所有指令操作冷却时间,单位毫秒,0则无限制 + singleCD: 2000 # 群聊中个人操作冷却时间,单位毫秒 + + onlyReplyAt: 0 # 是否只仅关注主动提及Bot的消息 0-否 1-是 + botAlias: # 开启后则只回复提及Bot的消息及特定前缀的消息 + - 云崽 + - 云宝 + + addLimit: 0 # 是否限制添加消息 0-所有群员 1-群管理员 2-主人 + addPrivate: 1 # 是否允许私聊添加 + addReply: 1 # 是否回复触发消息 + addAt: 0 # 是否提及触发用户 + addRecall: 60 # 是否撤回回复消息 + + enable: # 只启用功能,配置后只有该功能才响应 + disable: # 禁用功能,功能名称,例如:十连、角色查询、体力查询、用户绑定、抽卡记录、添加表情、欢迎新人、退群通知 + - 禁用示例 + - 支持多个 + +# Bot单独设置 +114514:default: + onlyReplyAt: 1 + botAlias: + - 臭崽 + - 臭宝 + +# 群单独设置 +123456: + groupCD: 500 + singleCD: 2000 + +# [Bot:群]单独设置 +114514:123456: + enable: + disable: \ No newline at end of file diff --git a/Yunzai/config/default_config/other.yaml b/Yunzai/config/default_config/other.yaml new file mode 100644 index 0000000000000000000000000000000000000000..96810b376a6f70f070b6b8af25b7efe39ae0f603 --- /dev/null +++ b/Yunzai/config/default_config/other.yaml @@ -0,0 +1,27 @@ +# 是否自动同意加好友 1-同意 0-不处理 +autoFriend: 1 +# 是否自动退群人数,当被好友拉进群时,群人数小于配置值自动退出, 默认50,0则不处理 +autoQuit: 50 +# 主人帐号 +masterQQ: + - "stdin" +# Bot账号:主人帐号 +master: + - "stdin:stdin" + +# 禁用私聊功能 true:私聊只接受ck以及抽卡链接(Bot主人不受限制),false:私聊可以触发全部指令,默认false +disablePrivate: false +# 禁用私聊Bot提示内容 +disableMsg: "私聊功能已禁用,仅支持发送cookie,抽卡记录链接,记录日志文件" +# 私聊通行字符串 +disableAdopt: + - stoken +#白名单群,配置后只在该群生效 +whiteGroup: + +#黑名单群 +blackGroup: + - 213938015 +#黑名单账号 +blackQQ: + - 528952540 \ No newline at end of file diff --git a/Yunzai/config/default_config/redis.yaml b/Yunzai/config/default_config/redis.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9be88333b46430e4ffcebf746bf85c7fed7b7b3 --- /dev/null +++ b/Yunzai/config/default_config/redis.yaml @@ -0,0 +1,10 @@ +# redis地址 +host: 127.0.0.1 +# redis端口 +port: 6379 +# redis用户名,可以为空 +username: +# redis密码,没有密码可以为空 +password: +# redis数据库 +db: 0 \ No newline at end of file diff --git a/Yunzai/config/default_config/renderer.yaml b/Yunzai/config/default_config/renderer.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f44866b5b06aa2b4c15b0ac85d0fb8143e517f61 --- /dev/null +++ b/Yunzai/config/default_config/renderer.yaml @@ -0,0 +1,2 @@ +# 渲染后端, 默认为 puppeteer +name: \ No newline at end of file diff --git a/Yunzai/config/pm2/pm2.json b/Yunzai/config/pm2/pm2.json new file mode 100644 index 0000000000000000000000000000000000000000..4f24a9264b8e5452b86934685daa1bd4b54119b6 --- /dev/null +++ b/Yunzai/config/pm2/pm2.json @@ -0,0 +1,10 @@ +{ + "apps": [ + { + "name": "TRSS-Yunzai", + "script": "./app.js", + "max_memory_restart": "512M", + "restart_delay": 60000 + } + ] +} \ No newline at end of file diff --git a/Yunzai/config/test/default.yaml b/Yunzai/config/test/default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1477402e2630fb135e0267d3b2692b18d84a374b --- /dev/null +++ b/Yunzai/config/test/default.yaml @@ -0,0 +1,10 @@ +# 默认测试配置,其他配置自行复制 +post_type: message +message_type: group +sub_type: normal +group_id: 213938015 +group_name: '2333' +user_id: 805475874 +# 测试命令 +text: 十连 +card: 测试(104070461) diff --git a/Yunzai/lib/bot.js b/Yunzai/lib/bot.js new file mode 100644 index 0000000000000000000000000000000000000000..0c478ffd702713f8e2a1e0002553843feb445d45 --- /dev/null +++ b/Yunzai/lib/bot.js @@ -0,0 +1,231 @@ +import "./config/init.js" +import cfg from "./config/config.js" +import PluginsLoader from "./plugins/loader.js" +import ListenerLoader from "./listener/loader.js" +import { EventEmitter } from "events" +import express from "express" +import http from "http" +import { WebSocketServer } from "ws" +import _ from "lodash" + +export default class Yunzai extends EventEmitter { + constructor() { + super() + this.uin = [] + this.adapter = [] + this.express = express() + this.server = http.createServer(this.express) + this.server.on("upgrade", (req, socket, head) => { + this.wss.handleUpgrade(req, socket, head, conn => { + conn.id = `${req.connection.remoteAddress}-${req.headers["sec-websocket-key"]}` + this.makeLog("mark", `${logger.blue(`[${conn.id} <=> ${req.url}]`)} 建立连接:${JSON.stringify(req.headers)}`) + conn.on("error", logger.error) + conn.on("close", () => this.makeLog("mark", `${logger.blue(`[${conn.id} <≠> ${req.url}]`)} 断开连接`)) + conn.on("message", msg => this.makeLog("debug", `${logger.blue(`[${conn.id} => ${req.url}]`)} 消息:${String(msg).trim()}`)) + conn.sendMsg = msg => { + if (typeof msg == "object") + msg = JSON.stringify(msg) + this.makeLog("debug", `${logger.blue(`[${conn.id} <= ${req.url}]`)} 消息:${msg}`) + return conn.send(msg) + } + for (const i of this.wsf[req.url.split("/")[1]] || []) + i(conn, req, socket, head) + }) + }) + this.wss = new WebSocketServer({ noServer: true }) + this.wsf = {} + } + + makeLog(level, msg) { + logger[level](_.truncate(msg, { length: cfg.bot.logLength })) + } + + em(name = "", data = {}) { + if (data.self_id) + Object.defineProperty(data, "bot", { value: Bot[data.self_id] }) + while (true) { + this.emit(name, data) + const i = name.lastIndexOf(".") + if (i == -1) break + name = name.slice(0, i) + } + } + + async run() { + await import("./plugins/stdin.js") + await PluginsLoader.load() + await ListenerLoader.load() + this.serverLoad() + this.emit("online", this) + } + + serverLoad() { + this.express.use(req => { + logger.mark(`${logger.blue(`[${req.ip} => ${req.url}]`)} HTTP ${req.method} 请求:${JSON.stringify(req.headers)}`) + req.res.redirect("https://github.com/TimeRainStarSky/Yunzai") + }) + + this.server.listen(cfg.bot.port, () => { + const host = this.server.address().address + const port = this.server.address().port + logger.mark(`启动 HTTP 服务器:${logger.green(`http://[${host}]:${port}`)}`) + for (const i of Object.keys(this.wsf)) + logger.info(`本机 ${i} 连接地址:${logger.blue(`ws://localhost:${port}/${i}`)}`) + }) + } + + getFriendArray() { + const array = [] + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].fl || []) + array.push({ ...i, bot_id }) + return array + } + + getFriendList() { + const array = [] + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].fl || []) + array.push(id) + return array + } + + getFriendMap() { + const map = new Map + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].fl || []) + map.set(id, { ...i, bot_id }) + return map + } + get fl() { return this.getFriendMap() } + + getGroupArray() { + const array = [] + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].gl || []) + array.push({ ...i, bot_id }) + return array + } + + getGroupList() { + const array = [] + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].gl || []) + array.push(id) + return array + } + + getGroupMap() { + const map = new Map + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].gl || []) + map.set(id, { ...i, bot_id }) + return map + } + get gl() { return this.getGroupMap() } + get gml() { + const map = new Map + for (const bot_id of this.uin) + for (const [id, i] of this[bot_id].gml || []) + map.set(id, i) + return map + } + + pickFriend(user_id) { + user_id = Number(user_id) || String(user_id) + const user = this.fl.get(user_id) + if (user) return this[user.bot_id].pickFriend(user_id) + logger.error(`获取用户对象失败:找不到用户 ${logger.red(user_id)}`) + } + get pickUser() { return this.pickFriend } + + pickGroup(group_id) { + group_id = Number(group_id) || String(group_id) + const group = this.gl.get(group_id) + if (group) return this[group.bot_id].pickGroup(group_id) + logger.error(`获取群对象失败:找不到群 ${logger.red(group_id)}`) + } + + pickMember(group_id, user_id) { + const group = this.pickGroup(group_id) + if (group) return group.pickMember(user_id) + } + + sendFriendMsg(bot_id, user_id, msg) { + try { + if (!bot_id) + return this.pickFriend(user_id).sendMsg(msg) + + if (this[bot_id]) + return this[bot_id].pickFriend(user_id).sendMsg(msg) + + return new Promise(resolve => + this.once(`connect.${bot_id}`, data => + resolve(data.bot.pickFriend(user_id).sendMsg(msg)))) + } catch (err) { + logger.error(`${logger.blue(`[${bot_id}]`)} 发送好友消息失败:[$${user_id}] ${err}`) + } + return false + } + + sendGroupMsg(bot_id, group_id, msg) { + try { + if (!bot_id) + return this.pickGroup(group_id).sendMsg(msg) + + if (this[bot_id]) + return this[bot_id].pickGroup(group_id).sendMsg(msg) + + return new Promise(resolve => + this.once(`connect.${bot_id}`, data => + resolve(data.bot.pickGroup(group_id).sendMsg(msg)))) + } catch (err) { + logger.error(`${logger.blue(`[${bot_id}]`)} 发送群消息失败:[$${group_id}] ${err}`) + } + return false + } + + async getFriendMsg(fnc = () => true) { + if (typeof fnc != "function") { + const { self_id, user_id } = fnc + fnc = data => data.self_id == self_id && data.user_id == user_id + } + + while (true) { + const msg = await new Promise(resolve => { + this.once("message", data => { + if (data.message && fnc(data)) { + let msg = "" + for (const i of data.message) + if (i.type = "text") + msg += i.text.trim() + resolve(msg) + } else { + resolve(false) + } + }) + }) + if (msg) return msg + } + } + + getMasterMsg() { + return this.getFriendMsg(data => + cfg.master[data.self_id]?.includes(String(data.user_id))) + } + + sendMasterMsg(msg) { + for (const bot_id in cfg.master) + for (const user_id of cfg.master[bot_id]) + this.sendFriendMsg(bot_id, user_id, msg) + } + + makeForwardMsg(msg) { return { type: "node", data: msg } } + + async sendForwardMsg(send, msg) { + const messages = [] + for (const { message } of msg) + messages.push(await send(message)) + return messages + } +} \ No newline at end of file diff --git a/Yunzai/lib/common/common.js b/Yunzai/lib/common/common.js new file mode 100644 index 0000000000000000000000000000000000000000..90a2605fa512acb3da18114394d596c42ac0168e --- /dev/null +++ b/Yunzai/lib/common/common.js @@ -0,0 +1,75 @@ +import { pipeline } from 'stream' +import { promisify } from 'util' +import fetch from 'node-fetch' +import fs from 'node:fs' +import path from 'node:path' + +/** + * 发送私聊消息 + * @param user_id 账号 + * @param msg 消息 + */ +function relpyPrivate(userId, msg) { + return Bot.pickFriend(userId).sendMsg(msg) +} + +/** + * 休眠函数 + * @param ms 毫秒 + */ +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +/** + * 下载保存文件 + * @param fileUrl 下载地址 + * @param savePath 保存路径 + */ +async function downFile(fileUrl, savePath,param = {}) { + try { + mkdirs(path.dirname(savePath)) + logger.debug(`[下载文件] ${fileUrl}`) + const response = await fetch(fileUrl,param) + const streamPipeline = promisify(pipeline) + await streamPipeline(response.body, fs.createWriteStream(savePath)) + return true + } catch (err) { + logger.error(`下载文件错误:${err}`) + return false + } +} + +function mkdirs(dirname) { + if (fs.existsSync(dirname)) { + return true + } else { + if (mkdirs(path.dirname(dirname))) { + fs.mkdirSync(dirname) + return true + } + } +} + +/** + * 制作转发消息 + * @param e 消息事件 + * @param msg 消息数组 + * @param dec 转发描述 + */ +function makeForwardMsg(e, msg = [], dec) { + const forwardMsg = [] + if (dec) + forwardMsg.push({ message: dec }) + for (const message of msg) + forwardMsg.push({ message }) + + if (e?.group?.makeForwardMsg) + return e.group.makeForwardMsg(forwardMsg) + else if (e?.friend?.makeForwardMsg) + return e.friend.makeForwardMsg(forwardMsg) + else + return Bot.makeForwardMsg(forwardMsg) +} + +export default { relpyPrivate, sleep, downFile, mkdirs, makeForwardMsg } \ No newline at end of file diff --git a/Yunzai/lib/config/check.js b/Yunzai/lib/config/check.js new file mode 100644 index 0000000000000000000000000000000000000000..7141169065437ce6e6a96214aaa765b4afc34e9a --- /dev/null +++ b/Yunzai/lib/config/check.js @@ -0,0 +1,32 @@ +import fs from 'fs' +import { createRequire } from 'module' +const require = createRequire(import.meta.url) +const { exec } = require('child_process') + +export async function checkRun () { + if (process.argv[1].includes('pm2')) return + if (process.argv[1].includes('test')) return + + let cfg = pm2Cfg() + let status = await execSync(`pm2 show ${cfg.apps[0].name}`) + + if (status.stdout.includes('online')) { + logger.mark('检测到后台正在运行') + logger.mark('已停止后台进程,防止重复运行') + execSync(`pm2 stop ${cfg.apps[0].name}`) + } +} + +async function execSync (cmd) { + return new Promise((resolve, reject) => { + exec(cmd, (error, stdout, stderr) => { + resolve({ error, stdout, stderr }) + }) + }) +} + +function pm2Cfg () { + let cfg = fs.readFileSync('config/pm2/pm2.json') + cfg = JSON.parse(cfg) + return cfg +} diff --git a/Yunzai/lib/config/config.js b/Yunzai/lib/config/config.js new file mode 100644 index 0000000000000000000000000000000000000000..d3fcf31ded62ba5243075d8e7a331a1a3dfba253 --- /dev/null +++ b/Yunzai/lib/config/config.js @@ -0,0 +1,174 @@ +import YAML from "yaml" +import fs from "node:fs" +import chokidar from "chokidar" + +/** 配置文件 */ +class Cfg { + constructor () { + this.config = {} + + /** 监听文件 */ + this.watcher = { config: {}, defSet: {} } + + this.initCfg() + } + + /** 初始化配置 */ + initCfg () { + let path = "config/config/" + let pathDef = "config/default_config/" + const files = fs.readdirSync(pathDef).filter(file => file.endsWith(".yaml")) + for (let file of files) + if (!fs.existsSync(`${path}${file}`)) + fs.copyFileSync(`${pathDef}${file}`, `${path}${file}`) + if (!fs.existsSync("data")) fs.mkdirSync("data") + if (!fs.existsSync("resources")) fs.mkdirSync("resources") + } + + /** Bot配置 */ + get bot () { + let bot = this.getConfig("bot") + let defbot = this.getdefSet("bot") + bot = { ...defbot, ...bot } + + return bot + } + + get other () { + return this.getConfig("other") + } + + get redis () { + return this.getConfig("redis") + } + + get renderer() { + return this.getConfig("renderer"); + } + + /** 主人账号 */ + get masterQQ () { + let masterQQ = this.getConfig("other").masterQQ || [] + + if (!Array.isArray(masterQQ)) + masterQQ = [masterQQ] + + const masters = [] + for (const i of masterQQ) + masters.push(Number(i) || String(i)) + return masters + } + + /** Bot账号:[主人帐号] */ + get master () { + let master = this.getConfig("other").master || [] + + if (!Array.isArray(master)) + master = [master] + + const masters = {} + for (let i of master) { + i = i.split(":") + if (Array.isArray(masters[i[0]])) + masters[i[0]].push(i[1]) + else + masters[i[0]] = [i[1]] + } + return masters + } + + /** 机器人账号 */ + get uin () { + return Object.keys(this.master) + } + get qq () { + return this.uin + } + + /** package.json */ + get package () { + if (this._package) return this._package + + this._package = JSON.parse(fs.readFileSync("package.json", "utf8")) + return this._package + } + + /** 群配置 */ + getGroup (bot_id = "", group_id = "") { + const config = this.getConfig("group") + const defCfg = this.getdefSet("group") + return { + ...defCfg.default, + ...config.default, + ...config[`${bot_id}:default`], + ...config[group_id], + ...config[`${bot_id}:${group_id}`], + } + } + + /** other配置 */ + getOther () { + let def = this.getdefSet("other") + let config = this.getConfig("other") + return { ...def, ...config } + } + + /** + * @param app 功能 + * @param name 配置文件名称 + */ + getdefSet (name) { + return this.getYaml("default_config", name) + } + + /** 用户配置 */ + getConfig (name) { + return this.getYaml("config", name) + } + + /** + * 获取配置yaml + * @param type 默认跑配置-defSet,用户配置-config + * @param name 名称 + */ + getYaml (type, name) { + let file = `config/${type}/${name}.yaml` + let key = `${type}.${name}` + if (this.config[key]) return this.config[key] + + this.config[key] = YAML.parse( + fs.readFileSync(file, "utf8") + ) + + this.watch(file, name, type) + + return this.config[key] + } + + /** 监听配置文件 */ + watch (file, name, type = "default_config") { + let key = `${type}.${name}` + + if (this.watcher[key]) return + + const watcher = chokidar.watch(file) + watcher.on("change", path => { + delete this.config[key] + if (typeof Bot == "undefined") return + logger.mark(`[修改配置文件][${type}][${name}]`) + if (this[`change_${name}`]) { + this[`change_${name}`]() + } + }) + + this.watcher[key] = watcher + } + + async change_bot () { + /** 修改日志等级 */ + let log = await import("./log.js") + log.default() + } +} + +export default new Cfg() \ No newline at end of file diff --git a/Yunzai/lib/config/init.js b/Yunzai/lib/config/init.js new file mode 100644 index 0000000000000000000000000000000000000000..2cd1cc27e8788f9748137c9ddc5cc49343a4728a --- /dev/null +++ b/Yunzai/lib/config/init.js @@ -0,0 +1,42 @@ +import setLog from './log.js' +import redisInit from './redis.js' +import { checkRun } from './check.js' +import cfg from './config.js' + +/** 设置标题 */ +process.title = 'TRSS Yunzai' + +/** 设置时区 */ +process.env.TZ = 'Asia/Shanghai' + +/** 捕获未处理的Promise错误 */ +process.on('unhandledRejection', (error, promise) => { + if (logger) { + logger.error(error) + } else { + console.log(error) + } +}) + +/** 退出事件 */ +process.on('exit', async code => { + if (typeof redis != 'undefined' && typeof test == 'undefined') + await redis.save() + logger.mark(logger.magenta('TRSS-Yunzai 已停止运行')) +}) + +await checkInit() + +/** 初始化事件 */ +async function checkInit() { + /** 日志设置 */ + setLog() + + logger.mark('----^_^----') + logger.mark(logger.yellow(`TRSS-Yunzai v${cfg.package.version} 启动中...`)) + logger.mark(logger.cyan('https://github.com/TimeRainStarSky/Yunzai')) + + await redisInit() + + checkRun() +} diff --git a/Yunzai/lib/config/log.js b/Yunzai/lib/config/log.js new file mode 100644 index 0000000000000000000000000000000000000000..e957e5261db637918df4afc640dcd90a885b556a --- /dev/null +++ b/Yunzai/lib/config/log.js @@ -0,0 +1,98 @@ +import log4js from 'log4js' +import chalk from 'chalk' +import cfg from './config.js' +import fs from 'node:fs' + +/** +* 设置日志样式 +*/ +export default function setLog () { + let file = './logs' + if (!fs.existsSync(file)) { + fs.mkdirSync(file) + } + + /** 调整error日志等级 */ + // log4js.levels.levels[5].level = Number.MAX_VALUE + // log4js.levels.levels.sort((a, b) => a.level - b.level) + + log4js.configure({ + appenders: { + console: { + type: 'console', + layout: { + type: 'pattern', + pattern: '%[[TRSSYz][%d{hh:mm:ss.SSS}][%4.4p]%] %m' + } + }, + command: { + type: 'dateFile', // 可以是console,dateFile,file,Logstash等 + filename: 'logs/command', // 将会按照filename和pattern拼接文件名 + pattern: 'yyyy-MM-dd.log', + numBackups: 15, + alwaysIncludePattern: true, + layout: { + type: 'pattern', + pattern: '[%d{hh:mm:ss.SSS}][%4.4p] %m' + } + }, + error: { + type: 'file', + filename: 'logs/error.log', + alwaysIncludePattern: true, + layout: { + type: 'pattern', + pattern: '[%d{hh:mm:ss.SSS}][%4.4p] %m' + } + } + }, + categories: { + default: { appenders: ['console'], level: cfg.bot.log_level }, + command: { appenders: ['console', 'command'], level: 'warn' }, + error: { appenders: ['console', 'command', 'error'], level: 'error' } + } + }) + + const defaultLogger = log4js.getLogger('message') + const commandLogger = log4js.getLogger('command') + const errorLogger = log4js.getLogger('error') + + /* eslint-disable no-useless-call */ + /** 全局变量 logger */ + global.logger = { + trace () { + defaultLogger.trace.call(defaultLogger, ...arguments) + }, + debug () { + defaultLogger.debug.call(defaultLogger, ...arguments) + }, + info () { + defaultLogger.info.call(defaultLogger, ...arguments) + }, + // warn及以上的日志采用error策略 + warn () { + commandLogger.warn.call(defaultLogger, ...arguments) + }, + error () { + errorLogger.error.call(errorLogger, ...arguments) + }, + fatal () { + errorLogger.fatal.call(errorLogger, ...arguments) + }, + mark () { + errorLogger.mark.call(commandLogger, ...arguments) + } + } + + logColor() +} + +function logColor () { + logger.chalk = chalk + logger.red = chalk.red + logger.green = chalk.green + logger.yellow = chalk.yellow + logger.blue = chalk.blue + logger.magenta = chalk.magenta + logger.cyan = chalk.cyan +} diff --git a/Yunzai/lib/config/redis.js b/Yunzai/lib/config/redis.js new file mode 100644 index 0000000000000000000000000000000000000000..e4b84c0b575f603b0f3c70f91c0a4c1dbc62f138 --- /dev/null +++ b/Yunzai/lib/config/redis.js @@ -0,0 +1,76 @@ +import cfg from "./config.js" +import common from "../common/common.js" +import { createClient } from "redis" +import { exec } from "node:child_process" + +/** + * 初始化全局redis客户端 + */ +export default async function redisInit() { + const rc = cfg.redis + const redisUn = rc.username || "" + let redisPw = rc.password ? `:${rc.password}` : "" + if (rc.username || rc.password) + redisPw += "@" + const redisUrl = `redis://${redisUn}${redisPw}${rc.host}:${rc.port}/${rc.db}` + let client = createClient({ url: redisUrl }) + + try { + logger.info(`正在连接 ${logger.blue(redisUrl)}`) + await client.connect() + } catch (err) { + logger.error(`Redis 错误:${logger.red(err)}`) + + const cmd = "redis-server --save 900 1 --save 300 10 --daemonize yes" + await aarch64() + logger.info("正在启动 Redis...") + await execSync(cmd) + await common.sleep(1000) + + try { + client = createClient({ url: redisUrl }) + await client.connect() + } catch (err) { + logger.error(`Redis 错误:${logger.red(err)}`) + logger.error(`请先启动 Redis:${logger.blue(cmd)}`) + process.exit() + } + } + + client.on("error", async err => { + logger.error(`Redis 错误:${logger.red(err)}`) + const cmd = "redis-server --save 900 1 --save 300 10 --daemonize yes" + await aarch64() + logger.error(`请先启动 Redis:${cmd}`) + process.exit() + }) + + /** 全局变量 redis */ + global.redis = client + logger.info("Redis 连接成功") + return client +} + +async function aarch64() { + if (process.platform == "win32") + return "" + /** 判断arch */ + const arch = await execSync("uname -m") + if (arch.stdout && arch.stdout.includes("aarch64")) { + /** 判断redis版本 */ + let v = await execSync("redis-server -v") + if (v.stdout) { + v = v.stdout.match(/v=(\d)./) + /** 忽略arm警告 */ + if (v && v[1] >= 6) + return " --ignore-warnings ARM64-COW-BUG" + } + } + return "" +} + +function execSync (cmd) { + return new Promise((resolve, reject) => { + exec(cmd, (error, stdout, stderr) => { + resolve({ error, stdout, stderr }) + }) + }) +} \ No newline at end of file diff --git a/Yunzai/lib/events/connect.js b/Yunzai/lib/events/connect.js new file mode 100644 index 0000000000000000000000000000000000000000..46ef1e231a9564c4dd8cae17214bc3d1c7968dce --- /dev/null +++ b/Yunzai/lib/events/connect.js @@ -0,0 +1,23 @@ +import EventListener from "../listener/listener.js" +import cfg from "../config/config.js" + +/** + * 监听连接事件 + */ +export default class connectEvent extends EventListener { + constructor() { + super({ event: "connect" }) + } + + async execute(e) { + if (!Bot.uin.includes(e.self_id)) + Bot.uin.push(e.self_id) + + if (!cfg.bot.online_msg) return + const key = `Yz:loginMsg:${e.self_id}` + if (await redis.get(key)) return + redis.set(key, "1", { EX: cfg.bot.online_msg_exp }) + for (const i of cfg.master[e.self_id] || []) + e.bot.pickFriend(i).sendMsg(`欢迎使用【TRSS-Yunzai v${cfg.package.version}】\n【#帮助】查看指令说明\n【#状态】查看运行状态\n【#日志】查看运行日志\n【#重启】重新启动\n【#更新】拉取 Git 更新\n【#全部更新】更新全部插件\n【#更新日志】查看更新日志\n【#设置主人】设置主人账号\n【#安装插件】查看可安装插件`) + } +} \ No newline at end of file diff --git a/Yunzai/lib/events/message.js b/Yunzai/lib/events/message.js new file mode 100644 index 0000000000000000000000000000000000000000..8084c076bdc9574890a4fab98da03f20879df5f3 --- /dev/null +++ b/Yunzai/lib/events/message.js @@ -0,0 +1,14 @@ +import EventListener from '../listener/listener.js' + +/** + * 监听群聊消息 + */ +export default class messageEvent extends EventListener { + constructor () { + super({ event: 'message' }) + } + + async execute (e) { + this.plugins.deal(e) + } +} \ No newline at end of file diff --git a/Yunzai/lib/events/notice.js b/Yunzai/lib/events/notice.js new file mode 100644 index 0000000000000000000000000000000000000000..8e42c604303afb95bfb207fafabdf98f59fb6460 --- /dev/null +++ b/Yunzai/lib/events/notice.js @@ -0,0 +1,14 @@ +import EventListener from '../listener/listener.js' + +/** + * 监听群聊消息 + */ +export default class noticeEvent extends EventListener { + constructor () { + super({ event: 'notice' }) + } + + async execute (e) { + this.plugins.deal(e) + } +} \ No newline at end of file diff --git a/Yunzai/lib/events/online.js b/Yunzai/lib/events/online.js new file mode 100644 index 0000000000000000000000000000000000000000..9f68eee654c3e05a06b6faf3869af3a198a90589 --- /dev/null +++ b/Yunzai/lib/events/online.js @@ -0,0 +1,18 @@ +import EventListener from '../listener/listener.js' +import cfg from '../config/config.js' + +/** + * 监听上线事件 + */ +export default class onlineEvent extends EventListener { + constructor () { + super({ + event: 'online', + once: true + }) + } + + async execute () { + logger.mark('----^_^----') + } +} \ No newline at end of file diff --git a/Yunzai/lib/events/request.js b/Yunzai/lib/events/request.js new file mode 100644 index 0000000000000000000000000000000000000000..44338f7ab4a7e21d2ff0a0f61d2bb575be3c7074 --- /dev/null +++ b/Yunzai/lib/events/request.js @@ -0,0 +1,14 @@ +import EventListener from '../listener/listener.js' + +/** + * 监听群聊消息 + */ +export default class requestEvent extends EventListener { + constructor () { + super({ event: 'request' }) + } + + async execute (e) { + this.plugins.deal(e) + } +} \ No newline at end of file diff --git a/Yunzai/lib/listener/listener.js b/Yunzai/lib/listener/listener.js new file mode 100644 index 0000000000000000000000000000000000000000..644f7a1bb5ee78279807bce45a6733f333274b74 --- /dev/null +++ b/Yunzai/lib/listener/listener.js @@ -0,0 +1,16 @@ +import PluginsLoader from '../plugins/loader.js' + +export default class EventListener { + /** + * 事件监听 + * @param data.prefix 事件名称前缀 + * @param data.event 监听的事件 + * @param data.once 是否只监听一次 + */ + constructor (data) { + this.prefix = data.prefix || '' + this.event = data.event + this.once = data.once || false + this.plugins = PluginsLoader + } +} \ No newline at end of file diff --git a/Yunzai/lib/listener/loader.js b/Yunzai/lib/listener/loader.js new file mode 100644 index 0000000000000000000000000000000000000000..cbed4fd1ed8fb5a0f2eddfc25c8109bb5d1b69ea --- /dev/null +++ b/Yunzai/lib/listener/loader.js @@ -0,0 +1,57 @@ +import fs from 'node:fs' +import lodash from 'lodash' + +/** + * 加载监听事件 + */ +class ListenerLoader { + /** + * 监听事件加载 + */ + async load () { + logger.info("-----------") + logger.info("加载监听事件中...") + let eventCount = 0 + for (const file of fs.readdirSync('./lib/events').filter(file => file.endsWith('.js'))) { + logger.debug(`加载监听事件:${file}`) + try { + let listener = await import(`../events/${file}`) + if (!listener.default) continue + listener = new listener.default() + const on = listener.once ? 'once' : 'on' + + if (lodash.isArray(listener.event)) { + listener.event.forEach((type) => { + const e = listener[type] ? type : 'execute' + Bot[on](listener.prefix + type, event => listener[e](event)) + }) + } else { + const e = listener[listener.event] ? listener.event : 'execute' + Bot[on](listener.prefix + listener.event, event => listener[e](event)) + } + eventCount++ + } catch (e) { + logger.mark(`监听事件错误:${file}`) + logger.error(e) + } + } + logger.info(`加载监听事件[${eventCount}个]`) + + logger.info("-----------") + logger.info("加载适配器中...") + let adapterCount = 0 + for (const adapter of Bot.adapter) { + try { + logger.debug(`加载适配器:${adapter.name}(${adapter.id})`) + await adapter.load() + adapterCount++ + } catch (e) { + logger.mark(`加载适配器错误:${adapter.name}(${adapter.id})`) + logger.error(e) + } + } + logger.info(`加载适配器[${adapterCount}个]`) + } +} + +export default new ListenerLoader() \ No newline at end of file diff --git a/Yunzai/lib/modules/oicq/index.js b/Yunzai/lib/modules/oicq/index.js new file mode 100644 index 0000000000000000000000000000000000000000..75af0cb556343e22ea3905071637e918248529d2 --- /dev/null +++ b/Yunzai/lib/modules/oicq/index.js @@ -0,0 +1,67 @@ +import fs from "node:fs" +import path from "node:path" + +function toSegment(type, data) { + for (const i in data) { + switch (typeof data[i]) { + case "string": + if ((i == "file" || data[i].match(/^file:\/\//)) && fs.existsSync(data[i].replace(/^file:\/\//, ""))) { + if (i == "file" && !data.name) + data.name = path.basename(data[i]) + data[i] = `base64://${fs.readFileSync(data[i].replace(/^file:\/\//, "")).toString("base64")}` + } + break + case "object": + if (Buffer.isBuffer(data[i])) + data[i] = `base64://${data[i].toString("base64")}` + } + } + return { type, ...data } +} + +const segment = new class segment { + custom(type, data) { + return toSegment(type, data) + } + image(file, name) { + return toSegment("image", { file, name }) + } + at(qq, name) { + return toSegment("at", { qq, name }) + } + record(file, name) { + return toSegment("record", { file, name }) + } + video(file, name) { + return toSegment("video", { file, name }) + } + file(file, name) { + return toSegment("file", { file, name }) + } + reply(id, text, qq, time, seq) { + return toSegment("reply", { id, text, qq, time, seq }) + } + face(id) { + return toSegment("face", { id }) + } + share(url, title, content, image) { + return toSegment("share", { url, title, content, image }) + } + music(type, id, url, audio, title) { + return toSegment("music", { type, id, url, audio, title }) + } + poke(qq) { + return toSegment("poke", { qq }) + } + gift(qq, id) { + return toSegment("gift", { qq, id }) + } + cardimage(file, name, minwidth, minheight, maxwidth, maxheight, source, icon) { + return toSegment("cardimage", { file, name, minwidth, minheight, maxwidth, maxheight, source, icon }) + } + tts(text) { + return toSegment("tts", { text }) + } +} + +export { segment } \ No newline at end of file diff --git a/Yunzai/lib/modules/oicq/package.json b/Yunzai/lib/modules/oicq/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6e44b527415899c53b0f946bccbef187a7229164 --- /dev/null +++ b/Yunzai/lib/modules/oicq/package.json @@ -0,0 +1,5 @@ +{ + "name": "oicq", + "type": "module", + "main": "index.js" +} \ No newline at end of file diff --git a/Yunzai/lib/plugins/handler.js b/Yunzai/lib/plugins/handler.js new file mode 100644 index 0000000000000000000000000000000000000000..a96ebade0a82b9018f94bd0d5060c3304e490657 --- /dev/null +++ b/Yunzai/lib/plugins/handler.js @@ -0,0 +1,73 @@ +import util from 'node:util' +import lodash from 'lodash' + +let events = {} +let Handler = { + add (cfg) { + let { ns, fn, self, property = 50 } = cfg + let key = cfg.key || cfg.event + if (!key || !fn) { + return + } + Handler.del(ns, key) + logger.mark(`[Handler][Reg]: [${ns}][${key}]`) + events[key] = events[key] || [] + events[key].push({ + property, + fn, + ns, + self, + key + }) + events[key] = lodash.orderBy(events[key], ['priority'], ['asc']) + }, + del (ns, key = '') { + if (!key) { + for (let key in events) { + Handler.del(ns, key) + } + return + } + if (!events[key]) { + return + } + for (let idx = 0; idx < events[key].length; idx++) { + let handler = events[key][idx] + if (handler.ns === ns) { + events[key].splice(idx, 1) + events[key] = lodash.orderBy(events[key], ['priority'], ['asc']) + } + } + }, + async callAll (key, e, args) { + // 暂时屏蔽调用 + // return Handler.call(key, e, args, true) + }, + async call (key, e, args, allHandler = false) { + let ret + for (let obj of events[key]) { + let fn = obj.fn + let done = true + let reject = (msg = '') => { + if (msg) { + logger.mark(`[Handler][Reject]: [${obj.ns}][${key}] ${msg}`) + } + done = false + } + ret = fn.call(obj.self, e, args, reject) + if (util.types.isPromise(ret)) { + ret = await ret + } + if (done && !allHandler) { + logger.mark(`[Handler][Done]: [${obj.ns}][${key}]`) + return ret + } + } + return ret + }, + has (key) { + return !!events[key] + } +} +export default Handler + diff --git a/Yunzai/lib/plugins/loader.js b/Yunzai/lib/plugins/loader.js new file mode 100644 index 0000000000000000000000000000000000000000..fce9fa62e3cc67880241a71ea412c70025a615fb --- /dev/null +++ b/Yunzai/lib/plugins/loader.js @@ -0,0 +1,872 @@ +import util from "node:util" +import fs from "node:fs" +import lodash from "lodash" +import cfg from "../config/config.js" +import plugin from "./plugin.js" +import schedule from "node-schedule" +import { segment } from "oicq" +import chokidar from "chokidar" +import moment from "moment" +import path from "node:path" +import common from "../common/common.js" +import Runtime from "./runtime.js" +import Handler from './handler.js' + +/** 全局变量 plugin */ +global.plugin = plugin +global.segment = segment + +/** + * 加载插件 + */ +class PluginsLoader { + constructor() { + this.priority = [] + this.handler = {} + this.task = [] + this.dir = "./plugins" + + /** 命令冷却cd */ + this.groupCD = {} + this.singleCD = {} + + /** 插件监听 */ + this.watcher = {} + + this.msgThrottle = {} + + /** 星铁命令前缀 */ + this.srReg = /^#?(\*|星铁|星轨|穹轨|星穹|崩铁|星穹铁道|崩坏星穹铁道|铁道)+/ + } + + /** + * 监听事件加载 + * @param isRefresh 是否刷新 + */ + async load(isRefresh = false) { + this.delCount() + if (!lodash.isEmpty(this.priority) && !isRefresh) return + + const files = this.getPlugins() + + logger.info("-----------") + logger.info("加载插件中...") + + let pluCount = 0 + + let packageErr = [] + for (let File of files) { + try { + let tmp = await import(File.path) + let apps = tmp + if (tmp.apps) { + apps = { ...tmp.apps } + } + lodash.forEach(apps, (p, i) => { + if (!p.prototype) return + pluCount++ + /* eslint-disable new-cap */ + let plugin = new p() + logger.debug(`载入插件 [${File.name}][${plugin.name}]`) + /** 执行初始化 */ + this.runInit(plugin) + /** 初始化定时任务 */ + this.collectTask(plugin.task) + this.priority.push({ + class: p, + key: File.name, + name: plugin.name, + priority: plugin.priority + }) + if (plugin.handler) { + lodash.forEach(plugin.handler, ({ fn, key, priority }) => { + Handler.add({ + ns: plugin.namespace || File.name, + key: key, + self: plugin, + property: priority || plugin.priority || 500, + fn: plugin[fn] + }) + }) + } + }) + } catch (error) { + if (error.stack.includes("Cannot find package")) { + packageErr.push({ error, File }) + } else { + logger.error(`载入插件错误:${logger.red(File.name)}`) + logger.error(decodeURI(error.stack)) + } + } + } + + this.packageTips(packageErr) + this.creatTask() + + logger.info(`加载定时任务[${this.task.length}个]`) + logger.info(`加载插件[${pluCount}个]`) + + /** 优先级排序 */ + this.priority = lodash.orderBy(this.priority, ["priority"], ["asc"]) + } + + async runInit(plugin) { + plugin.init && plugin.init() + } + + packageTips(packageErr) { + if (!packageErr || packageErr.length <= 0) return + logger.mark("--------插件载入错误--------") + packageErr.forEach(v => { + let pack = v.error.stack.match(/'(.+?)'/g)[0].replace(/'/g, "") + logger.mark(`${v.File.name} 缺少依赖:${logger.red(pack)}`) + logger.mark(`新增插件后请执行安装命令:${logger.red("pnpm i")} 安装依赖`) + logger.mark("如安装后仍未解决可联系插件作者解决") + }) + // logger.error("或者使用其他包管理工具安装依赖") + logger.mark("---------------------") + } + + getPlugins() { + let ignore = ["index.js"] + let files = fs.readdirSync(this.dir, { withFileTypes: true }) + let ret = [] + for (let val of files) { + let filepath = "../../plugins/" + val.name + let tmp = { + name: val.name, + } + if (val.isFile()) { + if (!val.name.endsWith(".js")) continue + if (ignore.includes(val.name)) continue + tmp.path = filepath + ret.push(tmp) + continue + } + + if (fs.existsSync(`${this.dir}/${val.name}/index.js`)) { + tmp.path = filepath + "/index.js" + ret.push(tmp) + continue + } + + let apps = fs.readdirSync(`${this.dir}/${val.name}`, { withFileTypes: true }) + for (let app of apps) { + if (!app.name.endsWith(".js")) continue + if (ignore.includes(app.name)) continue + + ret.push({ + name: `${val.name}/${app.name}`, + path: `../../plugins/${val.name}/${app.name}` + }) + + /** 监听热更新 */ + this.watch(val.name, app.name) + } + } + + return ret + } + + /** + * 处理事件 + * + * 参数文档 https://github.com/TimeRainStarSky/Yunzai/tree/docs + * @param e 事件 + */ + async deal(e) { + /** 检查黑白名单 */ + if (!this.checkBlack(e)) return + /** 冷却 */ + if (!this.checkLimit(e)) return + /** 处理事件 */ + this.dealEvent(e) + /** 处理消息 */ + this.dealMsg(e) + /** 处理回复 */ + this.reply(e) + /** 过滤事件 */ + let priority = [] + /** 注册runtime */ + await Runtime.init(e) + + this.priority.forEach(v => { + let p = new v.class(e) + p.e = e + /** 判断是否启用功能 */ + if (!this.checkDisable(e, p)) return + /** 过滤事件 */ + if (!this.filtEvent(e, p)) return + priority.push(p) + }) + + for (let plugin of priority) { + /** 上下文hook */ + if (plugin.getContext) { + let context = plugin.getContext() + if (!lodash.isEmpty(context)) { + for (let fnc in context) { + plugin[fnc](context[fnc]) + } + return + } + } + + /** 群上下文hook */ + if (plugin.getContextGroup) { + let context = plugin.getContextGroup() + if (!lodash.isEmpty(context)) { + for (let fnc in context) { + plugin[fnc](context[fnc]) + } + return + } + } + } + + /** 是否只关注主动at */ + if (!this.onlyReplyAt(e)) return + + // 判断是否是星铁命令,若是星铁命令则标准化处理 + // e.isSr = true,且命令标准化为 #星铁 开头 + if (this.srReg.test(e.msg)) { + e.isSr = true + e.msg = e.msg.replace(this.srReg, "#星铁") + } + + /** accept */ + for (let plugin of priority) { + /** accept hook */ + if (plugin.accept) { + let res = plugin.accept(e) + + if (util.types.isPromise(res)) res = await res + + if (res === "return") return + + if (res) break + } + } + + /* eslint-disable no-labels */ + a: for (let plugin of priority) { + /** 正则匹配 */ + if (plugin.rule) { + for (let v of plugin.rule) { + /** 判断事件 */ + if (v.event && !this.filtEvent(e, v)) continue + + if (new RegExp(v.reg).test(e.msg)) { + e.logFnc = `[${plugin.name}][${v.fnc}]` + + if (v.log !== false) { + logger.mark(`${e.logFnc}${e.logText} ${lodash.truncate(e.msg, { length: 80 })}`) + } + + /** 判断权限 */ + if (!this.filtPermission(e, v)) break a + + try { + let res = plugin[v.fnc] && plugin[v.fnc](e) + + let start = Date.now() + + if (util.types.isPromise(res)) res = await res + + if (res !== false) { + /** 设置冷却cd */ + this.setLimit(e) + if (v.log !== false) { + logger.mark(`${e.logFnc} ${lodash.truncate(e.msg, { length: 80 })} 处理完成 ${Date.now() - start}ms`) + } + break a + } + } catch (error) { + logger.error(`${e.logFnc}`) + logger.error(error.stack) + break a + } + } + } + } + } + } + + /** 过滤事件 */ + filtEvent(e, v) { + if (!v.event) return false + let event = v.event.split(".") + let eventMap = { + message: ["post_type", "message_type", "sub_type"], + notice: ["post_type", "notice_type", "sub_type"], + request: ["post_type", "request_type", "sub_type"] + } + let newEvent = [] + event.forEach((val, index) => { + if (val === "*") { + newEvent.push(val) + } else if (eventMap[e.post_type]) { + newEvent.push(e[eventMap[e.post_type][index]]) + } + }) + newEvent = newEvent.join(".") + + return v.event === newEvent + } + + /** 判断权限 */ + filtPermission(e, v) { + if (v.permission == "all" || !v.permission) return true + + if (v.permission == "master") { + if (e.isMaster) { + return true + } else { + e.reply("暂无权限,只有主人才能操作") + return false + } + } + + if (e.isGroup) { + if (!e.member?._info) { + e.reply("数据加载中,请稍后再试") + return false + } + if (v.permission == "owner") { + if (!e.member.is_owner) { + e.reply("暂无权限,只有群主才能操作") + return false + } + } + if (v.permission == "admin") { + if (!e.member.is_admin) { + e.reply("暂无权限,只有管理员才能操作") + return false + } + } + } + + return true + } + + dealEvent(e) { + if (!e.friend && e.user_id) e.friend = e.bot.pickFriend(e.user_id) + if (!e.group && e.group_id) e.group = e.bot.pickGroup(e.group_id) + if (!e.member && e.group && e.user_id) e.member = e.group.pickMember(e.user_id) + for (const i of [e.friend, e.group, e.member]) { + if (typeof i != "object") continue + if (!i.makeForwardMsg) i.makeForwardMsg = Bot.makeForwardMsg + if (!i.sendForwardMsg) i.sendForwardMsg = msg => Bot.sendForwardMsg(msg => i.sendMsg(msg), msg) + if (!i.getInfo) i.getInfo = () => i + } + } + + /** + * 处理消息,加入自定义字段 + * @param e.msg 文本消息,多行会自动拼接 + * @param e.img 图片消息数组 + * @param e.atBot 是否at机器人 + * @param e.at 是否at,多个at 以最后的为准 + * @param e.file 接受到的文件 + * @param e.isPrivate 是否私聊 + * @param e.isGroup 是否群聊 + * @param e.isMaster 是否管理员 + * @param e.logText 日志用户字符串 + * @param e.logFnc 日志方法字符串 + */ + dealMsg(e) { + if (e.message) for (const i of e.message) { + switch (i.type) { + case "text": + if (!e.msg) e.msg = "" + if (i.text) e.msg += i.text.replace(/^\s*[##井]+\s*/, "#").replace(/^\s*[\\**※]+\s*/, "*").trim() + break + case "image": + if (Array.isArray(e.img)) + e.img.push(i.url) + else + e.img = [i.url] + break + case "at": + if (i.qq == e.self_id) + e.atBot = true + else + e.at = i.qq + break + case "reply": + e.reply_id = i.id + if (e.group?.getMsg) + e.getReply = () => e.group.getMsg(e.reply_id) + else if (e.friend?.getMsg) + e.getReply = () => e.friend.getMsg(e.reply_id) + break + case "file": + e.file = i + break + } + } + + e.logText = "" + + if (e.message_type == "private" || e.notice_type == "friend") { + e.isPrivate = true + + if (e.sender) { + e.sender.card = e.sender.nickname + } else { + e.sender = { + card: e.friend?.nickname, + nickname: e.friend?.nickname + } + } + + e.logText = `[${e.sender?.nickname ? `${e.sender.nickname}(${e.user_id})` : e.user_id}]` + } + + if (e.message_type == "group" || e.notice_type == "group") { + e.isGroup = true + if (e.sender) { + e.sender.card = e.sender.card || e.sender.nickname + } else if (e.member) { + e.sender = { + card: e.member.card || e.member.nickname + } + } else if (e.nickname) { + e.sender = { + card: e.nickname, + nickname: e.nickname + } + } else { + e.sender = { + card: "", + nickname: "" + } + } + + if (!e.group_name) e.group_name = e.group?.name + + e.logText = `[${e.group_name ? `${e.group_name}(${e.group_id})` : e.group_id}, ${e.sender?.nickname ? `${e.sender.nickname}(${e.user_id})` : e.user_id}]` + } + + if (e.user_id && cfg.master[e.self_id]?.includes(String(e.user_id))) { + e.isMaster = true + } + + /** 只关注主动at msg处理 */ + if (e.msg && e.isGroup) { + let groupCfg = cfg.getGroup(e.self_id, e.group_id) + let alias = groupCfg.botAlias + if (!Array.isArray(alias)) { + alias = [alias] + } + for (let name of alias) { + if (e.msg.startsWith(name)) { + e.msg = lodash.trimStart(e.msg, name).trim() + e.hasAlias = true + break + } + } + } + } + + /** 处理回复,捕获发送失败异常 */ + reply(e) { + if (e.reply) + e.replyNew = e.reply + else + e.replyNew = msg => { + if (e.isGroup) { + if (e.group?.sendMsg) { + return e.group.sendMsg(msg) + } else { + return e.bot.pickGroup(e.group_id).sendMsg(msg) + } + } else { + if (e.friend?.sendMsg) { + return e.friend.sendMsg(msg) + } else { + return e.bot.pickFriend(e.user_id).sendMsg(msg) + } + } + } + + /** + * @param msg 发送的消息 + * @param quote 是否引用回复 + * @param data.recallMsg 是否撤回消息,0-120秒,0不撤回 + * @param data.at 是否提及用户 + */ + e.reply = async (msg = "", quote = false, data = {}) => { + if (!msg) return false + + let { recallMsg = 0, at = "" } = data + + if (at) { + if (at === true) + at = e.user_id + if (Array.isArray(msg)) + msg.unshift(segment.at(at)) + else + msg = [segment.at(at), msg] + } + + if (quote && e.message_id) { + if (Array.isArray(msg)) + msg.unshift(segment.reply(e.message_id)) + else + msg = [segment.reply(e.message_id), msg] + } + + let res + try { + res = await e.replyNew(msg) + } catch (err) { + if (typeof msg != "string") + msg = lodash.truncate(JSON.stringify(msg), { length: 300 }) + logger.error(`发送消息错误:${msg}`) + logger.error(err) + } + + if (recallMsg > 0 && res?.message_id) { + if (e.group?.recallMsg) + setTimeout(() => { + e.group.recallMsg(res.message_id) + if (e.message_id) + e.group.recallMsg(e.message_id) + }, recallMsg * 1000) + else if (e.friend?.recallMsg) + setTimeout(() => { + e.friend.recallMsg(res.message_id) + if (e.message_id) + e.friend.recallMsg(e.message_id) + }, recallMsg * 1000) + } + + this.count(e, msg) + return res + } + } + + count(e, msg) { + let screenshot = false + if (msg && msg?.file) + screenshot = true + + this.saveCount("sendMsg") + if (screenshot) + this.saveCount("screenshot") + + if (e.group_id) { + this.saveCount("sendMsg", e.group_id) + if (screenshot) + this.saveCount("screenshot", e.group_id) + } + } + + saveCount(type, groupId = "") { + let key = "Yz:count:" + + if (groupId) { + key += `group:${groupId}:` + } + + let dayKey = `${key}${type}:day:${moment().format("MMDD")}` + let monthKey = `${key}${type}:month:${Number(moment().month()) + 1}` + let totalKey = `${key}${type}:total` + + redis.incr(dayKey) + redis.incr(monthKey) + if (!groupId) redis.incr(totalKey) + redis.expire(dayKey, 3600 * 24 * 30) + redis.expire(monthKey, 3600 * 24 * 30) + } + + delCount() { + let key = "Yz:count:" + redis.set(`${key}sendMsg:total`, "0") + redis.set(`${key}screenshot:total`, "0") + } + + /** 收集定时任务 */ + collectTask(task) { + if (Array.isArray(task)) { + task.forEach((val) => { + if (!val.cron) return + if (!val.name) throw new Error("插件任务名称错误") + this.task.push(val) + }) + } else { + if (task.fnc && task.cron) { + if (!task.name) throw new Error("插件任务名称错误") + this.task.push(task) + } + } + } + + /** 创建定时任务 */ + creatTask() { + if (process.argv[1].includes("test")) return + this.task.forEach((val) => { + val.job = schedule.scheduleJob(val.cron, async () => { + try { + if (val.log === true) { + logger.mark(`开始定时任务:${val.name}`) + } + let res = val.fnc() + if (util.types.isPromise(res)) res = await res + if (val.log === true) { + logger.mark(`定时任务完成:${val.name}`) + } + } catch (error) { + logger.error(`定时任务报错:${val.name}`) + logger.error(error) + } + }) + }) + } + + /** 检查命令冷却cd */ + checkLimit(e) { + /** 禁言中 */ + if (e.isGroup && e?.group?.mute_left > 0) return false + if (!e.message || e.isPrivate) return true + + let config = cfg.getGroup(e.self_id, e.group_id) + + if (config.groupCD && this.groupCD[e.group_id]) { + return false + } + if (config.singleCD && this.singleCD[`${e.group_id}.${e.user_id}`]) { + return false + } + + let { msgThrottle } = this + + let msgId = e.user_id + ':' + e.raw_message + if (msgThrottle[msgId]) { + return false + } + msgThrottle[msgId] = true + setTimeout(() => { + delete msgThrottle[msgId] + }, 200) + + return true + } + + /** 设置冷却cd */ + setLimit(e) { + if (!e.message || e.isPrivate) return + let config = cfg.getGroup(e.self_id, e.group_id) + + if (config.groupCD) { + this.groupCD[e.group_id] = true + setTimeout(() => { + delete this.groupCD[e.group_id] + }, config.groupCD) + } + if (config.singleCD) { + let key = `${e.group_id}.${e.user_id}` + this.singleCD[key] = true + setTimeout(() => { + delete this.singleCD[key] + }, config.singleCD) + } + } + + /** 是否只关注主动at */ + onlyReplyAt(e) { + if (!e.message || e.isPrivate) return true + + let groupCfg = cfg.getGroup(e.self_id, e.group_id) + + if (groupCfg.onlyReplyAt != 1 || !groupCfg.botAlias) return true + + /** at机器人 */ + if (e.atBot) return true + + /** 消息带前缀 */ + if (e.hasAlias) return true + + return false + } + + /** 判断黑白名单 */ + checkBlack(e) { + let other = cfg.getOther() + + if (e.test) return true + + /** 黑名单qq */ + if (other.blackQQ?.length && other.blackQQ.includes(Number(e.user_id) || String(e.user_id))) { + return false + } + + if (e.group_id) { + /** 白名单群 */ + if (other.whiteGroup?.length) { + if (other.whiteGroup.includes(Number(e.group_id) || String(e.group_id))) return true + return false + } + /** 黑名单群 */ + if (other.blackGroup?.length && other.blackGroup.includes(Number(e.group_id) || String(e.group_id))) { + return false + } + } + + return true + } + + /** 判断是否启用功能 */ + checkDisable(e, p) { + let groupCfg = cfg.getGroup(e.self_id, e.group_id) + if (!lodash.isEmpty(groupCfg.enable)) { + if (groupCfg.enable.includes(p.name)) { + return true + } + // logger.debug(`${e.logText}[${p.name}]功能已禁用`) + return false + } + + if (!lodash.isEmpty(groupCfg.disable)) { + if (groupCfg.disable.includes(p.name)) { + // logger.debug(`${e.logText}[${p.name}]功能已禁用`) + return false + } + + return true + } + return true + } + + /** 监听热更新 */ + watch(dirName, appName) { + this.watchDir(dirName) + if (this.watcher[`${dirName}.${appName}`]) return + + let file = `./plugins/${dirName}/${appName}` + const watcher = chokidar.watch(file) + let key = `${dirName}/${appName}` + + /** 监听修改 */ + watcher.on("change", async path => { + logger.mark(`[修改插件][${dirName}][${appName}]`) + + let tmp = {} + try { + tmp = await import(`../../plugins/${dirName}/${appName}?${moment().format("x")}`) + } catch (error) { + logger.error(`载入插件错误:${logger.red(dirName + "/" + appName)}`) + logger.error(decodeURI(error.stack)) + return + } + + if (tmp.apps) tmp = { ...tmp.apps } + lodash.forEach(tmp, (p) => { + /* eslint-disable new-cap */ + let plugin = new p() + for (let i in this.priority) { + if (this.priority[i].key == key) { + this.priority[i].class = p + this.priority[i].priority = plugin.priority + } + } + + if (plugin.handler) { + lodash.forEach(plugin.handler, ({ fn, key, priority }) => { + Handler.add({ + ns: plugin.namespace || File.name, + key: key, + self: plugin, + property: priority || plugin.priority || 500, + fn: plugin[fn] + }) + }) + } + }) + + this.priority = lodash.orderBy(this.priority, ["priority"], ["asc"]) + }) + + /** 监听删除 */ + watcher.on("unlink", async path => { + logger.mark(`[卸载插件][${dirName}][${appName}]`) + for (let i in this.priority) { + if (this.priority[i].key == key) { + this.priority.splice(i, 1) + /** 停止更新监听 */ + this.watcher[`${dirName}.${appName}`].removeAllListeners("change") + break + } + } + }) + + this.watcher[`${dirName}.${appName}`] = watcher + } + + /** 监听文件夹更新 */ + watchDir(dirName) { + if (this.watcher[dirName]) return + + let file = `./plugins/${dirName}/` + const watcher = chokidar.watch(file) + + /** 热更新 */ + setTimeout(() => { + /** 新增文件 */ + watcher.on("add", async PluPath => { + let appName = path.basename(PluPath) + if (!appName.endsWith(".js")) return + if (!fs.existsSync(`${this.dir}/${dirName}/${appName}`)) return + + let key = `${dirName}/${appName}` + + this.watch(dirName, appName) + + /** 太快了延迟下 */ + await common.sleep(500) + + logger.mark(`[新增插件][${dirName}][${appName}]`) + let tmp = {} + try { + tmp = await import(`../../plugins/${dirName}/${appName}?${moment().format("X")}`) + } catch (error) { + logger.error(`载入插件错误:${logger.red(dirName + "/" + appName)}`) + logger.error(decodeURI(error.stack)) + return + } + + if (tmp.apps) tmp = { ...tmp.apps } + + lodash.forEach(tmp, (p) => { + if (!p.prototype) { + logger.error(`[载入失败][${dirName}][${appName}] 格式错误已跳过`) + return + } + /* eslint-disable new-cap */ + let plugin = new p() + + for (let i in this.priority) { + if (this.priority[i].key == key) { + return + } + } + + this.priority.push({ + class: p, + key, + name: plugin.name, + priority: plugin.priority + }) + }) + + /** 优先级排序 */ + this.priority = lodash.orderBy(this.priority, ["priority"], ["asc"]) + }) + }, 500) + + this.watcher[dirName] = watcher + } +} + +export default new PluginsLoader() \ No newline at end of file diff --git a/Yunzai/lib/plugins/plugin.js b/Yunzai/lib/plugins/plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..b4874ba2c3579a6961b6c58a61b590319f23c2a6 --- /dev/null +++ b/Yunzai/lib/plugins/plugin.js @@ -0,0 +1,119 @@ +let stateArr = {} + +export default class plugin { + /** + * @param name 插件名称 + * @param dsc 插件描述 + * @param handler handler配置 + * @param handler.key handler支持的事件key + * @param handler.fn handler的处理func + * @param namespace namespace,设置handler时建议设置 + * @param event 执行事件,默认message + * @param priority 优先级,数字越小优先级越高 + * @param rule + * @param rule.reg 命令正则 + * @param rule.fnc 命令执行方法 + * @param rule.event 执行事件,默认message + * @param rule.log false时不显示执行日志 + * @param rule.permission 权限 master,owner,admin,all + * @param task + * @param task.name 定时任务名称 + * @param task.cron 定时任务cron表达式 + * @param task.fnc 定时任务方法名 + * @param task.log false时不显示执行日志 + */ + constructor ({ + name = 'your-plugin', + dsc = '无', + handler, + namespace, + event = 'message', + priority = 5000, + task = { fnc: '', cron: '' }, + rule = [] + }) { + /** 插件名称 */ + this.name = name + /** 插件描述 */ + this.dsc = dsc + /** 监听事件,默认message https://oicqjs.github.io/oicq/#events */ + this.event = event + /** 优先级 */ + this.priority = priority + /** 定时任务,可以是数组 */ + this.task = { + /** 任务名 */ + name: '', + /** 任务方法名 */ + fnc: task.fnc || '', + /** 任务cron表达式 */ + cron: task.cron || '' + } + /** 命令规则 */ + this.rule = rule + + if (handler) { + this.handler = handler + this.namespace = namespace || '' + } + } + + /** + * @param msg 发送的消息 + * @param quote 是否引用回复 + * @param data.recallMsg 群聊是否撤回消息,0-120秒,0不撤回 + * @param data.at 是否at用户 + */ + reply (msg = '', quote = false, data = {}) { + if (!this.e.reply || !msg) return false + return this.e.reply(msg, quote, data) + } + + conKey (isGroup = false) { + if (isGroup) { + return `${this.name}.${this.e.group_id}` + } else { + return `${this.name}.${this.userId || this.e.user_id}` + } + } + + /** + * @param type 执行方法 + * @param isGroup 是否群聊 + * @param time 操作时间,默认120秒 + */ + setContext (type, isGroup = false, time = 120) { + let key = this.conKey(isGroup) + if (!stateArr[key]) stateArr[key] = {} + stateArr[key][type] = this.e + if (time) { + /** 操作时间 */ + setTimeout(() => { + if (stateArr[key][type]) { + delete stateArr[key][type] + this.e.reply('操作超时已取消', true) + } + }, time * 1000) + } + } + + getContext () { + let key = this.conKey() + return stateArr[key] + } + + getContextGroup () { + let key = this.conKey(true) + return stateArr[key] + } + + /** + * @param type 执行方法 + * @param isGroup 是否群聊 + */ + finish (type, isGroup = false) { + if (stateArr[this.conKey(isGroup)] && stateArr[this.conKey(isGroup)][type]) { + delete stateArr[this.conKey(isGroup)][type] + } + } +} diff --git a/Yunzai/lib/plugins/runtime.js b/Yunzai/lib/plugins/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..21b2d46074ee823ac0d00af1a4860c4f7caf0cf1 --- /dev/null +++ b/Yunzai/lib/plugins/runtime.js @@ -0,0 +1,245 @@ +/** + * plugin的runtime,可通过e.runtime访问 + * + * 提供一些常用的运行时变量、方法及model获取 + * 降低对目录结构的依赖 + */ +import lodash from 'lodash' +import fs from 'node:fs' +import gsCfg from '../../plugins/genshin/model/gsCfg.js' +import common from '../common/common.js' +import cfg from '../config/config.js' +import MysApi from '../../plugins/genshin/model/mys/mysApi.js' +import MysInfo from '../../plugins/genshin/model/mys/mysInfo.js' +import puppeteer from '../puppeteer/puppeteer.js' +import { Version } from '#miao' +import NoteUser from '../../plugins/genshin/model/mys/NoteUser.js' +import MysUser from '../../plugins/genshin/model/mys/MysUser.js' +import Handler from './handler.js' + +/** + * 常用的处理方法 + */ + +export default class Runtime { + constructor (e) { + this.e = e + this._mysInfo = {} + + this.handler = { + has: Handler.has, + call: Handler.call, + callAll: Handler.callAll + } + } + + get uid () { + return this.user?.uid + } + + get hasCk () { + return this.user?.hasCk + } + + get user () { + return this.e.user + } + + get cfg () { + return cfg + } + + get gsCfg () { + return gsCfg + } + + get common () { + return common + } + + get puppeteer () { + return puppeteer + } + + get MysInfo () { + return MysInfo + } + + get NoteUser () { + return NoteUser + } + + get MysUser () { + return MysUser + } + + static async init (e) { + await MysInfo.initCache() + let runtime = new Runtime(e) + e.runtime = runtime + e.game = e.isSr ? 'sr' : 'gs' + await runtime.initUser() + return runtime + } + + async initUser () { + let e = this.e + let user = await NoteUser.create(e) + if (user) { + e.user = new Proxy(user, { + get (self, key, receiver) { + let game = e.isSr ? 'sr' : 'gs' + let fnMap = { + uid: 'getUid', + uidList: 'getUidList', + mysUser: 'getMysUser', + ckUidList: 'getCkUidList' + } + if (fnMap[key]) { + return self[fnMap[key]](game) + } + if (key === 'uidData') { + return self.getUidData('', game) + } + if (['getUid', 'getUidList', 'getMysUser', 'getCkUidList', 'getUidMapList', 'getGameDs'].includes(key)) { + return (_game, arg2) => { + return self[key](_game || game, arg2) + } + } + if (['getUidData', 'hasUid', 'addRegUid', 'delRegUid', 'setMainUid'].includes(key)) { + return (uid, _game = '') => { + return self[key](uid, _game || game) + } + } + return self[key] + } + }) + } + } + + /** + * 获取MysInfo实例 + * + * @param targetType all: 所有用户均可, cookie:查询用户必须具备Cookie + * @returns {Promise} + */ + async getMysInfo (targetType = 'all') { + if (!this._mysInfo[targetType]) { + this._mysInfo[targetType] = await MysInfo.init(this.e, targetType === 'cookie' ? 'detail' : 'roleIndex') + } + return this._mysInfo[targetType] + } + + async getUid () { + return await MysInfo.getUid(this.e) + } + + /** + * 获取MysApi实例 + * + * @param targetType all: 所有用户均可, cookie:查询用户必须具备Cookie + * @param option MysApi option + * @returns {Promise} + */ + async getMysApi (targetType = 'all', option = {}) { + let mys = await this.getMysInfo(targetType) + if (mys.uid && mys?.ckInfo?.ck) { + return new MysApi(mys.uid, mys.ckInfo.ck, option) + } + return false + } + + /** + * 生成MysApi实例 + * @param uid + * @param ck + * @param option + * @returns {Promise} + */ + async createMysApi (uid, ck, option) { + return new MysApi(uid, ck, option) + } + + /** + * + * @param plugin plugin key + * @param path html文件路径,相对于plugin resources目录 + * @param data 渲染数据 + * @param cfg 渲染配置 + * @param cfg.retType 返回值类型 + * * default/空:自动发送图片,返回true + * * msgId:自动发送图片,返回msg id + * * base64: 不自动发送图像,返回图像base64数据 + * @param cfg.beforeRender({data}) 可改写渲染的data数据 + * @returns {Promise} + */ + async render (plugin, path, data = {}, cfg = {}) { + // 处理传入的path + path = path.replace(/.html$/, '') + let paths = lodash.filter(path.split('/'), (p) => !!p) + path = paths.join('/') + // 创建目录 + const mkdir = (check) => { + let currDir = `${process.cwd()}/temp` + for (let p of check.split('/')) { + currDir = `${currDir}/${p}` + if (!fs.existsSync(currDir)) { + fs.mkdirSync(currDir) + } + } + return currDir + } + mkdir(`html/${plugin}/${path}`) + // 自动计算pluResPath + let pluResPath = `../../../${lodash.repeat('../', paths.length)}plugins/${plugin}/resources/` + let miaoResPath = `../../../${lodash.repeat('../', paths.length)}plugins/miao-plugin/resources/` + const layoutPath = process.cwd() + '/plugins/miao-plugin/resources/common/layout/' + // 渲染data + data = { + sys: { + scale: 1 + }, + /** miao 相关参数 **/ + copyright: `Created By TRSS-Yunzai${Version.yunzai} `, + _res_path: pluResPath, + _miao_path: miaoResPath, + _tpl_path: process.cwd() + '/plugins/miao-plugin/resources/common/tpl/', + defaultLayout: layoutPath + 'default.html', + elemLayout: layoutPath + 'elem.html', + + ...data, + + /** 默认参数 **/ + _plugin: plugin, + _htmlPath: path, + pluResPath, + tplFile: `./plugins/${plugin}/resources/${path}.html`, + saveId: data.saveId || data.save_id || paths[paths.length - 1], + pageGotoParams: { + waitUntil: 'networkidle2' + } + } + // 处理beforeRender + if (cfg.beforeRender) { + data = cfg.beforeRender({ data }) || data + } + // 保存模板数据 + if (process.argv.includes('dev')) { + // debug下保存当前页面的渲染数据,方便模板编写与调试 + // 由于只用于调试,开发者只关注自己当时开发的文件即可,暂不考虑app及plugin的命名冲突 + let saveDir = mkdir(`ViewData/${plugin}`) + let file = `${saveDir}/${data._htmlPath.split('/').join('_')}.json` + fs.writeFileSync(file, JSON.stringify(data)) + } + // 截图 + let base64 = await puppeteer.screenshot(`${plugin}/${path}`, data) + if (cfg.retType === 'base64') { + return base64 + } + let ret = true + if (base64) { + ret = await this.e.reply(base64) + } + return cfg.retType === 'msgId' ? ret : true + } +} diff --git a/Yunzai/lib/plugins/stdin.js b/Yunzai/lib/plugins/stdin.js new file mode 100644 index 0000000000000000000000000000000000000000..1212fc70a97b20a87009189bb34665ee377b4d14 --- /dev/null +++ b/Yunzai/lib/plugins/stdin.js @@ -0,0 +1,159 @@ +import fetch from "node-fetch" +import fs from "node:fs" +import path from "node:path" +import common from "../common/common.js" +import { fileTypeFromBuffer } from "file-type" + +Bot.adapter.push(new class stdinAdapter { + constructor() { + this.id = "stdin" + this.name = "标准输入" + this.path = "data/stdin/" + common.mkdirs(this.path) + } + + async makeBuffer(file) { + if (file.match(/^base64:\/\//)) + return Buffer.from(file.replace(/^base64:\/\//, ""), "base64") + else if (file.match(/^https?:\/\//)) + return Buffer.from(await (await fetch(file)).arrayBuffer()) + else if (fs.existsSync(file)) + return Buffer.from(fs.readFileSync(file)) + return file + } + + async fileType(data) { + const file = {} + try { + file.url = data.replace(/^base64:\/\/.*/, "base64://...") + file.buffer = await this.makeBuffer(data) + file.type = await fileTypeFromBuffer(file.buffer) + file.path = `${this.path}${Date.now()}.${file.type.ext}` + } catch (err) { + logger.error(`文件类型检测错误:${logger.red(err)}`) + } + return file + } + + async sendMsg(msg) { + if (!Array.isArray(msg)) + msg = [msg] + for (let i of msg) { + if (typeof i != "object") + i = { type: "text", data: { text: i }} + else if (!i.data) + i = { type: i.type, data: { ...i, type: undefined }} + + let file + if (i.data.file) + file = await this.fileType(i.data.file) + + switch (i.type) { + case "text": + if (i.data.text.match("\n")) + i.data.text = `\n${i.data.text}` + logger.info(`${logger.blue(`[${this.id}]`)} 发送文本:${i.data.text}`) + break + case "image": + logger.info(`${logger.blue(`[${this.id}]`)} 发送图片:${file.url}\n文件已保存到:${logger.cyan(file.path)}`) + fs.writeFileSync(file.path, file.buffer) + break + case "record": + logger.info(`${logger.blue(`[${this.id}]`)} 发送音频:${file.url}\n文件已保存到:${logger.cyan(file.path)}`) + fs.writeFileSync(file.path, file.buffer) + break + case "video": + logger.info(`${logger.blue(`[${this.id}]`)} 发送视频:${file.url}\n文件已保存到:${logger.cyan(file.path)}`) + fs.writeFileSync(file.path, file.buffer) + break + case "reply": + break + case "at": + break + case "node": + Bot.sendForwardMsg(msg => this.sendMsg(msg), i.data) + break + default: + i = JSON.stringify(i) + if (i.match("\n")) + i = `\n${i}` + logger.info(`${logger.blue(`[${this.id}]`)} 发送消息:${i}`) + } + } + return { message_id: Date.now() } + } + + recallMsg(message_id) { + logger.info(`${logger.blue(`[${this.id}]`)} 撤回消息:${message_id}`) + } + + async sendFile(file, name = path.basename(file)) { + const buffer = await this.makeBuffer(file) + if (!Buffer.isBuffer(buffer)) { + logger.error(`${logger.blue(`[${this.id}]`)} 发送文件错误:找不到文件 ${logger.red(file)}`) + return false + } + + const files = `${this.path}${Date.now()}-${name}` + logger.info(`${logger.blue(`[${this.id}]`)} 发送文件:${file}\n文件已保存到:${logger.cyan(files)}`) + return fs.writeFileSync(files, buffer) + } + + pickFriend() { + return { + user_id: this.id, + nickname: this.name, + group_id: this.id, + group_name: this.name, + sendMsg: msg => this.sendMsg(msg), + recallMsg: message_id => this.recallMsg(message_id), + sendFile: (file, name) => this.sendFile(file, name), + } + } + + message(msg) { + const data = { + bot: Bot[this.id], + self_id: this.id, + user_id: this.id, + post_type: "message", + message_type: "private", + sender: { user_id: this.id, nickname: this.name }, + message: [{ type: "text", text: msg }], + raw_message: msg, + friend: this.pickFriend(), + } + logger.info(`${logger.blue(`[${data.self_id}]`)} 系统消息:[${data.sender.nickname}(${data.user_id})] ${data.raw_message}`) + + Bot.em(`${data.post_type}.${data.message_type}`, data) + } + + load() { + Bot[this.id] = { + adapter: this, + uin: this.id, + nickname: this.name, + stat: { start_time: Date.now()/1000 }, + version: { id: this.id, name: this.name }, + pickFriend: () => this.pickFriend(), + get pickUser() { return this.pickFriend }, + get pickMember() { return this.pickFriend }, + get pickGroup() { return this.pickFriend }, + + fl: new Map().set(this.id, { + user_id: this.id, + nickname: this.name, + group_id: this.id, + group_name: this.name, + }), + get gl() { return this.fl }, + gml: new Map, + } + Bot[this.id].gml.set(this.id, Bot[this.id].fl) + + process[this.id].on("data", data => this.message(data.toString())) + + logger.mark(`${logger.blue(`[${this.id}]`)} ${this.name}(${this.id}) 已连接`) + Bot.em(`connect.${this.id}`, { self_id: this.id }) + } +}) \ No newline at end of file diff --git a/Yunzai/lib/puppeteer/puppeteer.js b/Yunzai/lib/puppeteer/puppeteer.js new file mode 100644 index 0000000000000000000000000000000000000000..11e06fc81f7da08ceaa4a302677e636e5d5e40b9 --- /dev/null +++ b/Yunzai/lib/puppeteer/puppeteer.js @@ -0,0 +1,23 @@ +import Renderer from '../renderer/loader.js' + +/** + * 暂时保留对手工引用puppeteer.js的兼容 + * 后期会逐步废弃 + * 只提供截图及分片截图功能 + */ +let renderer = Renderer.getRenderer() +renderer.screenshot = async (name, data) => { + let img = await renderer.render(name, data) + return img ? segment.image(img) : img +} +renderer.screenshots = async (name, data) => { + data.multiPage = true + let imgs = await renderer.render(name, data) || [] + let ret = [] + for (let img of imgs) { + ret.push(img ? segment.image(img) : img) + } + return ret.length > 0 ? ret : false +} + +export default renderer \ No newline at end of file diff --git a/Yunzai/lib/renderer/Renderer.js b/Yunzai/lib/renderer/Renderer.js new file mode 100644 index 0000000000000000000000000000000000000000..a6dfe14d7de8bde78d33f6c047f01b4b43da3976 --- /dev/null +++ b/Yunzai/lib/renderer/Renderer.js @@ -0,0 +1,82 @@ +import template from 'art-template' +import chokidar from 'chokidar' +import path from 'node:path' +import fs from 'node:fs' + +export default class Renderer { + /** + * 渲染器 + * @param data.id 渲染器ID + * @param data.type 渲染器类型 + * @param data.render 渲染器入口 + */ + constructor(data) { + /** 渲染器ID */ + this.id = data.id || 'renderer' + /** 渲染器类型 */ + this.type = data.type || 'image' + /** 渲染器入口 */ + this.render = this[data.render || 'render'] + this.dir = './temp/html' + this.html = {} + this.watcher = {} + this.createDir(this.dir) + } + + /** 创建文件夹 */ + createDir(dirname) { + if (fs.existsSync(dirname)) { + return true + } else { + if (this.createDir(path.dirname(dirname))) { + fs.mkdirSync(dirname) + return true + } + } + } + + /** 模板 */ + dealTpl(name, data) { + let { tplFile, saveId = name } = data + let savePath = `./temp/html/${name}/${saveId}.html` + + /** 读取html模板 */ + if (!this.html[tplFile]) { + this.createDir(`./temp/html/${name}`) + + try { + this.html[tplFile] = fs.readFileSync(tplFile, 'utf8') + } catch (error) { + logger.error(`加载html错误:${tplFile}`) + return false + } + + this.watch(tplFile) + } + + data.resPath = `./resources/` + + /** 替换模板 */ + let tmpHtml = template.render(this.html[tplFile], data) + + /** 保存模板 */ + fs.writeFileSync(savePath, tmpHtml) + + logger.debug(`[图片生成][使用模板] ${savePath}`) + + return savePath + } + + /** 监听配置文件 */ + watch(tplFile) { + if (this.watcher[tplFile]) return + + const watcher = chokidar.watch(tplFile) + watcher.on('change', path => { + delete this.html[tplFile] + logger.mark(`[修改html模板] ${tplFile}`) + }) + + this.watcher[tplFile] = watcher + } +} \ No newline at end of file diff --git a/Yunzai/lib/renderer/loader.js b/Yunzai/lib/renderer/loader.js new file mode 100644 index 0000000000000000000000000000000000000000..f7506119c70c1171bd9e82a74772f7234f419d7d --- /dev/null +++ b/Yunzai/lib/renderer/loader.js @@ -0,0 +1,56 @@ +import fs from 'node:fs' +import yaml from 'yaml' +import lodash from 'lodash' +import cfg from '../config/config.js' +import { Data } from '#miao' +import Renderer from './Renderer.js' + +/** 全局变量 Renderer */ +global.Renderer = Renderer + +/** + * 加载渲染器 + */ +class RendererLoader { + constructor() { + this.renderers = new Map() + this.dir = './renderers' + // TODO 渲染器热加载 + this.watcher = {} + } + + static async init() { + const render = new RendererLoader() + await render.load() + return render + } + + async load() { + const subFolders = fs.readdirSync(this.dir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()) + for (let subFolder of subFolders) { + let name = subFolder.name + try { + const rendererFn = await Data.importDefault(`${this.dir}/${name}/index.js`) + let configFile = `${this.dir}/${name}/config.yaml` + let rendererCfg = fs.existsSync(configFile) ? yaml.parse(fs.readFileSync(configFile, 'utf8')) : {} + let renderer = rendererFn(rendererCfg) + if (!renderer.id || !renderer.type || !renderer.render || !lodash.isFunction(renderer.render)) { + logger.warn('渲染后端 ' + (renderer.id || subFolder.name) + ' 不可用') + } + this.renderers.set(renderer.id, renderer) + logger.info(`加载渲染后端 ${renderer.id}`) + } catch (err) { + logger.error(`渲染后端 ${name} 加载失败`) + logger.error(err) + } + } + } + + getRenderer(name = cfg.renderer?.name || 'puppeteer') { + // TODO 渲染器降级 + return this.renderers.get(name) + } +} + + +export default await RendererLoader.init() \ No newline at end of file diff --git a/Yunzai/lib/tools/command.js b/Yunzai/lib/tools/command.js new file mode 100644 index 0000000000000000000000000000000000000000..1451294c73034e1b357b4f57c668629a6d737f34 --- /dev/null +++ b/Yunzai/lib/tools/command.js @@ -0,0 +1,118 @@ + +import '../config/init.js' +import log4js from 'log4js' +import PluginsLoader from '../plugins/loader.js' +import cfg from '../config/config.js' + +class Command { + constructor () { + this.command = '' + // this.setLog() + /** 全局Bot */ + global.Bot = {} + } + + /** + * @param type 命令配置类型,默认default + */ + async run (type = 'default') { + /** 加载icqq事件监听 */ + await PluginsLoader.load() + /** 获取命令行参数 */ + this.getCommand() + /** 伪造消息 */ + let e = this.fakeE(type) + + /** 插件处理消息 */ + await PluginsLoader.deal(e) + } + + /** 设置命令 */ + getCommand () { + if (process.argv[2]) { + this.command = '#' + process.argv[2].replace(/#|#|井/g, '#').trim() + } + } + + fakeE (id = 'default') { + /** 获取配置 */ + let data = cfg.getYaml('test', id) + let text = this.command || data.text || '' + logger.info(`测试命令 [${text}]`) + let e = { + test: true, + self_id: 10000, + time: new Date().getTime(), + post_type: data.post_type || 'message', + message_type: data.message_type || 'group', + sub_type: data.sub_type || 'normal', + group_id: data.group_id || 826198224, + group_name: data.group_name || '测试群', + user_id: data.user_id, + anonymous: null, + message: [{ type: 'text', text }], + raw_message: text, + font: '微软雅黑', + sender: { + user_id: data.user_id, + nickname: '测试', + card: data.card, + sex: 'male', + age: 0, + area: 'unknown', + level: 2, + role: 'owner', + title: '' + }, + group: { + mute_left: 0, + sendMsg: (msg) => { + logger.info(`回复内容 ${msg}`) + } + }, + friend: { + getFileUrl: (fid) => { + return data.message[0].url + } + }, + message_id: 'JzHU0DACliIAAAD3RzTh1WBOIC48', + reply: async (msg) => { + logger.info(`回复内容 ${msg}`) + }, + toString: () => { + return text + } + } + + if (data.message) { + e.message = data.message + } + + return e + } + + /** 日志 */ + setLog () { + log4js.configure({ + appenders: { + // 设置控制台输出 (默认日志级别是关闭的(即不会输出日志)) + out: { + type: 'console', + layout: { + type: 'pattern', + pattern: '[%d{hh:mm:ss.SSS}][%[%5.5p%]] - %m' + } + } + }, + // 不同等级的日志追加到不同的输出位置:appenders: ['out', 'allLog'] categories 作为getLogger方法的键名对应 + categories: { + // appenders:采用的appender,取上面appenders项,level:设置级别 + default: { appenders: ['out'], level: 'debug' } + } + }) + global.logger = log4js.getLogger('[test]') + logger.level = 'debug' + } +} + +export default new Command() diff --git a/Yunzai/lib/tools/name.js b/Yunzai/lib/tools/name.js new file mode 100644 index 0000000000000000000000000000000000000000..d4ff2f219b1616d910e139e825f8c352e3bfbba8 --- /dev/null +++ b/Yunzai/lib/tools/name.js @@ -0,0 +1,35 @@ +import fs from "node:fs" +import childProcess from "child_process" + +const _path = process.cwd() + +fs.readFile(`${_path}/config/pm2/pm2.json`, `utf8`, (err, data) => { + if (err) { + console.log('pm2.json文件读取错误:', err) + return + } + + try { + const config = JSON.parse(data) + if (config.apps && config.apps.length > 0 && config.apps[0].name) { + const appName = config.apps[0].name + console.log(config.apps[0].name) + runPm2Logs(appName) + } else { + console.log('读取失败:无法在pm2.json中找到name数组') + } + } catch (parseError) { + console.log('读取失败:json文件解析发生了错误', parseError) + } +}) + +function runPm2Logs(appName) { + const command = process.platform === 'win32' ? 'pm2.cmd' : 'pm2' + const args = ['logs', '--lines', '400', appName] + const pm2LogsProcess = childProcess.spawn(command, args, { stdio: 'inherit' }) + pm2LogsProcess.on('exit', (code) => { + if (code !== 0) { + console.error(`pm2 logs process exited with code ${code}`) + } + }) +} \ No newline at end of file diff --git a/Yunzai/lib/tools/test.js b/Yunzai/lib/tools/test.js new file mode 100644 index 0000000000000000000000000000000000000000..1bccf5ade7e32f0de2a5e945d4e27527da785998 --- /dev/null +++ b/Yunzai/lib/tools/test.js @@ -0,0 +1,11 @@ +import command from './command.js' + +/** + * npm test 十连 + * 配置数据config/test/defult.yaml + */ +await command.run() +// await command.run('bingCk') +// await command.run('gachaLog') +// await command.run('xlsx') +process.exit() diff --git a/Yunzai/lib/tools/web.js b/Yunzai/lib/tools/web.js new file mode 100644 index 0000000000000000000000000000000000000000..32ff156fdfc500239352f888c3da06d4421c562d --- /dev/null +++ b/Yunzai/lib/tools/web.js @@ -0,0 +1,74 @@ +import express from 'express' +import template from 'express-art-template' +import fs from 'fs' +import lodash from 'lodash' + +/* +* npm run app web-debug开启Bot后 +* 可另外通过 npm run web 开启浏览器调试 +* 访问 http://localhost:8000/ 即可看到对应页面 +* 页面内的资源需使用 {{_res_path}}来作为resources目录的根目录 +* 可编辑模板与页面查看效果 +* todo: 预览页面的热更 +* +* */ + +let app = express() + +let _path = process.cwd() + +app.engine('html', template) +app.set('views', _path + '/resources/') +app.set('view engine', 'art') +app.use(express.static(_path + '/resources')) +app.use('/plugins', express.static('plugins')) + +app.get('/', function (req, res) { + let pluginList = fs.readdirSync(_path + '/temp/ViewData/') || [] + let html = [ + '在npm run web-dev模式下触发截图消息后,可在下方选择页面进行调试', + '如果页面内资源路径不正确请使用{{_res_path}}作为根路径,对应之前的../../../../', + '可直接修改模板html或css刷新查看效果' + ] + let li = {} + for (let pIdx in pluginList) { + const plugin = pluginList[pIdx] + let fileList = fs.readdirSync(_path + `/temp/ViewData/${plugin}/`) || [] + for (let idx in fileList) { + let ret = /(.+)\.json$/.exec(fileList[idx]) + if (ret && ret[1]) { + let text = [plugin, ...ret[1].split('_')] + li[text.join('')] = (`
  • ${text.join(' / ')}
  • `) + } + } + } + res.send(html.join('
    ') + '
      ' + lodash.values(li).join('') + '
    ') +}) + +app.get('/:page', function (req, res) { + let [plugin, app, ...page] = req.params.page.split('_') + page = page.join('_') + if (plugin == 'favicon.ico') { + return res.send('') + } + let data = JSON.parse(fs.readFileSync(_path + `/temp/ViewData/${plugin}/${app}_${page}.json`, 'utf8')) + data = data || {} + data._res_path = '' + data._sys_res_path = data._res_path + + if (data._plugin) { + data._res_path = `/plugins/${data._plugin}/resources/` + data.pluResPath = data._res_path + } + let htmlPath = '' + let tplPath = `${app}/${htmlPath}${page}/${page}.html` + if (data._plugin) { + tplPath = `../plugins/${data._plugin}/resources/${htmlPath}/${app}/${page.split('_').join('/')}.html` + } else if (data._no_type_path) { + tplPath = `${app}/${page}.html` + } + res.render(tplPath, data) +}) + +app.listen(8000) +console.log('页面服务已启动,触发消息图片后访问 http://localhost:8000/ 调试页面') diff --git a/Yunzai/package.json b/Yunzai/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d5ce248523737519431a4fda390c161558a395c2 --- /dev/null +++ b/Yunzai/package.json @@ -0,0 +1,53 @@ +{ + "name": "trss-yunzai", + "version": "3.1.0", + "author": "TimeRainStarSky, Yoimiya-Kokomi, Le-niao", + "description": "Bot", + "main": "app.js", + "type": "module", + "scripts": { + "app": "node .", + "dev": "node . dev", + "web": "node ./lib/tools/web.js", + "test": "node ./lib/tools/test.js", + "start": "pm2 start ./config/pm2/pm2.json", + "stop": "pm2 stop ./config/pm2/pm2.json", + "restart": "pm2 restart ./config/pm2/pm2.json", + "log": "node ./lib/tools/name.js" + }, + "dependencies": { + "art-template": "^4.13.2", + "chalk": "^5.3.0", + "chokidar": "^3.5.3", + "express": "^4.18.2", + "file-type": "^18.5.0", + "https-proxy-agent": "7.0.2", + "image-size": "^1.0.2", + "lodash": "^4.17.21", + "log4js": "^6.9.1", + "md5": "^2.3.0", + "moment": "^2.29.4", + "node-fetch": "^3.3.2", + "node-schedule": "^2.1.1", + "node-xlsx": "^0.23.0", + "oicq": "link:lib/modules/oicq", + "pm2": "^5.3.0", + "puppeteer": "^21.3.8", + "redis": "^4.6.10", + "sequelize": "^6.33.0", + "sqlite3": "^5.1.6", + "ws": "^8.14.2", + "yaml": "^2.3.3" + }, + "devDependencies": { + "eslint": "^8.51.0", + "eslint-config-standard": "^17.1.0", + "eslint-plugin-import": "^2.28.1", + "eslint-plugin-n": "^16.2.0", + "eslint-plugin-promise": "^6.1.1" + }, + "imports": { + "#miao": "./plugins/miao-plugin/components/index.js", + "#miao.models": "./plugins/miao-plugin/models/index.js" + } +} diff --git a/Yunzai/plugins/.gitignore b/Yunzai/plugins/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b82ef0b2d9f3bc3a9552305cdc963b0307091d3a --- /dev/null +++ b/Yunzai/plugins/.gitignore @@ -0,0 +1,11 @@ +* +!.gitignore +!adapter +!adapter/** +!system +!system/** +!other +!other/** +!example/一言.js +!example/主动复读.js +!example/进群退群通知.js \ No newline at end of file diff --git a/Yunzai/plugins/adapter/ComWeChat.js b/Yunzai/plugins/adapter/ComWeChat.js new file mode 100644 index 0000000000000000000000000000000000000000..a0b910c93434355b9f14d86fb45f222b6f6a7e31 --- /dev/null +++ b/Yunzai/plugins/adapter/ComWeChat.js @@ -0,0 +1,501 @@ +import { randomUUID } from "crypto" +import path from "node:path" +import fs from "node:fs" +import { fileTypeFromBuffer } from "file-type" + +Bot.adapter.push(new class ComWeChatAdapter { + constructor() { + this.id = "WeChat" + this.name = "ComWeChat" + this.path = this.name + } + + toStr(data) { + switch (typeof data) { + case "string": + return data + case "number": + return String(data) + case "object": + if (Buffer.isBuffer(data)) + return Buffer.from(data, "utf8").toString() + else + return JSON.stringify(data) + } + return data + } + + makeLog(msg) { + return this.toStr(msg).replace(/(base64:\/\/|"type":"data","data":").*?"/g, '$1..."') + } + + sendApi(ws, action, params = {}) { + const echo = randomUUID() + const msg = { action, params, echo } + ws.sendMsg(msg) + return new Promise(resolve => + Bot.once(echo, data => + resolve({ ...data, ...data.data }))) + } + + async fileName(file) { + try { + if (file.match(/^base64:\/\//)) { + const buffer = Buffer.from(file.replace(/^base64:\/\//, ""), "base64") + const type = await fileTypeFromBuffer(buffer) + return `${Date.now()}.${type.ext}` + } else { + return path.basename(file) + } + } catch (err) { + logger.error(`文件类型检测错误:${logger.red(err)}`) + } + return false + } + + async uploadFile(data, file, name) { + const opts = { name: name || await this.fileName(file) || randomUUID() } + + if (file.match(/^https?:\/\//)) { + opts.type = "url" + opts.url = file + } else if (file.match(/^base64:\/\//)) { + opts.type = "data" + opts.data = file.replace(/^base64:\/\//, "") + } else if (fs.existsSync(file)) { + opts.type = "data" + opts.data = fs.readFileSync(file).toString("base64") + } else { + opts.type = "path" + opts.path = file + } + + logger.info(`${logger.blue(`[${data.self_id}]`)} 上传文件:${this.makeLog(opts)}`) + return data.bot.sendApi("upload_file", opts) + } + + async makeMsg(data, msg) { + if (!Array.isArray(msg)) + msg = [msg] + const msgs = [] + for (let i of msg) { + if (typeof i != "object") + i = { type: "text", data: { text: i }} + else if (!i.data) + i = { type: i.type, data: { ...i, type: undefined }} + if (i.data.file) + i.data = { file_id: (await this.uploadFile(data, i.data.file, i.data.name)).file_id } + + switch (i.type) { + case "text": + case "image": + case "file": + case "wx.emoji": + case "wx.link": + break + case "record": + case "video": + i.type = "file" + break + case "at": + if (i.data.qq == "all") + i = { type: "mention_all", data: {}} + else + i = { type: "mention", data: { user_id: i.data.qq }} + break + case "reply": + continue + default: + i = { type: "text", data: { text: JSON.stringify(i) }} + } + msgs.push(i) + } + return msgs + } + + async sendFriendMsg(data, msg) { + if (msg?.type == "node") + return Bot.sendForwardMsg(msg => this.sendFriendMsg(data, msg), msg.data) + + const message = await this.makeMsg(data, msg) + logger.info(`${logger.blue(`[${data.self_id} => ${data.user_id}]`)} 发送好友消息:${this.makeLog(message)}`) + return data.bot.sendApi("send_message", { + detail_type: "private", + user_id: data.user_id, + message, + }) + } + + async sendGroupMsg(data, msg) { + if (msg?.type == "node") + return Bot.sendForwardMsg(msg => this.sendGroupMsg(data, msg), msg.data) + + const message = await this.makeMsg(data, msg) + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id}]`)} 发送群消息:${this.makeLog(message)}`) + return data.bot.sendApi("send_message", { + detail_type: "group", + group_id: data.group_id, + message, + }) + } + + async getFriendArray(data) { + const array = [] + for (const i of (await data.bot.sendApi("get_friend_list")).data) + array.push({ + ...i, + nickname: i.user_remark == "null" ? i.user_displayname || i.user_name : i.user_remark, + }) + return array + } + + async getFriendList(data) { + const array = [] + for (const { user_id } of (await this.getFriendArray(data))) + array.push(user_id) + return array + } + + async getFriendMap(data) { + for (const i of (await this.getFriendArray(data))) + data.bot.fl.set(i.user_id, i) + return data.bot.fl + } + + getFriendInfo(data) { + return data.bot.sendApi("get_user_info", { + user_id: data.user_id, + }) + } + + async getGroupArray(data) { + return (await data.bot.sendApi("get_group_list")).data + } + + async getGroupList(data) { + const array = [] + for (const { group_id } of (await this.getGroupArray(data))) + array.push(group_id) + return array + } + + async getGroupMap(data) { + for (const i of (await this.getGroupArray(data))) + data.bot.gl.set(i.group_id, i) + return data.bot.gl + } + + getGroupInfo(data) { + return data.bot.sendApi("get_group_info", { + group_id: data.group_id, + }) + } + + async getMemberArray(data) { + return (await data.bot.sendApi("get_group_member_list", { + group_id: data.group_id, + })).data + } + + async getMemberList(data) { + const array = [] + for (const { user_id } of (await this.getMemberArray(data))) + array.push(user_id) + return array + } + + async getMemberMap(data) { + const map = new Map + for (const i of (await this.getMemberArray(data))) + map.set(i.user_id, i) + return map + } + + getMemberInfo(data) { + return data.bot.sendApi("get_group_member_info", { + group_id: data.group_id, + user_id: data.user_id, + }) + } + + pickFriend(data, user_id) { + const i = { + ...data.bot.fl.get(user_id), + ...data, + user_id, + } + return { + ...i, + sendMsg: msg => this.sendFriendMsg(i, msg), + sendFile: (file, name) => this.sendFriendMsg(i, segment.file(file, name)), + getInfo: () => this.getFriendInfo(i), + getAvatarUrl: async () => (await this.getFriendInfo(i))["wx.avatar"], + } + } + + pickMember(data, group_id, user_id) { + const i = { + ...data.bot.fl.get(user_id), + ...data, + group_id, + user_id, + } + return { + ...this.pickFriend(i, user_id), + ...i, + getInfo: () => this.getMemberInfo(i), + getAvatarUrl: async () => (await this.getMemberInfo(i))["wx.avatar"], + } + } + + pickGroup(data, group_id) { + const i = { + ...data.bot.gl.get(group_id), + ...data, + group_id, + } + return { + ...i, + sendMsg: msg => this.sendGroupMsg(i, msg), + sendFile: (file, name) => this.sendGroupMsg(i, segment.file(file, name)), + getInfo: () => this.getGroupInfo(i), + getAvatarUrl: async () => (await this.getGroupInfo(i))["wx.avatar"], + getMemberArray: () => this.getMemberArray(i), + getMemberList: () => this.getMemberList(i), + getMemberMap: () => this.getMemberMap(i), + pickMember: user_id => this.pickMember(i, i.group_id, user_id), + } + } + + async connect(data, ws) { + for (const bot of data.status.bots) + data.self_id = bot.self.user_id + + Bot[data.self_id] = { + adapter: this, + ws: ws, + sendApi: (action, params) => this.sendApi(ws, action, params), + stat: { ...data.status, start_time: data.time }, + + info: {}, + get uin() { return this.info.user_id }, + get nickname() { return this.info.user_name }, + get avatar() { return this.info["wx.avatar"] }, + + pickFriend: user_id => this.pickFriend(data, user_id), + get pickUser() { return this.pickFriend }, + getFriendArray: () => this.getFriendArray(data), + getFriendList: () => this.getFriendList(data), + getFriendMap: () => this.getFriendMap(data), + fl: new Map, + + pickMember: (group_id, user_id) => this.pickMember(data, group_id, user_id), + pickGroup: group_id => this.pickGroup(data, group_id), + getGroupArray: () => this.getGroupArray(data), + getGroupList: () => this.getGroupList(data), + getGroupMap: () => this.getGroupMap(data), + gl: new Map, + gml: new Map, + } + data.bot = Bot[data.self_id] + + if (!Bot.uin.includes(data.self_id)) + Bot.uin.push(data.self_id) + + data.bot.info = (await data.bot.sendApi("get_self_info")).data + data.bot.version = { + ...(await data.bot.sendApi("get_version")).data, + id: this.id, + name: this.name, + } + + data.bot.getFriendMap() + data.bot.getGroupMap() + + logger.mark(`${logger.blue(`[${data.self_id}]`)} ${this.name}(${this.id}) ${data.bot.version.impl}-${data.bot.version.version} 已连接`) + Bot.em(`connect.${data.self_id}`, data) + } + + makeMessage(data) { + data.post_type = data.type + data.message_type = data.detail_type + data.raw_message = data.alt_message + + data.sender = { + ...data.bot.fl.get(data.user_id), + user_id: data.user_id, + } + + const message = [] + for (const i of data.message) + switch (i.type) { + case "mention": + message.push({ type: "at", qq: i.data.user_id }) + break + case "mention_all": + message.push({ type: "at", qq: "all" }) + break + case "voice": + message.push({ type: "record", ...i.data }) + break + case "reply": + message.push({ type: "reply", id: i.data.message_id, user_id: i.data.user_id }) + break + default: + message.push({ type: i.type, ...i.data }) + } + data.message = message + + switch (data.message_type) { + case "private": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友消息:[${data.user_id}] ${data.raw_message}`) + break + case "group": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群消息:[${data.group_id}, ${data.user_id}] ${data.raw_message}`) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + + Bot.em(`${data.post_type}.${data.message_type}`, data) + } + + makeNotice(data) { + data.post_type = data.type + if (data.group_id) + data.notice_type = "group" + else + data.notice_type = "friend" + + switch (data.detail_type) { + case "private_message_delete": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友消息撤回:[${data.user_id}] ${data.message_id}`) + data.sub_type = "recall" + break + case "group_message_delete": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群消息撤回:[${data.group_id}, ${data.operator_id}=>${data.user_id}] ${data.message_id}`) + data.sub_type = "recall" + break + case "wx.get_private_file": + logger.info(`${logger.blue(`[${data.self_id}]`)} 私聊文件:[${data.user_id}] ${data.file_name} ${data.file_length} ${data.md5}`) + break + case "wx.get_group_file": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群文件:[${data.group_id}, ${data.user_id}] ${data.file_name} ${data.file_length} ${data.md5}`) + break + case "wx.get_private_redbag": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友红包:[${data.user_id}]`) + break + case "wx.get_group_redbag": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群红包:[${data.group_id}, ${data.user_id}]`) + break + case "wx.get_private_poke": + data.operator_id = data.from_user_id + data.target_id = data.user_id + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友拍一拍:[${data.operator_id}=>${data.target_id}]`) + break + case "wx.get_group_poke": + data.operator_id = data.from_user_id + data.target_id = data.user_id + logger.info(`${logger.blue(`[${data.self_id}]`)} 群拍一拍:[${data.group_id}, ${data.operator_id}=>${data.target_id}]`) + break + case "wx.get_private_card": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友用户名片:[${data.user_id}] ${data.v3} ${data.v4} ${data.nickname} ${data.head_url} ${data.province} ${data.city} ${data.sex}`) + break + case "wx.get_group_card": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群用户名片:[${data.group_id}, ${data.user_id}] ${data.v3} ${data.v4} ${data.nickname} ${data.head_url} ${data.province} ${data.city} ${data.sex}`) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知通知:${logger.magenta(JSON.stringify(data))}`) + } + if (!data.sub_type) + data.sub_type = data.detail_type.split("_").pop() + + Bot.em(`${data.post_type}.${data.notice_type}.${data.sub_type}`, data) + } + + makeRequest(data) { + data.post_type = data.type + if (data.group_id) + data.notice_type = "group" + else + data.notice_type = "friend" + + switch (data.detail_type) { + case "wx.friend_request": + logger.info(`${logger.blue(`[${data.self_id}]`)} 加好友请求:[${data.user_id}] ${data.v3} ${data.v4} ${data.nickname} ${data.content} ${data.province} ${data.city}`) + data.sub_type = "add" + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知请求:${logger.magenta(JSON.stringify(data))}`) + } + if (!data.sub_type) + data.sub_type = data.detail_type.split("_").pop() + + Bot.em(`${data.post_type}.${data.request_type}.${data.sub_type}`, data) + } + + makeMeta(data, ws) { + switch (data.detail_type) { + case "heartbeat": + break + case "connect": + break + case "status_update": + this.connect(data, ws) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + } + + message(data, ws) { + try { + data = JSON.parse(data) + } catch (err) { + return logger.error(`解码数据失败:${logger.red(err)}`) + } + + if (data.self?.user_id) { + data.self_id = data.self.user_id + } else { + data.self_id = data.id + } + + if (data.type) { + if (data.type != "meta" && !Bot.uin.includes(data.self_id)) { + logger.warn(`${logger.blue(`[${data.self_id}]`)} 找不到对应Bot,忽略消息:${logger.magenta(JSON.stringify(data))}`) + return false + } + data.bot = Bot[data.self_id] + + switch (data.type) { + case "meta": + this.makeMeta(data, ws) + break + case "message": + this.makeMessage(data) + break + case "notice": + this.makeNotice(data) + break + case "request": + this.makeRequest(data) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + } else if (data.echo) { + Bot.emit(data.echo, data) + } else { + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + } + + load() { + if (!Array.isArray(Bot.wsf[this.path])) + Bot.wsf[this.path] = [] + Bot.wsf[this.path].push((ws, ...args) => + ws.on("message", data => this.message(data, ws, ...args)) + ) + } +}) \ No newline at end of file diff --git a/Yunzai/plugins/adapter/GSUIDCore.js b/Yunzai/plugins/adapter/GSUIDCore.js new file mode 100644 index 0000000000000000000000000000000000000000..c790d7f5a138c784d8d164d2e9ad03afa2024798 --- /dev/null +++ b/Yunzai/plugins/adapter/GSUIDCore.js @@ -0,0 +1,249 @@ +import { randomUUID } from "crypto" +import path from "node:path" +import fs from "node:fs" + +Bot.adapter.push(new class GSUIDCoreAdapter { + constructor() { + this.id = "GSUIDCore" + this.name = "早柚核心" + this.path = this.id + } + + toStr(data) { + switch (typeof data) { + case "string": + return data + case "number": + return String(data) + case "object": + if (Buffer.isBuffer(data)) + return Buffer.from(data, "utf8").toString() + else + return JSON.stringify(data) + } + return data + } + + makeLog(msg) { + return this.toStr(msg).replace(/base64:\/\/.*?"/g, "base64://...\"") + } + + makeMsg(msg) { + if (!Array.isArray(msg)) + msg = [msg] + const msgs = [] + for (let i of msg) { + if (typeof i != "object") + i = { type: "text", text: i } + + switch (i.type) { + case "text": + i = { type: "text", data: i.text } + break + case "image": + i = { type: "image", data: i.file } + break + case "record": + i = { type: "file", data: i.file } + break + case "video": + i = { type: "file", data: i.file } + break + case "file": + i = { type: "file", data: i.file } + break + case "at": + i = { type: "at", data: i.qq } + break + case "reply": + i = { type: "reply", data: i.id } + break + case "node": { + const array = [] + for (const { message } of i.data) + array.push(...this.makeMsg(message)) + i.data = array + break + } default: + i = { type: "text", data: JSON.stringify(i) } + } + msgs.push(i) + } + return msgs + } + + sendFriendMsg(data, msg) { + const content = this.makeMsg(msg) + logger.info(`${logger.blue(`[${data.self_id} => ${data.user_id}]`)} 发送好友消息:${this.makeLog(content)}`) + data.bot.sendApi({ + bot_id: data.bot.bot_id, + bot_self_id: data.bot.bot_self_id, + target_type: "direct", + target_id: data.user_id, + content, + }) + return { message_id: Date.now() } + } + + sendGroupMsg(data, msg) { + const target = data.group_id.split("-") + const content = this.makeMsg(msg) + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id}]`)} 发送群消息:${this.makeLog(content)}`) + data.bot.sendApi({ + bot_id: data.bot.bot_id, + bot_self_id: data.bot.bot_self_id, + target_type: target[0], + target_id: target[1], + content, + }) + return { message_id: Date.now() } + } + + pickFriend(id, user_id) { + const i = { + ...Bot[id].fl.get(user_id), + self_id: id, + bot: Bot[id], + user_id: user_id, + } + return { + ...i, + sendMsg: msg => this.sendFriendMsg(i, msg), + } + } + + pickMember(id, group_id, user_id) { + const i = { + ...Bot[id].fl.get(user_id), + self_id: id, + bot: Bot[id], + group_id: group_id, + user_id: user_id, + } + return { + ...this.pickFriend(id, user_id), + ...i, + } + } + + pickGroup(id, group_id) { + const i = { + ...Bot[id].gl.get(group_id), + self_id: id, + bot: Bot[id], + group_id: group_id, + } + return { + ...i, + sendMsg: msg => this.sendGroupMsg(i, msg), + pickMember: user_id => this.pickMember(id, group_id, user_id), + } + } + + makeBot(data, ws) { + Bot[data.self_id] = { + adapter: this, + ws: ws, + get sendApi() { return this.ws.sendMsg }, + uin: data.self_id, + bot_id: data.bot_id, + bot_self_id: data.bot_self_id, + stat: { start_time: Date.now()/1000 }, + version: { + id: this.id, + name: this.name, + }, + pickFriend: user_id => this.pickFriend(data.self_id, user_id), + get pickUser() { return this.pickFriend }, + pickMember: (group_id, user_id) => this.pickMember(data.self_id, group_id, user_id), + pickGroup: group_id => this.pickGroup(data.self_id, group_id), + fl: new Map, + gl: new Map, + gml: new Map, + } + + logger.mark(`${logger.blue(`[${data.self_id}]`)} ${this.name}(${this.id}) 已连接`) + Bot.em(`connect.${data.self_id}`, data) + } + + message(data, ws) { + try { + data = JSON.parse(data) + } catch (err) { + return logger.error(`解码数据失败:${logger.red(err)}`) + } + + data.self_id = data.bot_self_id + if (Bot[data.self_id]) { + data.bot = Bot[data.self_id] + data.bot.ws = ws + } else { + this.makeBot(data, ws) + } + + data.post_type = "message" + data.message_id = data.msg_id + data.user_id = data.user_id + data.sender = { + user_id: data.user_id, + user_pm: data.user_pm, + } + if (!data.bot.fl.has(data.user_id)) + data.bot.fl.set(data.user_id, data.sender) + + data.message = [] + data.raw_message = "" + for (const i of data.content) { + switch (i.type) { + case "text": + data.message.push({ type: "text", text: i.data }) + data.raw_message += i.data + break + case "image": + data.message.push({ type: "image", url: i.data }) + data.raw_message += `[图片:${i.data}]` + break + case "file": + data.message.push({ type: "file", url: i.data }) + data.raw_message += `[文件:${i.data}]` + break + case "at": + data.message.push({ type: "at", qq: i.data }) + data.raw_message += `[提及:${i.data}]` + break + case "reply": + data.message.push({ type: "reply", id: i.data }) + data.raw_message += `[回复:${i.data}]` + break + case "node": + data.message.push({ type: "node", data: i.data }) + data.raw_message += `[合并转发:${JSON.stringify(i.data)}]` + break + default: + data.message.push(i) + data.raw_message += JSON.stringify(i) + } + } + + if (data.user_type == "direct") { + data.message_type = "private" + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友消息:[${data.user_id}] ${data.raw_message}`) + } else { + data.message_type = "group" + data.group_id = `${data.user_type}-${data.group_id}` + if (!data.bot.gl.has(data.group_id)) + data.bot.gl.set(data.group_id, { group_id: data.group_id }) + logger.info(`${logger.blue(`[${data.self_id}]`)} 群消息:[${data.group_id}, ${data.user_id}] ${data.raw_message}`) + } + + Bot.em(`${data.post_type}.${data.message_type}`, data) + } + + load() { + if (!Array.isArray(Bot.wsf[this.path])) + Bot.wsf[this.path] = [] + Bot.wsf[this.path].push((ws, ...args) => + ws.on("message", data => this.message(data, ws, ...args)) + ) + } +}) \ No newline at end of file diff --git a/Yunzai/plugins/adapter/go-cqhttp.js b/Yunzai/plugins/adapter/go-cqhttp.js new file mode 100644 index 0000000000000000000000000000000000000000..78cc78330088d80b49d4afa30c940f4086029480 --- /dev/null +++ b/Yunzai/plugins/adapter/go-cqhttp.js @@ -0,0 +1,842 @@ +import { randomUUID } from "crypto" +import path from "node:path" +import fs from "node:fs" + +Bot.adapter.push(new class gocqhttpAdapter { + constructor() { + this.id = "QQ" + this.name = "go-cqhttp" + this.path = this.name + } + + toStr(data) { + switch (typeof data) { + case "string": + return data + case "number": + return String(data) + case "object": + if (Buffer.isBuffer(data)) + return Buffer.from(data, "utf8").toString() + else + return JSON.stringify(data) + } + return data + } + + makeLog(msg) { + return this.toStr(msg).replace(/base64:\/\/.*?(,|]|")/g, "base64://...$1") + } + + sendApi(ws, action, params) { + const echo = randomUUID() + const msg = { action, params, echo } + ws.sendMsg(msg) + return new Promise(resolve => + Bot.once(echo, data => + resolve({ ...data, ...data.data }))) + } + + setProfile(data, profile) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 设置资料:${JSON.stringify(profile)}`) + return data.bot.sendApi("set_qq_profile", profile) + } + + makeMsg(msg) { + if (!Array.isArray(msg)) + msg = [msg] + const msgs = [] + for (const i of msg) + if (typeof i == "object") { + if (i.data) + msgs.push(i) + else + msgs.push({ type: i.type, data: { ...i, type: undefined }}) + } else { + msgs.push({ type: "text", data: { text: i }}) + } + return msgs + } + + sendFriendMsg(data, msg) { + if (msg?.type == "node") + return this.sendFriendForwardMsg(data, msg.data) + + logger.info(`${logger.blue(`[${data.self_id} => ${data.user_id}]`)} 发送好友消息:${this.makeLog(msg)}`) + return data.bot.sendApi("send_msg", { + user_id: data.user_id, + message: this.makeMsg(msg), + }) + } + + sendGroupMsg(data, msg) { + if (msg?.type == "node") + return this.sendGroupForwardMsg(data, msg.data) + + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id}]`)} 发送群消息:${this.makeLog(msg)}`) + return data.bot.sendApi("send_msg", { + group_id: data.group_id, + message: this.makeMsg(msg), + }) + } + + sendGuildMsg(data, msg) { + if (msg?.type == "node") + return Bot.sendForwardMsg(msg => this.sendGuildMsg(data, msg), msg) + + logger.info(`${logger.blue(`[${data.self_id}] => ${data.guild_id}-${data.channel_id}`)} 发送频道消息:${this.makeLog(msg)}`) + return data.bot.sendApi("send_guild_channel_msg", { + guild_id: data.guild_id, + channel_id: data.channel_id, + message: this.makeMsg(msg), + }) + } + + async getMsg(data, message_id) { + const msg = (await data.bot.sendApi("get_msg", { message_id })).data + + if (msg?.message) { + const message = [] + for (const i of msg.message) + message.push({ ...i.data, type: i.type }) + msg.message = message + } + + return msg + } + + recallMsg(data, message_id) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 撤回消息:${message_id}`) + return data.bot.sendApi("delete_msg", { message_id }) + } + + getForwardMsg(data, message_id) { + return data.bot.sendApi("get_forward_msg", { message_id }) + } + + makeForwardMsg(msg) { + const messages = [] + for (const i of msg) + messages.push({ + type: "node", + data: { + name: i.nickname || "匿名消息", + uin: Number(i.user_id) || 80000000, + content: this.makeMsg(i.message), + time: i.time, + }, + }) + return messages + } + + async sendFriendForwardMsg(data, msg) { + logger.info(`${logger.blue(`[${data.self_id} => ${data.user_id}]`)} 发送好友转发消息:${this.makeLog(msg)}`) + msg = await data.bot.sendApi("send_private_forward_msg", { + user_id: data.user_id, + messages: this.makeForwardMsg(msg), + }) + return msg + } + + async sendGroupForwardMsg(data, msg) { + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id}]`)} 发送群转发消息:${this.makeLog(msg)}`) + msg = await data.bot.sendApi("send_group_forward_msg", { + group_id: data.group_id, + messages: this.makeForwardMsg(msg), + }) + return msg + } + + async getFriendArray(data) { + return (await data.bot.sendApi("get_friend_list")).data + } + + async getFriendList(data) { + const array = [] + for (const { user_id } of (await this.getFriendArray(data))) + array.push(user_id) + return array + } + + async getFriendMap(data) { + for (const i of (await this.getFriendArray(data))) + data.bot.fl.set(i.user_id, i) + return data.bot.fl + } + + getFriendInfo(data) { + return data.bot.sendApi("get_stranger_info", { + user_id: data.user_id, + }) + } + + async getGroupArray(data) { + const array = (await data.bot.sendApi("get_group_list")).data + for (const guild of (await this.getGuildArray(data))) + for (const channel of (await this.getGuildChannelArray({ + ...data, + guild_id: guild.guild_id, + }))) + array.push({ + guild, + channel, + group_id: `${guild.guild_id}-${channel.channel_id}`, + group_name: `${guild.guild_name}-${channel.channel_name}`, + }) + return array + } + + async getGroupList(data) { + const array = [] + for (const { group_id } of (await this.getGroupArray(data))) + array.push(group_id) + return array + } + + async getGroupMap(data) { + for (const i of (await this.getGroupArray(data))) + data.bot.gl.set(i.group_id, i) + return data.bot.gl + } + + getGroupInfo(data) { + return data.bot.sendApi("get_group_info", { + group_id: data.group_id, + }) + } + + async getMemberArray(data) { + return (await data.bot.sendApi("get_group_member_list", { + group_id: data.group_id, + })).data + } + + async getMemberList(data) { + const array = [] + for (const { user_id } of (await this.getMemberArray(data))) + array.push(user_id) + return array + } + + async getMemberMap(data) { + const map = new Map + for (const i of (await this.getMemberArray(data))) + map.set(i.user_id, i) + return map + } + + getMemberInfo(data) { + return data.bot.sendApi("get_group_member_info", { + group_id: data.group_id, + user_id: data.user_id, + }) + } + + async getGuildArray(data) { + return (await data.bot.sendApi("get_guild_list")).data + } + + getGuildInfo(data) { + return data.bot.sendApi("get_guild_meta_by_guest", { + guild_id: data.guild_id, + }) + } + + async getGuildChannelArray(data) { + return (await data.bot.sendApi("get_guild_channel_list", { + guild_id: data.guild_id, + })).data + } + + async getGuildChannelMap(data) { + const map = new Map + for (const i of (await this.getGuildChannelArray(data))) + map.set(i.channel_id, i) + return map + } + + async getGuildMemberArray(data) { + const array = [] + let next_token = "" + while (true) { + const list = (await data.bot.sendApi("get_guild_member_list", { + guild_id: data.guild_id, + next_token, + })).data + + for (const i of list.members) + array.push({ + ...i, + user_id: i.tiny_id, + }) + if (list.finished) break + next_token = list.next_token + } + return array + } + + async getGuildMemberList(data) { + const array = [] + for (const { user_id } of (await this.getGuildMemberArray(data))) + array.push(user_id) + return array.push + } + + async getGuildMemberMap(data) { + const map = new Map + for (const i of (await this.getGuildMemberArray(data))) + map.set(i.user_id, i) + return map + } + + getGuildMemberInfo(data) { + return data.bot.sendApi("get_guild_member_profile", { + guild_id: data.guild_id, + user_id: data.user_id, + }) + } + + setGroupName(data, group_name) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 设置群名:[${data.group_id}] ${group_name}`) + return data.bot.sendApi("set_group_name", { + group_id: data.group_id, + group_name, + }) + } + + setGroupAvatar(data, file) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 设置群头像:[${data.group_id}] ${file}`) + return data.bot.sendApi("set_group_portrait", { + group_id: data.group_id, + file: segment.image(file).file, + }) + } + + setGroupAdmin(data, user_id, enable) { + logger.info(`${logger.blue(`[${data.self_id}]`)} ${enable ? "设置" : "取消"}群管理员:[${data.group_id}] ${user_id}`) + return data.bot.sendApi("set_group_admin", { + group_id: data.group_id, + user_id, + enable, + }) + } + + setGroupCard(data, user_id, card) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 设置群名片:[${data.group_id}] ${user_id} ${card}`) + return data.bot.sendApi("set_group_card", { + group_id: data.group_id, + user_id, + card, + }) + } + + setGroupTitle(data, user_id, special_title, duration) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 设置群头衔:[${data.group_id}] ${user_id} ${special_title} ${duration}`) + return data.bot.sendApi("set_group_special_title", { + group_id: data.group_id, + user_id, + special_title, + duration, + }) + } + + downloadFile(data, url, thread_count, headers) { + return data.bot.sendApi("download_file", { + url, + thread_count, + headers, + }) + } + + async makeFile(data, file, name = path.basename(file)) { + if (file.match(/^https?:\/\//)) + file = (await this.downloadFile(data, file)).file + else if (fs.existsSync(file)) + file = path.resolve(file) + return { file, name } + } + + async sendFriendFile(data, file, name) { + logger.info(`${logger.blue(`[${data.self_id} => ${data.user_id}]`)} 发送好友文件:${name}(${file})`) + return data.bot.sendApi("upload_private_file", { + user_id: data.user_id, + ...await this.makeFile(data, file, name), + }) + } + + async sendGroupFile(data, file, folder, name) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 发送群文件:[${data.group_id}] ${folder||""}/${name}(${file})`) + return data.bot.sendApi("upload_group_file", { + group_id: data.group_id, + folder, + ...await this.makeFile(data, file, name), + }) + } + + deleteGroupFile(data, file_id, busid) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 删除群文件:[${data.group_id}] ${file_id}(${busid})`) + return data.bot.sendApi("delete_group_file", { + group_id: data.group_id, + file_id, + busid, + }) + } + + createGroupFileFolder(data, name) { + logger.info(`${logger.blue(`[${data.self_id}]`)} 创建群文件夹:[${data.group_id}] ${name}`) + return data.bot.sendApi("create_group_file_folder", { + group_id: data.group_id, + name, + }) + } + + getGroupFileSystemInfo(data) { + return data.bot.sendApi("get_group_file_system_info", { + group_id: data.group_id, + }) + } + + getGroupFiles(data, folder_id) { + if (folder_id) + return data.bot.sendApi("get_group_files_by_folder", { + group_id: data.group_id, + folder_id, + }) + return data.bot.sendApi("get_group_root_files", { + group_id: data.group_id, + }) + } + + getGroupFileUrl(data, file_id, busid) { + return data.bot.sendApi("get_group_file_url", { + group_id: data.group_id, + file_id, + busid, + }) + } + + getGroupFs(data) { + return { + upload: (file, folder, name) => this.sendGroupFile(data, file, folder, name), + rm: (file_id, busid) => this.deleteGroupFile(data, file_id, busid), + mkdir: name => this.createGroupFileFolder(data, name), + df: () => this.getGroupFileSystemInfo(data), + ls: folder_id => this.getGroupFiles(data, folder_id), + download: (file_id, busid) => this.getGroupFileUrl(data, file_id, busid), + } + } + + setFriendAddRequest(data, flag, approve, remark) { + return data.bot.sendApi("set_friend_add_request", { + flag, + approve, + remark, + }) + } + + setGroupAddRequest(data, flag, sub_type, approve, reason) { + return data.bot.sendApi("set_group_add_request", { + flag, + sub_type, + approve, + reason, + }) + } + + pickFriend(data, user_id) { + const i = { + ...data.bot.fl.get(user_id), + ...data, + user_id, + } + return { + ...i, + sendMsg: msg => this.sendFriendMsg(i, msg), + getMsg: message_id => this.getMsg(i, message_id), + recallMsg: message_id => this.recallMsg(i, message_id), + getForwardMsg: message_id => this.getForwardMsg(i, message_id), + sendForwardMsg: msg => this.sendFriendForwardMsg(i, msg), + sendFile: (file, name) => this.sendFriendFile(i, file, name), + getInfo: () => this.getFriendInfo(i), + getAvatarUrl: () => `https://q1.qlogo.cn/g?b=qq&s=0&nk=${user_id}`, + } + } + + pickMember(data, group_id, user_id) { + if (typeof group_id == "string" && group_id.match("-")) { + const guild_id = group_id.split("-") + const i = { + ...data, + guild_id: guild_id[0], + channel_id: guild_id[1], + user_id, + } + return { + ...this.pickGroup(i, group_id), + ...i, + getInfo: () => this.getGuildMemberInfo(i), + getAvatarUrl: async () => (await this.getGuildMemberInfo(i)).avatar_url, + } + } + + const i = { + ...data.bot.fl.get(user_id), + ...data, + group_id, + user_id, + } + return { + ...this.pickFriend(i, user_id), + ...i, + getInfo: () => this.getMemberInfo(i), + poke: () => this.sendGroupMsg(i, segment.poke(user_id)), + } + } + + pickGroup(data, group_id) { + if (typeof group_id == "string" && group_id.match("-")) { + const guild_id = group_id.split("-") + const i = { + ...data.bot.gl.get(group_id), + ...data, + guild_id: guild_id[0], + channel_id: guild_id[1], + } + return { + ...i, + sendMsg: msg => this.sendGuildMsg(i, msg), + getMsg: message_id => this.getMsg(i, message_id), + recallMsg: message_id => this.recallMsg(i, message_id), + getForwardMsg: message_id => this.getForwardMsg(i, message_id), + getInfo: () => this.getGuildInfo(i), + getChannelArray: () => this.getGuildChannelArray(i), + getChannelList: () => this.getGuildChannelList(i), + getChannelMap: () => this.getGuildChannelMap(i), + getMemberArray: () => this.getGuildMemberArray(i), + getMemberList: () => this.getGuildMemberList(i), + getMemberMap: () => this.getGuildMemberMap(i), + pickMember: user_id => this.pickMember(i, group_id, user_id), + } + } + + const i = { + ...data.bot.gl.get(group_id), + ...data, + group_id, + } + return { + ...i, + sendMsg: msg => this.sendGroupMsg(i, msg), + getMsg: message_id => this.getMsg(i, message_id), + recallMsg: message_id => this.recallMsg(i, message_id), + getForwardMsg: message_id => this.getForwardMsg(i, message_id), + sendForwardMsg: msg => this.sendGroupForwardMsg(i, msg), + sendFile: (file, name) => this.sendGroupFile(i, file, undefined, name), + getInfo: () => this.getGroupInfo(i), + getAvatarUrl: () => `https://p.qlogo.cn/gh/${group_id}/${group_id}/0`, + getMemberArray: () => this.getMemberArray(i), + getMemberList: () => this.getMemberList(i), + getMemberMap: () => this.getMemberMap(i), + pickMember: user_id => this.pickMember(i, group_id, user_id), + pokeMember: user_id => this.sendGroupMsg(i, segment.poke(user_id)), + setName: group_name => this.setGroupName(i, group_name), + setAvatar: file => this.setGroupAvatar(i, file), + setAdmin: (user_id, enable) => this.setGroupAdmin(i, user_id, enable), + setCard: (user_id, card) => this.setGroupCard(i, user_id, card), + setTitle: (user_id, special_title, duration) => this.setGroupTitle(i, user_id, special_title, duration), + fs: this.getGroupFs(i), + } + } + + async connect(data, ws) { + Bot[data.self_id] = { + adapter: this, + ws: ws, + sendApi: (action, params) => this.sendApi(ws, action, params), + stat: { start_time: data.time }, + model: "TRSS Yunzai ", + + info: {}, + get uin() { return this.info.user_id }, + get nickname() { return this.info.nickname }, + get avatar() { return `https://q1.qlogo.cn/g?b=qq&s=0&nk=${this.uin}` }, + + setProfile: profile => this.setProfile(data, profile), + setNickname: nickname => this.setProfile(data, { nickname }), + + pickFriend: user_id => this.pickFriend(data, user_id), + get pickUser() { return this.pickFriend }, + getFriendArray: () => this.getFriendArray(data), + getFriendList: () => this.getFriendList(data), + getFriendMap: () => this.getFriendMap(data), + fl: new Map, + + pickMember: (group_id, user_id) => this.pickMember(data, group_id, user_id), + pickGroup: group_id => this.pickGroup(data, group_id), + getGroupArray: () => this.getGroupArray(data), + getGroupList: () => this.getGroupList(data), + getGroupMap: () => this.getGroupMap(data), + gl: new Map, + gml: new Map, + + request_list: [], + getSystemMsg: () => data.bot.request_list, + setFriendAddRequest: (flag, approve, remark) => this.setFriendAddRequest(data, flag, approve, remark), + setGroupAddRequest: (flag, sub_type, approve, reason) => this.setGroupAddRequest(data, flag, sub_type, approve, reason), + } + data.bot = Bot[data.self_id] + + if (!Bot.uin.includes(data.self_id)) + Bot.uin.push(data.self_id) + + data.bot.sendApi("_set_model_show", { + model: data.bot.model, + model_show: data.bot.model, + }) + + data.bot.info = (await data.bot.sendApi("get_login_info")).data + data.bot.guild_info = (await data.bot.sendApi("get_guild_service_profile")).data + data.bot.clients = (await data.bot.sendApi("get_online_clients")).clients + data.bot.version = { + ...(await data.bot.sendApi("get_version_info")).data, + id: this.id, + name: this.name, + } + + data.bot.getFriendMap() + data.bot.getGroupMap() + + logger.mark(`${logger.blue(`[${data.self_id}]`)} ${this.name}(${this.id}) ${data.bot.version.app_full_name} 已连接`) + Bot.em(`connect.${data.self_id}`, data) + } + + makeMessage(data) { + const message = [] + for (const i of data.message) + message.push({ ...i.data, type: i.type }) + data.message = message + + switch (data.message_type) { + case "private": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友消息:[${data.sender.nickname}(${data.user_id})] ${data.raw_message}`) + break + case "group": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群消息:[${data.group_id}, ${data.sender.card||data.sender.nickname}(${data.user_id})] ${data.raw_message}`) + break + case "guild": + data.message_type = "group" + data.group_id = `${data.guild_id}-${data.channel_id}` + logger.info(`${logger.blue(`[${data.self_id}]`)} 频道消息:[${data.group_id}, ${data.sender.nickname}(${data.user_id})] ${JSON.stringify(data.message)}`) + Object.defineProperty(data, "friend", { get() { return this.member || {}}}) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + + Bot.em(`${data.post_type}.${data.message_type}.${data.sub_type}`, data) + } + + async makeNotice(data) { + switch (data.notice_type) { + case "friend_recall": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友消息撤回:[${data.user_id}] ${data.message_id}`) + break + case "group_recall": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群消息撤回:[${data.group_id}, ${data.operator_id}=>${data.user_id}] ${data.message_id}`) + break + case "group_increase": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群成员增加:[${data.group_id}, ${data.operator_id}=>${data.user_id}] ${data.sub_type}`) + if (data.user_id == data.self_id) + data.bot.getGroupMap() + break + case "group_decrease": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群成员减少:[${data.group_id}, ${data.operator_id}=>${data.user_id}] ${data.sub_type}`) + if (data.user_id == data.self_id) + data.bot.getGroupMap() + break + case "group_admin": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群管理员变动:[${data.group_id}, ${data.user_id}] ${data.sub_type}`) + data.set = data.sub_type == "set" + break + case "group_upload": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群文件上传:[${data.group_id}, ${data.user_id}] ${JSON.stringify(data.file)}`) + break + case "group_ban": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群禁言:[${data.group_id}, ${data.operator_id}=>${data.user_id}] ${data.sub_type} ${data.duration}秒`) + break + case "friend_add": + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友添加:[${data.user_id}]`) + data.bot.getFriendMap() + break + case "notify": + if (data.group_id) + data.notice_type = "group" + else + data.notice_type = "friend" + switch (data.sub_type) { + case "poke": + data.operator_id = data.user_id + if (data.group_id) + logger.info(`${logger.blue(`[${data.self_id}]`)} 群戳一戳:[${data.group_id}, ${data.operator_id}=>${data.target_id}]`) + else + logger.info(`${logger.blue(`[${data.self_id}]`)} 好友戳一戳:[${data.operator_id}=>${data.target_id}]`) + break + case "honor": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群荣誉:[${data.group_id}, ${data.user_id}] ${data.honor_type}`) + break + case "title": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群头衔:[${data.group_id}, ${data.user_id}] ${data.title}`) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知通知:${logger.magenta(JSON.stringify(data))}`) + } + break + case "group_card": + logger.info(`${logger.blue(`[${data.self_id}]`)} 群名片更新:[${data.group_id}, ${data.user_id}] ${data.card_old}=>${data.card_new}`) + break + case "offline_file": + logger.info(`${logger.blue(`[${data.self_id}]`)} 离线文件:[${data.user_id}] ${JSON.stringify(data.file)}`) + break + case "client_status": + logger.info(`${logger.blue(`[${data.self_id}]`)} 客户端${data.online ? "上线" : "下线"}:${JSON.stringify(data.client)}`) + data.clients = (await data.bot.sendApi("get_online_clients")).clients + data.bot.clients = data.clients + break + case "essence": + data.notice_type = "group_essence" + logger.info(`${logger.blue(`[${data.self_id}]`)} 群精华消息:[${data.group_id}, ${data.operator_id}=>${data.sender_id}] ${data.sub_type} ${data.message_id}`) + break + case "guild_channel_recall": + logger.info(`${logger.blue(`[${data.self_id}]`)} 频道消息撤回:[${data.guild_id}-${data.channel_id}, ${data.operator_id}=>${data.user_id}] ${data.message_id}`) + break + case "message_reactions_updated": + data.notice_type = "guild_message_reactions_updated" + logger.info(`${logger.blue(`[${data.self_id}]`)} 频道消息表情贴:[${data.guild_id}-${data.channel_id}, ${data.user_id}] ${data.message_id} ${JSON.stringify(data.current_reactions)}`) + break + case "channel_updated": + data.notice_type = "guild_channel_updated" + logger.info(`${logger.blue(`[${data.self_id}]`)} 子频道更新:[${data.guild_id}-${data.channel_id}, ${data.user_id}] ${JSON.stringify(data.old_info)}=>${JSON.stringify(data.new_info)}`) + break + case "channel_created": + data.notice_type = "guild_channel_created" + logger.info(`${logger.blue(`[${data.self_id}]`)} 子频道创建:[${data.guild_id}-${data.channel_id}, ${data.user_id}] ${JSON.stringify(data.channel_info)}`) + data.bot.getGroupMap() + break + case "channel_destroyed": + data.notice_type = "guild_channel_destroyed" + logger.info(`${logger.blue(`[${data.self_id}]`)} 子频道删除:[${data.guild_id}-${data.channel_id}, ${data.user_id}] ${JSON.stringify(data.channel_info)}`) + data.bot.getGroupMap() + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知通知:${logger.magenta(JSON.stringify(data))}`) + } + + let notice = data.notice_type.split("_") + data.notice_type = notice.shift() + notice = notice.join("_") + if (notice) + data.sub_type = notice + + if (data.guild_id && data.channel_id) { + data.group_id = `${data.guild_id}-${data.channel_id}` + Object.defineProperty(data, "friend", { get() { return this.member || {}}}) + } + + Bot.em(`${data.post_type}.${data.notice_type}.${data.sub_type}`, data) + } + + makeRequest(data) { + switch (data.request_type) { + case "friend": + logger.info(`${logger.blue(`[${data.self_id}]`)} 加好友请求:[${data.user_id}] ${data.comment}(${data.flag})`) + data.sub_type = "add" + data.approve = approve => data.bot.setFriendAddRequest(data.flag, approve) + break + case "group": + logger.info(`${logger.blue(`[${data.self_id}]`)} 加群请求:[${data.group_id}, ${data.user_id}] ${data.sub_type} ${data.comment}(${data.flag})`) + data.approve = approve => data.bot.setGroupAddRequest(data.flag, data.sub_type, approve) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知请求:${logger.magenta(JSON.stringify(data))}`) + } + + data.bot.request_list.push(data) + Bot.em(`${data.post_type}.${data.request_type}.${data.sub_type}`, data) + } + + heartbeat(data) { + if (data.status?.stat) + data.bot.stat = { + ...data.status, + lost_pkt_cnt: data.status.stat.packet_lost, + lost_times: data.status.stat.lost_times, + recv_msg_cnt: data.status.stat.message_received, + recv_pkt_cnt: data.status.stat.packet_received, + sent_msg_cnt: data.status.stat.message_sent, + sent_pkt_cnt: data.status.stat.packet_sent, + start_time: data.bot.stat.start_time, + } + } + + makeMeta(data, ws) { + switch (data.meta_event_type) { + case "heartbeat": + this.heartbeat(data) + break + case "lifecycle": + this.connect(data, ws) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + } + + message(data, ws) { + try { + data = JSON.parse(data) + } catch (err) { + return logger.error(`解码数据失败:${logger.red(err)}`) + } + + if (data.post_type) { + if (data.meta_event_type != "lifecycle" && !Bot.uin.includes(data.self_id)) { + logger.warn(`${logger.blue(`[${data.self_id}]`)} 找不到对应Bot,忽略消息:${logger.magenta(JSON.stringify(data))}`) + return false + } + data.bot = Bot[data.self_id] + + switch (data.post_type) { + case "meta_event": + this.makeMeta(data, ws) + break + case "message": + this.makeMessage(data) + break + case "notice": + this.makeNotice(data) + break + case "request": + this.makeRequest(data) + break + case "message_sent": + data.post_type = "message" + this.makeMessage(data) + break + default: + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + } else if (data.echo) { + Bot.emit(data.echo, data) + } else { + logger.warn(`${logger.blue(`[${data.self_id}]`)} 未知消息:${logger.magenta(JSON.stringify(data))}`) + } + } + + load() { + if (!Array.isArray(Bot.wsf[this.path])) + Bot.wsf[this.path] = [] + Bot.wsf[this.path].push((ws, ...args) => + ws.on("message", data => this.message(data, ws, ...args)) + ) + } +}) \ No newline at end of file diff --git "a/Yunzai/plugins/example/\344\270\273\345\212\250\345\244\215\350\257\273.js" "b/Yunzai/plugins/example/\344\270\273\345\212\250\345\244\215\350\257\273.js" new file mode 100644 index 0000000000000000000000000000000000000000..f57cfa8815c6b98daa06b60804abc69c04261086 --- /dev/null +++ "b/Yunzai/plugins/example/\344\270\273\345\212\250\345\244\215\350\257\273.js" @@ -0,0 +1,37 @@ +import plugin from '../../lib/plugins/plugin.js' + +export class example2 extends plugin { + constructor () { + super({ + name: '复读', + dsc: '复读用户发送的内容,然后撤回', + /** https://oicqjs.github.io/oicq/#events */ + event: 'message', + priority: 5000, + rule: [ + { + /** 命令正则匹配 */ + reg: '^#复读$', + /** 执行方法 */ + fnc: 'repeat' + } + ] + }) + } + + /** 复读 */ + async repeat () { + /** 设置上下文,后续接收到内容会执行doRep方法 */ + this.setContext('doRep') + /** 回复 */ + await this.reply('请发送要复读的内容', false, { at: true }) + } + + /** 接受内容 */ + doRep () { + /** 复读内容 */ + this.reply(this.e.message, false, { recallMsg: 5 }) + /** 结束上下文 */ + this.finish('doRep') + } +} diff --git "a/Yunzai/plugins/example/\350\277\233\347\276\244\351\200\200\347\276\244\351\200\232\347\237\245.js" "b/Yunzai/plugins/example/\350\277\233\347\276\244\351\200\200\347\276\244\351\200\232\347\237\245.js" new file mode 100644 index 0000000000000000000000000000000000000000..e80ec3041a27cb990620efc792d804dfa175df48 --- /dev/null +++ "b/Yunzai/plugins/example/\350\277\233\347\276\244\351\200\200\347\276\244\351\200\232\347\237\245.js" @@ -0,0 +1,64 @@ +import plugin from '../../lib/plugins/plugin.js' +export class newcomer extends plugin { + constructor() { + super({ + name: '欢迎新人', + dsc: '新人入群欢迎', + /** https://oicqjs.github.io/oicq/#events */ + event: 'notice.group.increase', + priority: 5000 + }) + } + + /** 接受到消息都会执行一次 */ + async accept() { + if (this.e.user_id == this.e.self_id) return + + /** 定义入群欢迎内容 */ + let msg = '欢迎新人!' + /** 冷却cd 30s */ + let cd = 30 + + /** cd */ + let key = `Yz:newcomers:${this.e.group_id}` + if (await redis.get(key)) return + redis.set(key, '1', { EX: cd }) + + /** 回复 */ + await this.reply([ + segment.at(this.e.user_id), + // segment.image(), + msg + ]) + } +} + +export class outNotice extends plugin { + constructor() { + super({ + name: '退群通知', + dsc: 'xx退群了', + event: 'notice.group.decrease' + }) + + /** 退群提示词 */ + this.tips = '退群了' + } + + async accept() { + if (this.e.user_id == this.e.self_id) return + + let name, msg + if (this.e.member) { + name = this.e.member.card || this.e.member.nickname + } + + if (name) { + msg = `${name}(${this.e.user_id}) ${this.tips}` + } else { + msg = `${this.e.user_id} ${this.tips}` + } + logger.mark(`[退出通知]${this.e.logText} ${msg}`) + await this.reply(msg) + } +} \ No newline at end of file diff --git a/Yunzai/plugins/other/install.js b/Yunzai/plugins/other/install.js new file mode 100644 index 0000000000000000000000000000000000000000..d01dbf42c8eff05ce888004b24eda7d3e7011cda --- /dev/null +++ b/Yunzai/plugins/other/install.js @@ -0,0 +1,124 @@ +import { exec, execSync } from "child_process" +import plugin from "../../lib/plugins/plugin.js" +import fs from "node:fs" +import { Restart } from "./restart.js" + +let insing = false +const list = { + "Atlas":"https://gitee.com/Nwflower/atlas", + "ws-plugin":"https://gitee.com/xiaoye12123/ws-plugin", + "TRSS-Plugin" :"https://Yunzai.TRSS.me", + "yenai-plugin" :"https://gitee.com/yeyang52/yenai-plugin", + "flower-plugin" :"https://gitee.com/Nwflower/flower-plugin", + "xianyu-plugin" :"https://gitee.com/suancaixianyu/xianyu-plugin", + "earth-k-plugin":"https://gitee.com/SmallK111407/earth-k-plugin", + "useless-plugin":"https://gitee.com/SmallK111407/useless-plugin", + "StarRail-plugin" :"https://gitee.com/hewang1an/StarRail-plugin", + "xiaoyao-cvs-plugin":"https://gitee.com/Ctrlcvs/xiaoyao-cvs-plugin", + "Jinmaocuicuisha-plugin":"https://gitee.com/JMCCS/jinmaocuicuisha", + "trss-xianxin-plugin" :"https://gitee.com/snowtafir/xianxin-plugin", + "mysVilla-Plugin" :"https://gitee.com/TimeRainStarSky/Yunzai-mysVilla-Plugin", + "Telegram-Plugin" :"https://gitee.com/TimeRainStarSky/Yunzai-Telegram-Plugin", + "Discord-Plugin":"https://gitee.com/TimeRainStarSky/Yunzai-Discord-Plugin", + "QQGuild-Plugin":"https://gitee.com/TimeRainStarSky/Yunzai-QQGuild-Plugin", + "WeChat-Plugin" :"https://gitee.com/TimeRainStarSky/Yunzai-WeChat-Plugin", + "Proxy-Plugin" :"https://gitee.com/TimeRainStarSky/Yunzai-Proxy-Plugin", + "ICQQ-Plugin" :"https://gitee.com/TimeRainStarSky/Yunzai-ICQQ-Plugin", + "KOOK-Plugin" :"https://gitee.com/TimeRainStarSky/Yunzai-KOOK-Plugin", +} + +export class install extends plugin { + constructor() { + super({ + name: "安装插件", + dsc: "#安装插件 #安装TRSS-Plugin", + event: "message", + rule: [ + { + reg: `^#安装(插件|${Object.keys(list).join("|")})$`, + fnc: "install", + permission: "master" + } + ] + }) + } + + async install() { + if (insing) { + await this.reply("已有命令安装中..请勿重复操作") + return false + } + + const name = this.e.msg.replace(/^#安装/, "").trim() + if (name == "插件") { + let msg = "\n" + for (const name in list) + if (!fs.existsSync(`plugins/${name}`)) + msg += `${name}\n` + + if (msg == "\n") + msg = "暂无可安装插件" + else + msg = `可安装插件列表:${msg}发送 #安装+插件名 进行安装` + + await this.reply(msg) + return true + } + + const path = `plugins/${name}` + if (fs.existsSync(path)) { + await this.reply(`${name} 插件已安装`) + return false + } + await this.runInstall(name, list[name], path) + this.restart() + } + + async execSync(cmd) { + return new Promise(resolve => { + exec(cmd, (error, stdout, stderr) => { + resolve({ error, stdout, stderr }) + }) + }) + } + + async runInstall(name, url, path) { + logger.mark(`${this.e.logFnc} 开始安装:${name} 插件`) + await this.reply(`开始安装 ${name} 插件`) + + const cm = `git clone --depth 1 --single-branch "${url}" "${path}"` + insing = true + const ret = await this.execSync(cm) + if (fs.existsSync(`${path}/package.json`)) + await this.execSync("pnpm install") + insing = false + + if (ret.error) { + logger.mark(`${this.e.logFnc} 插件安装失败:${name}`) + this.gitErr(ret.error, ret.stdout) + return false + } + } + + async gitErr(err, stdout) { + let msg = "安装失败!" + let errMsg = err.toString() + stdout = stdout.toString() + + if (errMsg.includes('Timed out')) { + const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') + return this.reply(`${msg}\n连接超时:${remote}`) + } + + if (/Failed to connect|unable to access/g.test(errMsg)) { + const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') + return this.reply(`${msg}\n连接失败:${remote}`) + } + + await this.reply([errMsg, stdout]) + } + + restart() { + new Restart(this.e).restart() + } +} \ No newline at end of file diff --git a/Yunzai/plugins/other/restart.js b/Yunzai/plugins/other/restart.js new file mode 100644 index 0000000000000000000000000000000000000000..f0ef2bd228fab79e6a5de476bd0842e999060c06 --- /dev/null +++ b/Yunzai/plugins/other/restart.js @@ -0,0 +1,122 @@ +import plugin from '../../lib/plugins/plugin.js' +import { createRequire } from 'module' + +const require = createRequire(import.meta.url) +const { exec } = require('child_process') + +export class Restart extends plugin { + constructor (e = '') { + super({ + name: '重启', + dsc: '#重启', + event: 'message', + priority: 10, + rule: [{ + reg: '^#重启$', + fnc: 'restart', + permission: 'master' + }, { + reg: '^#(停机|关机)$', + fnc: 'stop', + permission: 'master' + }] + }) + + if (e) this.e = e + + this.key = 'Yz:restart' + } + + async init () { + let restart = await redis.get(this.key) + if (restart) { + restart = JSON.parse(restart) + let time = restart.time || new Date().getTime() + time = (new Date().getTime() - time) / 1000 + + let msg = `重启成功:耗时${time.toFixed(2)}秒` + + if (restart.isGroup) + Bot.sendGroupMsg(restart.bot_id, restart.id, msg) + else + Bot.sendFriendMsg(restart.bot_id, restart.id, msg) + + redis.del(this.key) + } + } + + async restart () { + await this.e.reply('开始执行重启,请稍等...') + logger.mark(`${this.e.logFnc} 开始执行重启,请稍等...`) + + let data = JSON.stringify({ + isGroup: !!this.e.isGroup, + id: this.e.isGroup ? this.e.group_id : this.e.user_id, + bot_id: this.e.self_id, + time: new Date().getTime() + }) + + let npm = await this.checkPnpm() + + try { + await redis.set(this.key, data, { EX: 120 }) + let cm = `${npm} start` + if (process.argv[1].includes('pm2')) { + cm = `${npm} run restart` + } + + exec(cm, { windowsHide: true }, (error, stdout, stderr) => { + if (error) { + redis.del(this.key) + this.e.reply(`操作失败!\n${error.stack}`) + logger.error(`重启失败\n${error.stack}`) + } else if (stdout) { + logger.mark('重启成功,运行已由前台转为后台') + logger.mark(`查看日志请用命令:${npm} run log`) + logger.mark(`停止后台运行命令:${npm} stop`) + process.exit() + } + }) + } catch (error) { + redis.del(this.key) + let e = error.stack ?? error + this.e.reply(`操作失败!\n${e}`) + } + + return true + } + + async checkPnpm () { + let npm = 'npm' + let ret = await this.execSync('pnpm -v') + if (ret.stdout) npm = 'pnpm' + return npm + } + + async execSync (cmd) { + return new Promise((resolve, reject) => { + exec(cmd, { windowsHide: true }, (error, stdout, stderr) => { + resolve({ error, stdout, stderr }) + }) + }) + } + + async stop () { + if (!process.argv[1].includes('pm2')) { + logger.mark('关机成功,已停止运行') + await this.e.reply('关机成功,已停止运行') + process.exit() + } + + logger.mark('关机成功,已停止运行') + await this.e.reply('关机成功,已停止运行') + + let npm = await this.checkPnpm() + exec(`${npm} stop`, { windowsHide: true }, (error, stdout, stderr) => { + if (error) { + this.e.reply(`操作失败!\n${error.stack}`) + logger.error(`关机失败\n${error.stack}`) + } + }) + } +} \ No newline at end of file diff --git a/Yunzai/plugins/other/sendLog.js b/Yunzai/plugins/other/sendLog.js new file mode 100644 index 0000000000000000000000000000000000000000..9b7d83b2c2d6bb4793da8dab1c2065c28bb35652 --- /dev/null +++ b/Yunzai/plugins/other/sendLog.js @@ -0,0 +1,78 @@ +import plugin from "../../lib/plugins/plugin.js" +import common from "../../lib/common/common.js" +import fs from "node:fs" +import lodash from "lodash" +import moment from "moment" + +export class sendLog extends plugin { + constructor() { + super({ + name: "发送日志", + dsc: "发送最近100条运行日志", + event: "message", + rule: [ + { + reg: "^#(运行|错误)*日志[0-9]*(.*)", + fnc: "sendLog", + permission: "master" + } + ] + }) + + this.lineNum = 100 + this.maxNum = 1000 + + this.logFile = `logs/command.${moment().format("YYYY-MM-DD")}.log` + this.errFile = "logs/error.log" + } + + async sendLog() { + let lineNum = this.e.msg.match(/\d+/g) + if (lineNum) { + this.lineNum = lineNum[0] + } else { + this.keyWord = this.e.msg.replace(/#|运行|错误|日志|\d/g, "") + } + + let logFile = this.logFile + let type = "运行" + if (this.e.msg.includes("错误")) { + logFile = this.errFile + type = "错误" + } + + if (this.keyWord) type = this.keyWord + + const log = this.getLog(logFile) + + if (lodash.isEmpty(log)) + return this.reply(`暂无相关日志:${type}`) + + return this.reply(await common.makeForwardMsg(this.e, [log.join("\n")], `最近${log.length}条${type}日志`)) + } + + getLog(logFile) { + let log = fs.readFileSync(logFile, { encoding: "utf-8" }) + log = log.split("\n") + + if (this.keyWord) { + for (const i in log) + if (!log[i].includes(this.keyWord)) + delete log[i] + } else { + log = lodash.slice(log, (Number(this.lineNum) + 1) * -1) + } + log = log.reverse() + + const tmp = [] + for (let i of log) { + if (!i) continue + if (this.keyWord && tmp.length >= this.maxNum) return + /* eslint-disable no-control-regex */ + i = i.replace(/\x1b[[0-9;]*m/g, "") + i = i.replace(/\r|\n/, "") + tmp.push(i) + } + return tmp + } +} diff --git a/Yunzai/plugins/other/setPubCk.js b/Yunzai/plugins/other/setPubCk.js new file mode 100644 index 0000000000000000000000000000000000000000..1f8324f08503827e21527a3c6ef702116c773bd3 --- /dev/null +++ b/Yunzai/plugins/other/setPubCk.js @@ -0,0 +1,167 @@ +import plugin from '../../lib/plugins/plugin.js' +import GsCfg from '../genshin/model/gsCfg.js' +import fs from 'node:fs' +import lodash from 'lodash' +import fetch from 'node-fetch' +import YAML from 'yaml' +import MysInfo from '../genshin/model/mys/mysInfo.js' +import common from '../../lib/common/common.js' + +export class setPubCk extends plugin { + constructor (e) { + super({ + name: '配置', + dsc: '#配置ck', + event: 'message', + priority: 700, + rule: [ + { + reg: '^#配置(ck|cookie)$|^#*配置公共查询ck$', + fnc: 'setPubCk', + permission: 'master' + }, + { + reg: '^#使用(全部|用户)ck$', + fnc: 'setUserCk', + permission: 'master' + } + ] + }) + + this.file = './plugins/genshin/config/mys.pubCk.yaml' + } + + /** 配置公共ck */ + async setPubCk () { + /** 设置上下文,后续接收到内容会执行doRep方法 */ + this.setContext('pubCk') + /** 回复 */ + await this.reply('请发送米游社cookie......\n配置后该ck将会加入公共查询池') + } + + async pubCk () { + let msg = this.e.msg + + if (!(/(ltoken|ltoken_v2)/.test(this.e.msg) && /(ltuid|ltmid_v2|account_mid_v2)/.test(this.e.msg))) { + this.e.reply('cookie错误,请发送正确的cookie') + return true + } + + this.finish('pubCk') + + let ck = msg.replace(/#|'|"/g, '') + let param = {} + ck.split(';').forEach((v) => { + // cookie_token_v2,ltoken_v2值也可能有= + // let tmp = lodash.trim(v).split('=') + let tmp = lodash.trim(v); + let index = tmp.indexOf("="); + param[tmp.slice(0,index)] = tmp.slice(index+1); + }) + + this.ck = '' + lodash.forEach(param, (v, k) => { + if (['ltoken', 'ltuid', 'cookie_token', 'account_id', 'cookie_token_v2', 'account_mid_v2', 'ltmid_v2', 'ltoken_v2'].includes(k)) { + this.ck += `${k}=${v};` + } + }) + + /** 检查ck是否失效 */ + if (!await this.checkCk()) { + logger.mark(`配置公共cookie错误:${this.checkMsg || 'cookie错误'}`) + await this.e.reply(`配置公共cookie错误:${this.checkMsg || 'cookie错误'}`) + return + } + + this.ltuid = param.ltuid + // 判断是否是v2版ck + if (param.cookie_token_v2 && (param.account_mid_v2 || param.ltoken_v2) && !(/(\d{4,9})/g).test(this.ltuid)) { + // 获取米游社通行证id + let userFullInfo = await this.getUserInfo() + if (userFullInfo?.data?.user_info) { + let userInfo = userFullInfo?.data?.user_info + this.ltuid = userInfo.uid + this.ck = `${this.ck}ltuid=${this.ltuid};` + } else { + logger.mark(`配置公共cookie错误:${userFullInfo.message || 'cookie错误'}`) + await this.e.reply(`配置公共cookie错误:${userFullInfo.message || 'cookie错误'}`) + return + } + } + + let ckArr = GsCfg.getConfig('mys', 'pubCk') || [] + + /** 判断是否重复 */ + for (let ck of ckArr) { + if (ck.includes(this.ltuid)) { + await this.e.reply('配置公共cookie错误:该ck已配置') + return + } + } + + ckArr.push(this.ck) + this.save(ckArr) + GsCfg.change_myspubCk() + + await this.e.reply(`配置公共ck成功:第${ckArr.length}个`) + } + + /** 检查ck是否可用 */ + async checkCk () { + let url = 'https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie?game_biz=hk4e_cn' + let res = await fetch(url, { method: 'get', headers: { Cookie: this.ck } }) + if (!res.ok) return false + res = await res.json() + if (res.retcode != 0) { + this.checkMsg = res.message + return false + } + + return true + } + + // 获取米游社通行证id + async getUserInfo (server = 'mys') { + try { + const that = this + let url = { + mys: 'https://bbs-api.mihoyo.com/user/wapi/getUserFullInfo?gids=2', + hoyolab: '' + } + let res = await fetch(url[server], { + method: 'get', + headers: { + Cookie: that.ck, + Accept: 'application/json, text/plain, */*', + Connection: 'keep-alive', + Host: 'bbs-api.mihoyo.com', + Origin: 'https://m.bbs.mihoyo.com', + Referer: ' https://m.bbs.mihoyo.com/' + } + }) + if (!res.ok) return res + res = await res.json() + return res + } catch (e) { + return null + } + } + + save (data) { + data = YAML.stringify(data) + fs.writeFileSync(this.file, data) + } + + async setUserCk () { + let set = './plugins/genshin/config/mys.set.yaml' + + let config = fs.readFileSync(set, 'utf8') + config = config.replace(/allowUseCookie: [0-1]/g, 'allowUseCookie: 1') + fs.writeFileSync(set, config, 'utf8') + + await common.sleep(500) + await MysInfo.initCache(true) + + await this.reply('开启成功,用户ck已加入公共查询ck池') + } +} diff --git a/Yunzai/plugins/other/update.js b/Yunzai/plugins/other/update.js new file mode 100644 index 0000000000000000000000000000000000000000..a33c30fcd613cbd39ce1a47037b319ebd2d7dcd3 --- /dev/null +++ b/Yunzai/plugins/other/update.js @@ -0,0 +1,240 @@ +import plugin from '../../lib/plugins/plugin.js' +import { createRequire } from 'module' +import lodash from 'lodash' +import fs from 'node:fs' +import { Restart } from './restart.js' +import common from '../../lib/common/common.js' + +const require = createRequire(import.meta.url) +const { exec, execSync } = require('child_process') + +let uping = false + +export class update extends plugin { + constructor() { + super({ + name: '更新', + dsc: '#更新 #强制更新', + event: 'message', + priority: 4000, + rule: [ + { + reg: '^#更新日志', + fnc: 'updateLog' + }, + { + reg: '^#(强制)?更新', + fnc: 'update' + }, + { + reg: '^#全部(强制)?更新$', + fnc: 'updateAll', + permission: 'master' + } + ] + }) + + this.typeName = 'TRSS-Yunzai' + } + + async update() { + if (!this.e.isMaster) return false + if (uping) return this.reply('已有命令更新中..请勿重复操作') + + if (/详细|详情|面板|面版/.test(this.e.msg)) return false + + /** 获取插件 */ + const plugin = this.getPlugin() + if (plugin === false) return false + + /** 执行更新 */ + await this.runUpdate(plugin) + + /** 是否需要重启 */ + if (this.isUp) { + // await this.reply('即将执行重启,以应用更新') + setTimeout(() => this.restart(), 2000) + } + } + + getPlugin(plugin = '') { + if (!plugin) { + plugin = this.e.msg.replace(/#(强制)?更新(日志)?/, '') + if (!plugin) return '' + } + + if (!fs.existsSync(`plugins/${plugin}/.git`)) return false + + this.typeName = plugin + return plugin + } + + async execSync(cmd) { + return new Promise((resolve, reject) => { + exec(cmd, { windowsHide: true }, (error, stdout, stderr) => { + resolve({ error, stdout, stderr }) + }) + }) + } + + async runUpdate(plugin = '') { + this.isNowUp = false + + let cm = 'git pull --no-rebase' + + let type = '更新' + if (this.e.msg.includes('强制')) { + type = '强制更新' + cm = `git reset --hard && git pull --rebase --allow-unrelated-histories` + } + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + + this.oldCommitId = await this.getcommitId(plugin) + + logger.mark(`${this.e.logFnc} 开始${type}:${this.typeName}`) + + await this.reply(`开始${type} ${this.typeName}`) + uping = true + const ret = await this.execSync(cm) + uping = false + + if (ret.error) { + logger.mark(`${this.e.logFnc} 更新失败:${this.typeName}`) + this.gitErr(ret.error, ret.stdout) + return false + } + + const time = await this.getTime(plugin) + + if (/Already up|已经是最新/g.test(ret.stdout)) { + await this.reply(`${this.typeName} 已是最新\n最后更新时间:${time}`) + } else { + await this.reply(`${this.typeName} 更新成功\n更新时间:${time}`) + this.isUp = true + await this.reply(await this.getLog(plugin)) + } + + logger.mark(`${this.e.logFnc} 最后更新时间:${time}`) + return true + } + + async getcommitId(plugin = '') { + let cm = 'git rev-parse --short HEAD' + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + + const commitId = await execSync(cm, { encoding: 'utf-8' }) + return lodash.trim(commitId) + } + + async getTime(plugin = '') { + let cm = 'git log -1 --pretty=%cd --date=format:"%F %T"' + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + + let time = '' + try { + time = await execSync(cm, { encoding: 'utf-8' }) + time = lodash.trim(time) + } catch (error) { + logger.error(error.toString()) + time = '获取时间失败' + } + + return time + } + + async gitErr(err, stdout) { + const msg = '更新失败!' + const errMsg = err.toString() + stdout = stdout.toString() + + if (errMsg.includes('Timed out')) { + const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') + return this.reply(`${msg}\n连接超时:${remote}`) + } + + if (/Failed to connect|unable to access/g.test(errMsg)) { + const remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') + return this.reply(`${msg}\n连接失败:${remote}`) + } + + if (errMsg.includes('be overwritten by merge')) { + return this.reply(`${msg}\n存在冲突:\n${errMsg}\n请解决冲突后再更新,或者执行#强制更新,放弃本地修改`) + } + + if (stdout.includes('CONFLICT')) { + return this.reply(`${msg}\n存在冲突:\n${errMsg}${stdout}\n请解决冲突后再更新,或者执行#强制更新,放弃本地修改`) + } + + return this.reply([errMsg, stdout]) + } + + async updateAll() { + const dirs = fs.readdirSync('./plugins/') + + await this.runUpdate() + + for (let plu of dirs) { + plu = this.getPlugin(plu) + if (plu === false) continue + await common.sleep(1500) + await this.runUpdate(plu) + } + + if (this.isUp) { + // await this.reply('即将执行重启,以应用更新') + setTimeout(() => this.restart(), 2000) + } + } + + restart() { + new Restart(this.e).restart() + } + + async getLog(plugin = '') { + let cm = 'git log -100 --pretty="%h||[%cd] %s" --date=format:"%F %T"' + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + + let logAll + try { + logAll = await execSync(cm, { encoding: 'utf-8' }) + } catch (error) { + logger.error(error.toString()) + await this.reply(error.toString()) + } + + if (!logAll) return false + + logAll = logAll.trim().split('\n') + + let log = [] + for (let str of logAll) { + str = str.split('||') + if (str[0] == this.oldCommitId) break + if (str[1].includes('Merge branch')) continue + log.push(str[1]) + } + let line = log.length + log = log.join('\n\n') + + if (log.length <= 0) return '' + + let end = '' + try { + cm = 'git config -l' + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + end = await execSync(cm, { encoding: 'utf-8' }) + end = end.match(/remote\..*\.url=.+/g).join('\n\n').replace(/remote\..*\.url=/g, '').replace(/\/\/([^@]+)@/, '//') + } catch (error) { + logger.error(error.toString()) + await this.reply(error.toString()) + } + + return common.makeForwardMsg(this.e, [log, end], `${plugin || 'TRSS-Yunzai'} 更新日志,共${line}条`) + } + + async updateLog() { + const plugin = this.getPlugin() + if (plugin === false) return false + return this.reply(await this.getLog(plugin)) + } +} \ No newline at end of file diff --git a/Yunzai/plugins/other/version.js b/Yunzai/plugins/other/version.js new file mode 100644 index 0000000000000000000000000000000000000000..f77786549d97f6c47b41612ae675b9198de3872b --- /dev/null +++ b/Yunzai/plugins/other/version.js @@ -0,0 +1,27 @@ +import { App, Common, Version } from '#miao' + +let app = App.init({ + id: 'version', + name: '版本', + desc: '版本' +}) + +app.reg({ + version: { + rule: /^#版本$/, + desc: '【#帮助】 版本介绍', + fn: async function (e) { + let { changelogs, currentVersion } = Version.readLogFile('root') + return await Common.render('help/version-info', { + currentVersion, + changelogs, + name: 'TRSS-Yunzai', + elem: 'cryo', + pluginName: false, + pluginVersion: false + }, { e, scale: 1.2 }) + } + } +}) + +export const version = app.v3App() diff --git a/Yunzai/plugins/system/add.js b/Yunzai/plugins/system/add.js new file mode 100644 index 0000000000000000000000000000000000000000..eacf1ac98268bd8dc9e89ddd044047dfe21c4121 --- /dev/null +++ b/Yunzai/plugins/system/add.js @@ -0,0 +1,446 @@ +import cfg from "../../lib/config/config.js" +import plugin from "../../lib/plugins/plugin.js" +import common from "../../lib/common/common.js" +import fs from "node:fs" +import path from "node:path" +import lodash from "lodash" +import fetch from "node-fetch" +import { fileTypeFromBuffer } from "file-type" + +let messageMap = {} + +export class add extends plugin { + constructor() { + super({ + name: "添加消息", + dsc: "添加消息", + event: "message", + priority: 50000, + rule: [ + { + reg: "^#(全局)?添加", + fnc: "add" + }, + { + reg: "^#(全局)?删除", + fnc: "del" + }, + { + reg: "", + fnc: "getMessage", + log: false + }, + { + reg: "^#(全局)?(消息|词条)", + fnc: "list" + } + ] + }) + + this.path = "data/messageJson/" + } + + async init() { + common.mkdirs(this.path) + } + + /** 群号key */ + get grpKey() { + return `Yz:group_id:${this.e.user_id}` + } + + /** #添加 */ + async add() { + this.isGlobal = Boolean(this.e.msg.match(/^#全局/)) + await this.getGroupId() + + if (!this.group_id) { + await this.reply("请先在群内触发消息,确定添加的群") + return + } + + this.initMessageMap() + + if (!this.checkAuth()) return false + /** 获取关键词 */ + this.getKeyWord() + if (!this.e.keyWord) { + await this.reply("添加错误:没有关键词") + return + } + + this.e.message = [] + this.setContext("addContext") + + return this.reply("请发送添加内容,完成后发送#结束添加", true, { at: true }) + } + + /** 获取群号 */ + async getGroupId() { + /** 添加全局消息,存入到机器人文件中 */ + if (this.isGlobal) { + this.group_id = "global" + return this.group_id + } + + if (this.e.isGroup) { + this.group_id = this.e.group_id + redis.setEx(this.grpKey, 3600 * 24 * 30, String(this.group_id)) + return this.group_id + } + + // redis获取 + let groupId = await redis.get(this.grpKey) + if (groupId) { + this.group_id = groupId + return this.group_id + } + + return false + } + + checkAuth() { + if (this.e.isMaster) return true + + const groupCfg = cfg.getGroup(this.e.self_id, this.group_id) + if (groupCfg.addLimit == 2) { + this.reply("暂无权限,只有主人才能操作") + return false + } + if (groupCfg.addLimit == 1) { + if (!this.e.member.is_admin) { + this.reply("暂无权限,只有管理员才能操作") + return false + } + } + + if (groupCfg.addPrivate != 1 && !this.e.isGroup) { + this.reply("禁止私聊添加") + return false + } + + return true + } + + /** 获取添加关键词 */ + getKeyWord() { + this.e.isGlobal = Boolean(this.e.msg.match(/^#全局/)) + this.keyWord = this.e.raw_message.replace(/#(全局)?(添加|删除)/, "").trim() + this.e.keyWord = this.trimAlias(this.keyWord) + } + + /** 过滤别名 */ + trimAlias(msg) { + const groupCfg = cfg.getGroup(this.e.self_id, this.group_id) + let alias = groupCfg.botAlias + if (!Array.isArray(alias)) + alias = [alias] + + for (const name of alias) + if (msg.startsWith(name)) + msg = lodash.trimStart(msg, name).trim() + + return msg + } + + /** 添加内容 */ + async addContext() { + const context = this.getContext()?.addContext + this.isGlobal = context.isGlobal + await this.getGroupId() + /** 关键词 */ + this.keyWord = context.keyWord + + if (!this.e.msg?.includes("#结束添加")) { + /** 添加内容 */ + for (const i of this.e.message) { + if (i.url) i.file = await this.saveFile(i) + if (i.type == "at" && i.qq == this.e.self_id) continue + context.message.push(i) + } + return + } + + this.finish("addContext") + if (!context.message?.length) { + this.reply("添加错误:没有添加内容") + return + } + + if (!messageMap[this.group_id]) + messageMap[this.group_id] = new Map() + + /** 支持单个关键词添加多个 */ + let message = messageMap[this.group_id].get(this.keyWord) + if (Array.isArray(message)) + message.push(context.message) + else + message = [context.message] + messageMap[this.group_id].set(this.keyWord, message) + + if (message.length > 1) + this.keyWord += String(message.length) + + this.saveJson() + return this.reply(`添加成功:${this.keyWord}`) + } + + saveJson() { + let obj = {} + for (let [k, v] of messageMap[this.group_id]) + obj[k] = v + + fs.writeFileSync(`${this.path}${this.group_id}.json`, JSON.stringify(obj, "", "\t")) + } + + async makeBuffer(file) { + if (file.match(/^base64:\/\//)) + return Buffer.from(file.replace(/^base64:\/\//, ""), "base64") + else if (file.match(/^https?:\/\//)) + return Buffer.from(await (await fetch(file)).arrayBuffer()) + else if (fs.existsSync(file)) + return Buffer.from(fs.readFileSync(file)) + return file + } + + async fileType(data) { + const file = { name: `${this.group_id}/${data.type}/${Date.now()}` } + try { + file.url = data.url.replace(/^base64:\/\/.*/, "base64://...") + file.buffer = await this.makeBuffer(data.url) + file.type = await fileTypeFromBuffer(file.buffer) + file.name = `${file.name}.${file.type.ext}` + } catch (err) { + logger.error(`文件类型检测错误:${logger.red(err)}`) + file.name = `${file.name}-${path.basename(data.file || data.url)}` + } + return file + } + + async saveFile(data) { + const file = await this.fileType(data) + if (file.name && Buffer.isBuffer(file.buffer) && common.mkdirs(path.dirname(`${this.path}${file.name}`))) { + fs.writeFileSync(`${this.path}${file.name}`, file.buffer) + return file.name + } + return data.url + } + + async getMessage() { + if (!this.e.raw_message) return false + this.isGlobal = false + + await this.getGroupId() + if (!this.group_id) return false + + this.initMessageMap() + this.initGlobalMessageMap() + + this.keyWord = this.trimAlias(this.e.raw_message.trim()) + let keyWord = this.keyWord + + let num = 0 + if (isNaN(keyWord)) { + num = keyWord.charAt(keyWord.length-1) + + if (!isNaN(num) && !messageMap[this.group_id].has(keyWord) && !messageMap.global.has(keyWord)) { + keyWord = lodash.trimEnd(keyWord, num).trim() + num-- + } + } + + let msg = [ + ...messageMap[this.group_id].get(keyWord) || [], + ...messageMap.global.get(keyWord) || [], + ] + if (lodash.isEmpty(msg)) return false + + if (!msg[num]) + num = lodash.random(0, msg.length-1) + + msg = [...msg[num]] + for (const i in msg) + if (msg[i].file && fs.existsSync(`${this.path}${msg[i].file}`)) + msg[i] = { ...msg[i], file: `base64://${fs.readFileSync(`${this.path}${msg[i].file}`).toString("base64")}` } + + logger.mark(`[发送消息]${this.e.logText} ${this.keyWord}`) + const groupCfg = cfg.getGroup(this.e.self_id, this.group_id) + return this.reply(msg, Boolean(groupCfg.addReply), { + at: Boolean(groupCfg.addAt), + recallMsg: groupCfg.addRecall, + }) + } + + /** 初始化已添加内容 */ + initMessageMap() { + if (messageMap[this.group_id]) return + messageMap[this.group_id] = new Map() + + const path = `${this.path}${this.group_id}.json` + if (!fs.existsSync(path)) return + + try { + const message = JSON.parse(fs.readFileSync(path, "utf8")) + for (const i in message) + messageMap[this.group_id].set(i, message[i]) + } catch (err) { + logger.error(`JSON 格式错误:${path} ${err}`) + } + } + + /** 初始化全局已添加内容 */ + initGlobalMessageMap() { + if (messageMap.global) return + messageMap.global = new Map() + + const globalPath = `${this.path}global.json` + if (!fs.existsSync(globalPath)) return + + try { + const message = JSON.parse(fs.readFileSync(globalPath, "utf8")) + for (const i in message) + messageMap.global.set(i, message[i]) + } catch (err) { + logger.error(`JSON 格式错误:${globalPath} ${err}`) + } + } + + async del() { + this.isGlobal = this.e.msg.includes("全局") + await this.getGroupId() + if (!(this.group_id && this.checkAuth())) return false + + this.initMessageMap() + + this.getKeyWord() + if (!this.keyWord) { + await this.reply("删除错误:没有关键词") + return false + } + + this.keyWord = this.trimAlias(this.keyWord) + let keyWord = this.keyWord + + let num = false + let index = 0 + if (isNaN(keyWord)) { + num = keyWord.charAt(keyWord.length-1) + + if (!isNaN(num) && !messageMap[this.group_id].has(keyWord)) { + keyWord = lodash.trimEnd(keyWord, num).trim() + index = num-1 + } else { + num = false + } + } + + let arr = messageMap[this.group_id].get(keyWord) + if (!arr) { + // await this.reply(`暂无此消息:${keyWord}`) + return false + } + + let tmp = [] + if (num) { + if (!arr[index]) { + // await this.reply(`暂无此消息:${keyWord}${num}`) + return false + } + + tmp = arr[index] + arr.splice(index, 1) + + if (arr.length <= 0) { + messageMap[this.group_id].delete(keyWord) + } else { + messageMap[this.group_id].set(keyWord, arr) + } + } else { + if (this.e.msg.includes("删除全部")) { + tmp = arr + arr = [] + } else { + tmp = arr.pop() + } + + if (arr.length <= 0) { + messageMap[this.group_id].delete(keyWord) + } else { + messageMap[this.group_id].set(keyWord, arr) + } + } + + this.saveJson() + return this.reply(`删除成功:${this.keyWord}`) + } + + async list() { + this.isGlobal = Boolean(this.e.msg.match(/^#全局/)) + + let page = 1 + let pageSize = 100 + let type = "list" + + await this.getGroupId() + if (!this.group_id) return false + + this.initMessageMap() + + const search = this.e.msg.replace(/^#(全局)?(消息|词条)/, "").trim() + if (search.match(/^列表/)) + page = search.replace(/^列表/, "") || 1 + else + type = "search" + + let list = messageMap[this.group_id] + + if (lodash.isEmpty(list)) { + await this.reply("暂无消息") + return + } + + let arr = [] + if (type == "list") + for (let [k, v] of messageMap[this.group_id]) + arr.push({ key: k, val: v, num: arr.length+1 }) + else + for (let [k, v] of messageMap[this.group_id]) + if (k.includes(search)) + arr.push({ key: k, val: v, num: arr.length+1 }) + + let count = arr.length + arr = arr.reverse() + + if (type == "list") + arr = this.pagination(page, pageSize, arr) + if (lodash.isEmpty(arr)) return false + + let msg = [] + let num = 0 + for (const i of arr) { + if (num >= page * pageSize) break + + let keyWord = i.key + if (!keyWord) continue + + msg.push(`${i.num}. ${keyWord}(${i.val.length})`) + num++ + } + msg = [msg.join("\n")] + + if (type == "list" && count > 100) + msg.push(`更多内容请翻页查看\n如:#消息列表${Number(page)+1}`) + + let title = `消息列表:第${page}页,共${count}条` + if (type == "search") + title = `消息${search}:共${count}条` + + return this.reply(await common.makeForwardMsg(this.e, msg, title)) + } + + /** 分页 */ + pagination(pageNo, pageSize, array) { + let offset = (pageNo-1) * pageSize + return offset+pageSize >= array.length ? array.slice(offset, array.length) : array.slice(offset, offset+pageSize) + } +} \ No newline at end of file diff --git a/Yunzai/plugins/system/botOperate.js b/Yunzai/plugins/system/botOperate.js new file mode 100644 index 0000000000000000000000000000000000000000..acceaab74024b7f87b7b4f7fc8b34f5614fc900e --- /dev/null +++ b/Yunzai/plugins/system/botOperate.js @@ -0,0 +1,45 @@ +export class botOperate extends plugin { + constructor () { + super({ + name: "Bot 操作", + dsc: "Bot 操作", + event: "message", + rule: [ + { + reg: "^#(Bot|机器人)验证.+:.+$", + fnc: "Verify", + permission: "master", + }, + { + reg: "^#(Bot|机器人)(上|下)线.+$", + fnc: "Operate", + permission: "master", + } + ] + }) + } + + Verify() { + const data = { msg: this.e.msg.replace(/^#(Bot|机器人)验证/, "").trim().split(":") } + data.self_id = data.msg.shift() + data.msg = data.msg.join(":") + Bot.em(`verify.${data.self_id}`, data) + } + + Operate() { + const bot = Bot[this.e.msg.replace(/^#(Bot|机器人)(上|下)线/, "").trim()] + if (typeof bot != "object") { + this.reply("Bot 不存在", true) + return false + } + if (this.e.msg.includes("上线") && typeof bot.login == "function") { + this.reply("已发送上线操作", true) + bot.login() + } else if (this.e.msg.includes("下线") && typeof bot.logout == "function") { + this.reply("已发送下线操作", true) + bot.logout() + } else { + this.reply("暂不支持此操作", true) + } + } +} \ No newline at end of file diff --git a/Yunzai/plugins/system/disablePrivate.js b/Yunzai/plugins/system/disablePrivate.js new file mode 100644 index 0000000000000000000000000000000000000000..b029557a6f8623b0e08489e45e6b20104d752c75 --- /dev/null +++ b/Yunzai/plugins/system/disablePrivate.js @@ -0,0 +1,75 @@ +import cfg from '../../lib/config/config.js' +import plugin from '../../lib/plugins/plugin.js' + +export class disPri extends plugin { + constructor () { + super({ + name: '禁止私聊', + dsc: '对私聊禁用做处理当开启私聊禁用时只接收cookie以及抽卡链接', + event: 'message.private' + }) + this.priority = 0 + } + + async accept () { + if (!cfg.other?.disablePrivate) return + + if (this.e.isMaster) return + + /** 发送日志文件,xlsx,json */ + if (this.e.file) { + if (!/(.*)\.txt|xlsx|json/ig.test(this.e.file?.name)) { + this.sendTips() + return 'return' + } else { + return false + } + } + + /** 绑定ck,抽卡链接 */ + let wordReg = /(.*)(ltoken|_MHYUUID|authkey=)(.*)|导出记录(json)*|(记录|安卓|苹果|ck|cookie|体力)帮助|^帮助$|^#*(删除|我的)ck$|^#(我的)?(uid|UID)[0-9]{0,2}$/g + /** 自定义通行字符 */ + let disableReg = `(.*)(${cfg.other?.disableAdopt?.join('|')})(.*)` + if (this.e.raw_message) { + if (!new RegExp(wordReg).test(this.e.raw_message) && (!new RegExp(disableReg).test(this.e.raw_message))) { + this.sendTips() + return 'return' + } + } + } + + async sendTips () { + /** 冷却cd 10s */ + let cd = 10 + + if (this.e.user_id == cfg.qq) return + + /** cd */ + let key = `Yz:disablePrivate:${this.e.user_id}` + if (await redis.get(key)) return + + this.e.reply(cfg.other.disableMsg) + + redis.setEx(key, cd, '1') + } +} + +export class disFriPoke extends plugin { + constructor () { + super({ + name: '禁止私聊', + dsc: '对私聊禁用做处理当开启私聊禁用时只接收cookie以及抽卡链接', + event: 'notice.friend.poke' + }) + this.priority = 0 + } + + async accept () { + if (!cfg.other?.disablePrivate) return + + if (this.e.isMaster) return + + this.e.reply(cfg.other.disableMsg) + return 'return' + } +} diff --git a/Yunzai/plugins/system/friend.js b/Yunzai/plugins/system/friend.js new file mode 100644 index 0000000000000000000000000000000000000000..ce3c17b40efbf828ac9cea4589bea90795583c73 --- /dev/null +++ b/Yunzai/plugins/system/friend.js @@ -0,0 +1,22 @@ +import cfg from '../../lib/config/config.js' +import common from '../../lib/common/common.js' + +export class friend extends plugin { + constructor () { + super({ + name: 'autoFriend', + dsc: '自动同意好友', + event: 'request.friend' + }) + } + + async accept() { + if (this.e.sub_type == 'add' || this.e.sub_type == 'single') { + if (cfg.other.autoFriend == 1) { + logger.mark(`[自动同意][添加好友] ${this.e.user_id}`) + await common.sleep(2000) + this.e.approve(true) + } + } + } +} \ No newline at end of file diff --git a/Yunzai/plugins/system/invite.js b/Yunzai/plugins/system/invite.js new file mode 100644 index 0000000000000000000000000000000000000000..2b74778272e8eedf5eed47f3b0965f5a38546651 --- /dev/null +++ b/Yunzai/plugins/system/invite.js @@ -0,0 +1,21 @@ +import cfg from '../../lib/config/config.js' + +export class invite extends plugin { + constructor () { + super({ + name: 'invite', + dsc: '主人邀请自动进群', + event: 'request.group.invite' + }) + } + + async accept () { + if (!this.e.isMaster) { + logger.mark(`[邀请加群]:${this.e.group_name}:${this.e.group_id}`) + return + } + logger.mark(`[主人邀请加群]:${this.e.group_name}:${this.e.group_id}`) + this.e.approve(true) + this.e.bot.pickFriend(this.e.user_id).sendMsg(`已同意加群:${this.e.group_name}`) + } +} diff --git a/Yunzai/plugins/system/master.js b/Yunzai/plugins/system/master.js new file mode 100644 index 0000000000000000000000000000000000000000..8f238dce5b23ad3c79554a5341c270ecaf5873bb --- /dev/null +++ b/Yunzai/plugins/system/master.js @@ -0,0 +1,55 @@ +import fs from "fs" +import { randomUUID } from "crypto" +let code = {} +let file = "config/config/other.yaml" +export class master extends plugin { + constructor () { + super({ + name: "设置主人", + dsc: "设置主人", + event: "message", + rule: [ + { + reg: "^#设置主人$", + fnc: "master" + } + ] + }) + } + + edit (file, key, value) { + let data = fs.readFileSync(file, "utf8") + if (data.match(RegExp(`- "?${value}"?`))) + return + value = `${key}:\n - "${value}"` + if (data.match(RegExp(`${key}:`))) + data = data.replace(RegExp(`${key}:`), value) + else + data = `${data}\n${value}` + fs.writeFileSync(file, data, "utf8") + } + + async master () { + if (this.e.isMaster) { + await this.reply(`账号:${this.e.user_id} 已经为主人`, true) + return false + } + + code[this.e.user_id] = randomUUID() + logger.mark(`${logger.cyan(`[${this.e.user_id}]`)} 设置主人验证码:${logger.green(code[this.e.user_id])}`) + this.setContext("verify") + await this.reply(`账号:${this.e.user_id} 请输入验证码`, true) + } + + async verify () { + this.finish("verify") + if (this.e.msg.trim() == code[this.e.user_id]) { + this.edit(file, "masterQQ", this.e.user_id) + this.edit(file, "master", `${this.e.self_id}:${this.e.user_id}`) + await this.reply(`账号:${this.e.user_id} 设置主人成功`, true) + } else { + await this.reply("验证码错误", true) + return false + } + } +} \ No newline at end of file diff --git a/Yunzai/plugins/system/quit.js b/Yunzai/plugins/system/quit.js new file mode 100644 index 0000000000000000000000000000000000000000..6c8d7f5b8101a4c5c813babfa3bf6055337d2b49 --- /dev/null +++ b/Yunzai/plugins/system/quit.js @@ -0,0 +1,36 @@ +import cfg from '../../lib/config/config.js' + +export class quit extends plugin { + constructor () { + super({ + name: 'notice', + dsc: '自动退群', + event: 'notice.group.increase' + }) + } + + async accept () { + if (this.e.user_id != this.e.self_id) return + + let other = cfg.other + if (other.autoQuit <= 0) return + + /** 判断主人,主人邀请不退群 */ + let gl = await this.e.group.getMemberMap() + for (let qq of cfg.masterQQ) { + if (gl.has(Number(qq) || String(qq))) { + logger.mark(`[主人拉群] ${this.e.group_id}`) + return + } + } + + /** 自动退群 */ + if (Array.from(gl).length <= other.autoQuit && !this.e.group.is_owner) { + await this.e.reply('禁止拉群,已自动退出') + logger.mark(`[自动退群] ${this.e.group_id}`) + setTimeout(() => { + this.e.group.quit() + }, 2000) + } + } +} diff --git a/Yunzai/plugins/system/recallMsg.js b/Yunzai/plugins/system/recallMsg.js new file mode 100644 index 0000000000000000000000000000000000000000..889d0fd741eb642df15fc0e9982ad58636277ba3 --- /dev/null +++ b/Yunzai/plugins/system/recallMsg.js @@ -0,0 +1,28 @@ +export class recallMsg extends plugin { + constructor () { + super({ + name: "回复撤回", + dsc: "撤回回复消息", + event: "message", + rule: [ + { + reg: `^#?撤回$`, + fnc: "recall" + } + ] + }) + } + + async recall(e) { + if (e.isMaster && e.reply_id) { + if (e.group?.recallMsg) { + e.group.recallMsg(e.reply_id) + e.group.recallMsg(e.message_id) + } else if (e.friend?.recallMsg) { + e.friend.recallMsg(e.reply_id) + e.friend.recallMsg(e.message_id) + } + } + return false + } +} \ No newline at end of file diff --git a/Yunzai/plugins/system/status.js b/Yunzai/plugins/system/status.js new file mode 100644 index 0000000000000000000000000000000000000000..a8b9a4123728b53e2aff732f938ffdbdb834a972 --- /dev/null +++ b/Yunzai/plugins/system/status.js @@ -0,0 +1,124 @@ +import cfg from '../../lib/config/config.js' +import moment from 'moment' + +export class status extends plugin { + constructor() { + super({ + name: '其他功能', + dsc: '#状态', + event: 'message', + rule: [ + { + reg: '^#状态$', + fnc: 'status' + } + ] + }) + } + + async status() { + if (this.e.isMaster) return this.statusMaster() + if (!this.e.isGroup) return this.reply('请群聊查看') + return this.statusGroup() + } + + async statusMaster() { + let runTime = moment().diff(moment.unix(this.e.bot.stat.start_time), 'seconds') + let Day = Math.floor(runTime / 3600 / 24) + let Hour = Math.floor((runTime / 3600) % 24) + let Min = Math.floor((runTime / 60) % 60) + if (Day > 0) { + runTime = `${Day}天${Hour}小时${Min}分钟` + } else { + runTime = `${Hour}小时${Min}分钟` + } + + let format = (bytes) => { + return (bytes / 1024 / 1024).toFixed(2) + 'MB' + } + + let msg = '-------状态-------' + msg += `\n运行时间:${runTime}` + msg += `\n内存使用:${format(process.memoryUsage().rss)}` + msg += `\n当前版本:v${cfg.package.version}` + msg += '\n-------累计-------' + msg += await this.getCount() + + await this.reply(msg) + } + + async statusGroup() { + let msg = '-------状态-------' + msg += await this.getCount(this.e.group_id) + + await this.reply(msg) + } + + async getCount(groupId = '') { + this.date = moment().format('MMDD') + this.month = Number(moment().month()) + 1 + + this.key = 'Yz:count:' + + if (groupId) this.key += `group:${groupId}:` + + this.msgKey = { + day: `${this.key}sendMsg:day:`, + month: `${this.key}sendMsg:month:` + } + + this.screenshotKey = { + day: `${this.key}screenshot:day:`, + month: `${this.key}screenshot:month:` + } + + let week = { + msg: 0, + screenshot: 0 + } + for (let i = 0; i <= 6; i++) { + let date = moment().startOf('week').add(i, 'days').format('MMDD') + + week.msg += Number(await redis.get(`${this.msgKey.day}${date}`)) ?? 0 + week.screenshot += Number(await redis.get(`${this.screenshotKey.day}${date}`)) ?? 0 + } + + let count = { + total: { + msg: await redis.get(`${this.key}sendMsg:total`) || 0, + screenshot: await redis.get(`${this.key}screenshot:total`) || 0 + }, + today: { + msg: await redis.get(`${this.msgKey.day}${this.date}`) || 0, + screenshot: await redis.get(`${this.screenshotKey.day}${this.date}`) || 0 + }, + week, + month: { + msg: await redis.get(`${this.msgKey.month}${this.month}`) || 0, + screenshot: await redis.get(`${this.screenshotKey.month}${this.month}`) || 0 + } + } + + let msg = '' + if (groupId) { + msg = `\n发送消息:${count.today.msg}条` + msg += `\n生成图片:${count.today.screenshot}次` + } else { + msg = `\n发送消息:${count.total.msg}条` + msg += `\n生成图片:${count.total.screenshot}次` + } + + if (count.month.msg > 200) { + msg += '\n-------本周-------' + msg += `\n发送消息:${count.week.msg}条` + msg += `\n生成图片:${count.week.screenshot}次` + } + if (moment().format('D') >= 8 && count.month.msg > 400) { + msg += '\n-------本月-------' + msg += `\n发送消息:${count.month.msg}条` + msg += `\n生成图片:${count.month.screenshot}次` + } + + return msg + } +} diff --git a/Yunzai/plugins/ws-plugin/.gitignore b/Yunzai/plugins/ws-plugin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..25b6a70767bfd5b6c233047258fbd8801eb5b746 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +Temp/ +config/config/* +model/db/data.db +**/test.js +!.gitignore \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/CHANGELOG.md b/Yunzai/plugins/ws-plugin/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..4fbfdfef0354dc77f132f7224be3b60b2f8facae --- /dev/null +++ b/Yunzai/plugins/ws-plugin/CHANGELOG.md @@ -0,0 +1,295 @@ +# 0.5.15 + +* RedProtocol 尝试适配喵崽 + +# 0.5.14 + +* `#ws重新连接` 改为指定 + +# 0.5.13 + +* red 非win系统可以使用`#ws设置red转发2`使发送伪造消息为直接发送 + +# 0.5.12 + +* 修改red连接过程 +* onebot增加快速操作api +* 尝试存储trss icqq插件发送的消息 + +# 0.5.11 + +* Chronocat 0.0.48 支持私聊导入抽卡记录等 + +# 0.5.10 + +* Chronocat响应群临时消息 + +# 0.5.9 + +* 将消息存储到数据库,默认存储7天 + * 仅支持 Miao-Yunzai & TRSS-Yunzai, Yunzai-Bot还是存储在redis +* Chronocat 0.0.47之前的版本获取群历史消息没有user_id,可能会导致获取失败,建议更新至0.0.47 + +# 0.5.8 + +* 增加一个设置项`#ws设置禁言拦截 开启/关闭`,详细请查看`#ws设置` + +# 0.5.7 + +* 支持正向http 反向http +* 部分细节优化 + +# 0.5.6 + +* 正向ws连接支持/api /event接口 + +# 0.5.5 + +* QQNT 转发消息发送者改为固定 +* 可能适配了ReadStream的file + +# 0.5.4 + +* Chronocat 0.0.43 发送转发消息有message_id返回了 + +# 0.5.3 + +* 支持了TRSS-Yunzai 的 ICQQ-Plugin + * 目前 TRSS-Yunzai 的可用协议为 + * GenshinUID Core 全部协议均可使用 + * onebot 仅支持 QQNT 以及 ICQQ + +# 0.5.2 + +* QQNT 拦截配置项中没有uin的连接 + * uin为需要连接的账号 +* 优化添加连接之后的提示词 + +# 0.5.1 + +* QQNT 将嵌套转发消息改成不嵌套 + * 暂时不支持嵌套转发 + +# 0.5.0 + +* 重构一下QQNT相关的代码 +* 优化一下onebotApi相关的代码 + * 之后可能会用得上 +* QQNT支持正向和反向ws连接,需要对QQNT连接的账号发送#ws添加连接 +* QQNT增加群禁言,全体禁言,踢群 + * 如果QQNT不在前台且焦点不在指定的群,获取的群成员列表可能为空 + * 如果为空的话则只会获取启动机器人之后在群内发送过消息的人 +* QQNT修复使用Chronocat0.0.42时的某些bug +* QQNT增加请求Api超时输出日志 + +# 0.4.20 + +* QQNT 简单支持一下文字的转发消息,(图片会把消息发给自己然后撤回取直链) + * 需要更新Chronocat 0.0.40 + * 需要64位QQNT,如果不是64位不能伪造转发消息 + * 机器人所在的QQNT看不了发送的转发消息 + * 发送转发消息之前至少要有一条消息 + * 转发消息目前不能主动撤回 + +# 0.4.19 + +* QQNT 增加获取群历史消息 + * 因为回复消息没有msgId,所以将seq存在redis获取对应的msgId,默认存储10分钟 +* QQNT 优化使用TRSS脚本自动获取Token + +# 0.4.18 + +* QQNT 增加发送视频 需要ffmpeg + +# 0.4.17 + +* QQNT 增加发送文件 + +# 0.4.16 + +* QQNT 发送语音修改为使用ffmpeg,请自行配置ffmpeg,否则可能无法发送语音 + * 更新后需要重新安装依赖 pnpm install --filter=ws-plugin + +# 0.4.15 + +* QQNT 优化进群通知,增加禁言通知 + +# 0.4.14 + +* 增加 TRSS-Yunzai 连接 gsuid_core +* 优化CQ:node + +# 0.4.13 + +* QQNT 增加发送回复消息 + * 回复会默认带一个 `@` + +# 0.4.12 + +* QQNT 若不填Token则自动获取Token + +# 0.4.11 + +* QQNT 增加发送语音,小表情 + * 语音只有手机上能听 + +# 0.4.10 + +* QQNT 增加入群通知 + +# 0.4.9 + +* QQNT 增加主动撤回消息 + +# 0.4.8 + +* 优化`#ws添加连接` + +# 0.4.7 + +* 增加 TRSS-Yunzai 连接 QQNT + +# 0.4.6 + +* 增加白名单 + +# 0.4.5 + +* 优化代码 + +# 0.4.4 + +* 增加api + * get_essence_msg_list 获取精华消息列表 + * _get_group_notice 获取群公告 + +# 0.4.3 + +* 增加匿名以及群匿名用户禁言API + +# 0.4.2 + +* 增加设置项`#ws设置全部 开启/关闭` 一键操作所有设置项 + +# 0.4.1 + +* 优化存储消息,其他插件使用e.reply时也能存储,防止get_msg报错 + +# 0.4.0 + +* 适配锅巴 +* 增加大部分api +* 增加请求上报 +* 增加`#ws更新日志` + +# 0.3.12 + +* 修复更换为Bot.on之后仅at不生效的问题 +* 增加可单独禁用群聊 + * `#ws禁用群123456` 不带群号则默认为当前群 + * `#ws启用群123456` 不带群号则默认为当前群 + * `#ws查看禁用群` + * 详细可查看`#ws帮助` + +# 0.3.11 + +* 新增CQ码[CQ:music] 音乐自定义分享 Copyright xiaofei-plugin + +# 0.3.10 + +* 修改message_id存储于redis +* 增加设置项`#ws设置存储600` +* 增加对message_id为null的判断 +* 获取消息仅针对`用户发送`以及`ws-plugin插件发送`,如果是其他插件发送的消息会获取不到 + +# 0.3.9 + +* 修改为Bot.on +* 删除设置项`#ws设置优先级` + +# 0.3.8 + +* 修复前缀判断时错误的匹配e.msg的问题 +* 反向ws连接添加缺少的请求头X-Client-Role + +# 0.3.7 + +* 增加api + * get_group_root_files 获取群根目录文件列表 + * get_group_files_by_folder 获取群子目录文件列表 + * get_group_file_url 获取群文件资源链接 + +# 0.3.6 + +* 增加CQ码[CQ:record] 语音 + +# 0.3.5 + +* 增加发送消息成功后的日志输出 +* 适配根据歌曲id分享音乐 + +# 0.3.4 + +* 可能修复了连接失败时关闭和删除连接无效的bug +* 增加一个设置项`#ws设置优先级1` 设置完重启后生效 +* 增加了几个bug + +# 0.3.3 + +* 增加CQ码[CQ:face] QQ表情 + +# 0.3.2 + +* 重新开放一下正向ws连接 + +# 0.3.1 + +* 增加指令`#ws帮助` Copyright miao-plugin + +# 0.3.0 + +* 增加指令`#ws关闭连接``#ws打开连接``#ws查看连接` + *`#ws关闭连接` 不会删除已有连接,同时不进行连接 + *`#ws打开连接` 打开已关闭的连接 + *`#ws查看连接` 查看已有的所有连接名字和状态 + *`#ws添加连接` 添加一个新的连接 + *`#ws删除连接` 删除一个已有的连接 + *`#ws重新连接` 强制断开已有的所有连接并重新连接 +* 暂时关闭正向ws连接 + +# 0.2.0 + +* 增加通知事件上报,默认关闭,需要可自行使用`#ws设置`进行开启 + * 增加以下通知事件 + * 群管理员变动,群成员减少,群成员增加 + * 群禁言,好友添加,群消息撤回 + * 好友消息撤回,群内戳一戳 + +# 0.1.0 + +* 增加指令`#ws版本``#ws设置` Copyright miao-plugin + +# 0.0.5 + +* 增加指令`#ws重新连接` +* 增加首次连接时将结果通知主人设置 + +# 0.0.4 + +* 增加断线自动重新连接 +* 增加断线和重连通知主人设置 + +# 0.0.3 + +* 适配gsuid群聊导出抽卡记录和私聊发送抽卡记录json文件 + +# 0.0.2 + +* 增加指令`#ws添加连接``#ws删除连接` + +# 0.0.1 + +* 初始化插件 +* 可连接支持onebotv11协议的bot以及gsuid_core +* 适配了部分onebot api + diff --git a/Yunzai/plugins/ws-plugin/LICENSE b/Yunzai/plugins/ws-plugin/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 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 General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Yunzai/plugins/ws-plugin/README.md b/Yunzai/plugins/ws-plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0b75b59da27dcca6d07e5a637c35ae310eb3e019 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/README.md @@ -0,0 +1,264 @@ +# ws-plugin + +## 介绍 +Yunzai-Bot 的扩展插件 ws-plugin 提供ontbot协议适配,通过WebSocket连接onebot实现的bot + +### 什么是onebot + +OneBot 是一个聊天机器人应用接口标准,旨在统一不同聊天平台上的机器人应用开发接口,使开发者只需编写一次业务逻辑代码即可应用到多种机器人平台。 + +### 可以用ws-plugin实现什么功能 + +* 可以在Yunzai-Bot的基础上连接多个使用onebot协议的机器人,比如[NoneBot2](https://github.com/nonebot/nonebot2), [zhenxun_bot](https://github.com/HibiKier/zhenxun_bot), [ZeroBot-Plugin](https://github.com/FloatTech/ZeroBot-Plugin)等 + +* 作为[Chronocaat](https://chronocat.vercel.app/)适配器 [点击前往寒暄的教程(http://Yunzai.icu)](http://Yunzai.icu) + * RedProtocol部分已实现 + * Satori等待Chronocat更新 + +### 支持的Yunzai-bot版本 + +#### [Miao-Yunzai](https://gitee.com/yoimiya-kokomi/Miao-Yunzai) && [Yunzai-Bot](https://gitee.com/yoimiya-kokomi/Yunzai-Bot) + +作为客户端: + - onebot v11 + - 反向 WebSocket + - 正向 WebSocket + - 正向http + - 反向http + - [gsuid_core](https://github.com/Genshin-bots/gsuid_core) + +作为服务端 + - RedProtocol + +#### [TRSS-Yunzai](https://gitee.com/TimeRainStarSky/Yunzai) + +作为客户端: + - onebot v11 (目前仅支持 [ICQQ-Plugin](https://gitee.com/TimeRainStarSky/Yunzai-ICQQ-Plugin) & Red) + - 反向 WebSocket + - 正向 WebSocket + - 正向http + - 反向http + - [gsuid_core](https://github.com/Genshin-bots/gsuid_core) + +作为服务端 + - RedProtocol + +## 安装与更新 + +### 使用Git安装(推荐) + +请将 ws-plugin 放置在 Yunzai-Bot 的 plugins 目录下,重启 Yunzai-Bot 后即可使用。 + +请使用 git 进行安装,以方便后续升级。在 Yunzai-Bot 根目录夹打开终端,运行下述指令之一 + +``` +#gitee +git clone --depth=1 https://gitee.com/xiaoye12123/ws-plugin.git ./plugins/ws-plugin/ +pnpm install --filter=ws-plugin +``` +``` +#github +git clone --depth=1 https://github.com/xiaoye12123/ws-plugin.git ./plugins/ws-plugin/ +pnpm install --filter=ws-plugin +``` + +进行安装。安装完毕后,管理员只需发送 `#ws更新` 即可自动更新 ws-plugin。 + +## 使用说明 + +
    +功能列表 | 只支持主人使用 + +| 指令 | 说明 | +| ------------ | --------------------------- | +| #ws帮助 | 召唤出ws插件的帮助图 | +| #ws设置 | 进行ws插件相关设置 | +| #ws添加连接 | 添加一个新的连接 | +| #ws删除连接 | 删除一个已有的连接 | +| #ws关闭连接 | 暂时关闭某个连接 | +| #ws打开连接 | 打开关闭的连接 | +| #ws查看连接 | 查看当前已有连接和状态 | +| #ws重新连接 | 断开已有连接并重新连接 | +| #ws连接说明 | 查看添加连接参数的说明 | + +
    + +## 反馈或建议(QQ群) + +QQ群 [698673296](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=0xSHDCUDrVbiOKe7ksEi5xpxdmJj8VRT&authKey=gnMoAHGtaQcqlGg50M%2B6QvIvKsyzMrPymK0FjIxCe7mdzUM8rSIi2jvxWczaZEU5&noverify=0&group_code=698673296) + +## onebot实现 + +
    +已实现 CQ 码 + +| CQ 码 | 功能 | +| ------------ | --------------------------- | +| [CQ:face] | [QQ表情] | +| [CQ:image] | [图片] | +| [CQ:record] | [语音] | +| [CQ:at] | [@某人] | +| [CQ:poke] | [戳一戳] | +| [CQ:music] | [音乐分享] | +| [CQ:music] | [音乐自定义分享] | +| [CQ:reply] | [回复] | +| [CQ:node] | [合并转发自定义节点] | +| [CQ:json] | [JSON消息] | + +[QQ表情]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#qq-%E8%A1%A8%E6%83%85 +[图片]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E5%9B%BE%E7%89%87 +[语音]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E8%AF%AD%E9%9F%B3 +[@某人]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E6%9F%90%E4%BA%BA +[戳一戳]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E6%88%B3%E4%B8%80%E6%88%B3 +[音乐分享]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E9%9F%B3%E4%B9%90%E5%88%86%E4%BA%AB- +[音乐自定义分享]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E9%9F%B3%E4%B9%90%E8%87%AA%E5%AE%9A%E4%B9%89%E5%88%86%E4%BA%AB- +[回复]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E5%9B%9E%E5%A4%8D +[合并转发自定义节点]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8A%82%E7%82%B9 +[JSON消息]: https://github.com/botuniverse/onebot-11/blob/master/message/segment.md#json-%E6%B6%88%E6%81%AF + +
    + +
    +已实现 API + +### 可能符合 OneBot 标准的 API + +| API | 功能 | +| --------------------- | --------------------------- | +| send_private_msg | [发送私聊消息] | +| send_group_msg | [发送群聊消息] | +| send_msg | [发送消息] | +| delete_msg | [撤回消息] | +| set_group_kick | [群组踢人] | +| set_group_ban | [群组单人禁言] | +| set_group_anonymous_ban| [群组匿名禁言] | +| set_group_whole_ban | [群组全员禁言] | +| set_group_admin | [群组设置管理员] | +| set_group_card | [设置群名片(群备注)] | +| set_group_name | [设置群名] | +| set_group_leave | [退出群组] | +| set_group_special_title| [设置群组专属头衔] | +| set_friend_add_request | [处理加好友请求] | +| set_group_add_request | [处理加群请求/邀请] | +| get_login_info | [获取登录号信息] | +| get_stranger_info | [获取陌生人信息] | +| get_friend_list | [获取好友列表] | +| get_group_info | [获取群信息] | +| get_group_list | [获取群列表] | +| get_group_member_info | [获取群成员信息] | +| get_group_member_list | [获取群成员列表] | +| get_version_info | [获取版本信息] | + +[发送私聊消息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#send_private_msg-%E5%8F%91%E9%80%81%E7%A7%81%E8%81%8A%E6%B6%88%E6%81%AF +[发送群聊消息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#send_group_msg-%E5%8F%91%E9%80%81%E7%BE%A4%E6%B6%88%E6%81%AF +[发送消息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#send_msg-%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF +[撤回消息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#delete_msg-%E6%92%A4%E5%9B%9E%E6%B6%88%E6%81%AF +[群组踢人]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_kick-%E7%BE%A4%E7%BB%84%E8%B8%A2%E4%BA%BA +[群组单人禁言]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80 +[群组匿名禁言]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_anonymous_ban-%E7%BE%A4%E7%BB%84%E5%8C%BF%E5%90%8D%E7%94%A8%E6%88%B7%E7%A6%81%E8%A8%80 +[群组全员禁言]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_whole_ban-%E7%BE%A4%E7%BB%84%E5%85%A8%E5%91%98%E7%A6%81%E8%A8%80 +[群组设置管理员]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_admin-%E7%BE%A4%E7%BB%84%E8%AE%BE%E7%BD%AE%E7%AE%A1%E7%90%86%E5%91%98 +[设置群名片(群备注)]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_card-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%90%8D%E7%89%87%E7%BE%A4%E5%A4%87%E6%B3%A8 +[设置群名]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_name-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%90%8D +[退出群组]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_leave-%E9%80%80%E5%87%BA%E7%BE%A4%E7%BB%84 +[设置群组专属头衔]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_special_title-%E8%AE%BE%E7%BD%AE%E7%BE%A4%E7%BB%84%E4%B8%93%E5%B1%9E%E5%A4%B4%E8%A1%94 +[处理加好友请求]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_friend_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82 +[处理加群请求/邀请]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_add_request-%E5%A4%84%E7%90%86%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%E9%82%80%E8%AF%B7 +[群组单人禁言]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#set_group_ban-%E7%BE%A4%E7%BB%84%E5%8D%95%E4%BA%BA%E7%A6%81%E8%A8%80 +[获取登录号信息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_login_info-%E8%8E%B7%E5%8F%96%E7%99%BB%E5%BD%95%E5%8F%B7%E4%BF%A1%E6%81%AF +[获取陌生人信息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_stranger_info-%E8%8E%B7%E5%8F%96%E9%99%8C%E7%94%9F%E4%BA%BA%E4%BF%A1%E6%81%AF +[获取好友列表]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_friend_list-%E8%8E%B7%E5%8F%96%E5%A5%BD%E5%8F%8B%E5%88%97%E8%A1%A8 +[获取群信息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_group_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E4%BF%A1%E6%81%AF +[获取群列表]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_group_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%88%97%E8%A1%A8 +[获取群成员信息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_group_member_info-%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%88%90%E5%91%98%E4%BF%A1%E6%81%AF +[获取群成员列表]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_group_member_list-%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%88%90%E5%91%98%E5%88%97%E8%A1%A8 +[获取版本信息]: https://github.com/botuniverse/onebot-11/blob/master/api/public.md#get_version_info-%E8%8E%B7%E5%8F%96%E7%89%88%E6%9C%AC%E4%BF%A1%E6%81%AF + +### 从 go-cqhttp cv 过来的api + +| 拓展 API | 功能 | +| --------------------------- | ---------------------- | +| set_group_portrait | [设置群头像] | +| get_msg | [获取消息] | +| get_forward_msg | [获取合并转发内容] | +| send_private_forward_msg | [发送合并转发(私聊)] | +| send_group_forward_msg | [发送合并转发(群聊)] | +| get_group_system_msg | [获取群系统消息] | +| get_group_root_files | [获取群根目录文件列表] | +| get_group_files_by_folder | [获取群子目录文件列表] | +| get_group_file_url | [获取群文件资源链接] | +| get_status | [获取状态] | + +[设置群头像]: https://docs.go-cqhttp.org/api/#%E8%AE%BE%E7%BD%AE%E7%BE%A4%E5%A4%B4%E5%83%8F +[获取消息]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E6%B6%88%E6%81%AF +[获取合并转发内容]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91%E5%86%85%E5%AE%B9 +[发送合并转发(私聊)]: https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-%E5%A5%BD%E5%8F%8B +[发送合并转发(群聊)]: https://docs.go-cqhttp.org/api/#%E5%8F%91%E9%80%81%E5%90%88%E5%B9%B6%E8%BD%AC%E5%8F%91-%E7%BE%A4 +[获取群系统消息]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E7%B3%BB%E7%BB%9F%E6%B6%88%E6%81%AF +[获取群根目录文件列表]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%A0%B9%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8 +[获取群子目录文件列表]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E5%AD%90%E7%9B%AE%E5%BD%95%E6%96%87%E4%BB%B6%E5%88%97%E8%A1%A8 +[获取群文件资源链接]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%BE%A4%E6%96%87%E4%BB%B6%E8%B5%84%E6%BA%90%E9%93%BE%E6%8E%A5 +[获取状态]: https://docs.go-cqhttp.org/api/#%E8%8E%B7%E5%8F%96%E7%8A%B6%E6%80%81 + +
    + +
    +已实现 Event + +| 事件类型 | Event | +| -------- | ---------------- | +| 通知事件 | [群管理员变动] | +| 通知事件 | [群成员减少] | +| 通知事件 | [群成员增加] | +| 通知事件 | [群禁言] | +| 通知事件 | [好友添加] | +| 通知事件 | [群消息撤回] | +| 通知事件 | [好友消息撤回] | +| 通知事件 | [群内戳一戳] | +| 请求事件 | [加好友请求] | +| 请求事件 | [加群请求/邀请] | + +[群管理员变动]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E7%BE%A4%E7%AE%A1%E7%90%86%E5%91%98%E5%8F%98%E5%8A%A8 +[群成员减少]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E7%BE%A4%E6%88%90%E5%91%98%E5%87%8F%E5%B0%91 +[群成员增加]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E7%BE%A4%E6%88%90%E5%91%98%E5%A2%9E%E5%8A%A0 +[群禁言]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E7%BE%A4%E7%A6%81%E8%A8%80 +[好友添加]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E5%A5%BD%E5%8F%8B%E6%B7%BB%E5%8A%A0 +[群消息撤回]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E7%BE%A4%E6%B6%88%E6%81%AF%E6%92%A4%E5%9B%9E +[好友消息撤回]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E5%A5%BD%E5%8F%8B%E6%B6%88%E6%81%AF%E6%92%A4%E5%9B%9E +[群内戳一戳]: https://github.com/botuniverse/onebot-11/blob/master/event/notice.md#%E7%BE%A4%E5%86%85%E6%88%B3%E4%B8%80%E6%88%B3 +[加好友请求]: https://github.com/botuniverse/onebot-11/blob/master/event/request.md#%E5%8A%A0%E5%A5%BD%E5%8F%8B%E8%AF%B7%E6%B1%82 +[加群请求/邀请]: https://github.com/botuniverse/onebot-11/blob/master/event/request.md#%E5%8A%A0%E7%BE%A4%E8%AF%B7%E6%B1%82%E9%82%80%E8%AF%B7 + +
    + +## TODO + +1. 更详细的帮助和设置 +2. 支持更多onebot api +3. 支持onebot v12 + +## 鸣谢 + +* [miao-plugin](https://gitee.com/yoimiya-kokomi/miao-plugin) : 使用的ui代码及实现均来自miao-plugin +* [@idanran](https://github.com/idanran) : QQNT 部分代码来源 +* [xiaofei-plugin](https://gitee.com/xfdown/xiaofei-plugin) : 音乐自定义分享授权使用 +* [yenai-plugin](https://www.yenai.ren/) : components部分代码来源 +* [onebot](https://github.com/botuniverse/onebot) : 统一的聊天机器人应用接口标准 +* [Miao-Yunzai](https://github.com/yoimiya-kokomi/Miao-Yunzai) : 喵版Yunzai [Gitee](https://gitee.com/yoimiya-kokomi/Miao-Yunzai) + / [Github](https://github.com/yoimiya-kokomi/Miao-Yunzai) +* [Yunzai-V3](https://github.com/yoimiya-kokomi/Yunzai-Bot) :Yunzai V3 - 喵喵维护版(使用 icqq) +* [Yunzai-V3](https://gitee.com/Le-niao/Yunzai-Bot) :Yunzai V3 - 乐神原版(使用 oicq) + + +## 免责声明 + +1. 功能仅限内部交流与小范围使用,请勿将Yunzai-Bot及ws-plugin用于以盈利为目的的场景 +2. 图片与其他素材均来自于网络,仅供交流学习使用,如有侵权请联系,会立即删除 + +## 其他 + +如果觉得此插件对你有帮助的话,可以点一个star,你的支持就是不断更新的动力~ + +## 访问量 + +[![访问量](https://profile-counter.glitch.me/xiaoye12123-ws-plugin/count.svg)](https://gitee.com/xiaoye12123/ws-plugin) \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/apps/admin.js b/Yunzai/plugins/ws-plugin/apps/admin.js new file mode 100644 index 0000000000000000000000000000000000000000..42bc543f949530cdd1dc7b128b9298db48724d71 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/apps/admin.js @@ -0,0 +1,666 @@ +import plugin from '../../../lib/plugins/plugin.js' +import { Config, clearWebSocket, initWebSocket, Render, Version, allSocketList, sendSocketList, createWebSocket } from '../components/index.js' +import lodash from 'lodash' + +let keys = lodash.map(Config.getCfgSchemaMap(), (i) => i.key) +let sysCfgReg = new RegExp(`^#ws设置\\s*(${keys.join('|')})?\\s*(.*)$`) +const groupReg = '^#ws(查看|删除|添加)?(禁用|启用)群([0-9]*)$' +const wsReg = '^#ws(添加|删除|打开|关闭|重新|查看)[连链]接(.*)$' + +export class setting extends plugin { + constructor() { + super({ + name: '[ws-plugin] 设置', + dsc: '[ws-plugin] 设置', + event: 'message', + priority: 1, + rule: [ + { + reg: wsReg, + fnc: 'modifyWs', + permission: 'master' + }, + { + reg: '^#ws连接说明$', + fnc: 'help', + permission: 'master' + }, + { + reg: sysCfgReg, + fnc: 'setting', + permission: 'master' + }, + { + reg: groupReg, + fnc: 'modifyGroup', + permission: 'master' + } + ] + }) + } + + async modifyGroup() { + let reg = new RegExp(groupReg) + let regRet = reg.exec(this.e.msg) + if (!regRet) { + return true + } + const type = regRet[2] + const target = type == '禁用' ? 'noGroup' : 'yesGroup' + const cfg = { + noGroup: Config.noGroup, + yesGroup: Config.yesGroup + } + const group_id = regRet[3] || this.e.group_id + let sendMsg = [] + if (regRet[1]) { + switch (regRet[1]) { + case '查看': + if (Array.isArray(cfg[target]) && cfg[target].length > 0) { + sendMsg.push(`以下为${type}群聊的群号\n`) + sendMsg.push(cfg[target].join('\n')) + } else { + sendMsg.push(`暂无${type}群聊`) + } + break; + case '删除': + let index = -1 + if (Array.isArray(cfg[target]) && cfg[target].length > 0) { + for (let i = 0; i < cfg[target].length; i++) { + if (cfg[target][i] == group_id) { + index = i + } + } + } + if (index == -1) { + sendMsg.push(`操作失败~在${type}群中没有这个群聊,当前${type}群列表:\n`) + sendMsg.push(cfg[target].join('\n')) + } else { + cfg[target].splice(index, 1) + sendMsg.push(`操作成功~从${type}群中删除了[${group_id}]!\n当前${type}列表:\n`) + sendMsg.push(cfg[target].join('\n')) + } + break; + case '添加': + let isExist = false + if (Array.isArray(cfg[target]) && cfg[target].length > 0) { + for (const item of cfg[target]) { + if (item == group_id) { + isExist = true + break + } + } + } else { + cfg[target] = [] + } + if (isExist) { + sendMsg.push(`操作失败~${type}群中已经添加了[${group_id}]\n当前${type}群列表:\n`) + sendMsg.push(cfg[target].join('\n')) + } else { + cfg[target].push(group_id) + sendMsg.push(`操作成功~向${type}群中添加了[${group_id}]!\n当前${type}群列表:\n`) + sendMsg.push(cfg[target].join('\n')) + } + default: + break; + } + } else { + let isExist = false + switch (type) { + case '禁用': + // 先看白名单有没有这个群 + if (Array.isArray(cfg['yesGroup']) && cfg['yesGroup'].length > 0) { + for (const i of cfg['yesGroup']) { + if (i == group_id) { + isExist = true + } + } + } + // 如果在白名单中则删除白名单 + if (isExist) { + cfg['yesGroup'] = cfg['yesGroup'].filter(i => i != group_id) + sendMsg.push(`操作成功~从白名单中删除了[${group_id}]!\n当前白名单列表:\n`) + sendMsg.push(cfg['yesGroup'].join('\n')) + } + // 否则添加为黑名单 + else { + // 再看看黑名单有没有这个群 + if (Array.isArray(cfg['noGroup']) && cfg['noGroup'].length > 0) { + for (const item of cfg['noGroup']) { + if (item == group_id) { + isExist = true + break + } + } + } else { + cfg['noGroup'] = [] + } + if (isExist) { + sendMsg.push(`操作失败~黑名单中已经添加了[${group_id}]\n当前黑名单列表:\n`) + sendMsg.push(cfg['noGroup'].join('\n')) + } else { + cfg['noGroup'].push(group_id) + sendMsg.push(`操作成功~向黑名单中添加了[${group_id}]!\n当前黑名单列表:\n`) + sendMsg.push(cfg['noGroup'].join('\n')) + } + } + break + case '启用': + // 先看黑名单有没有这个群 + if (Array.isArray(cfg['noGroup']) && cfg['noGroup'].length > 0) { + for (const item of cfg['noGroup']) { + if (item == group_id) { + isExist = true + break + } + } + } else { + cfg['noGroup'] = [] + } + // 如果在黑名单中则删除黑名单 + if (isExist) { + cfg['noGroup'] = cfg['noGroup'].filter(i => i != group_id) + sendMsg.push(`操作成功~从黑名单中删除了[${group_id}]!\n当前黑名单列表:\n`) + sendMsg.push(cfg['noGroup'].join('\n')) + } + // 否则添加为黑名单 + else { + // 再看看白名单有没有这个群 + if (Array.isArray(cfg['yesGroup']) && cfg['yesGroup'].length > 0) { + for (const item of cfg['yesGroup']) { + if (item == group_id) { + isExist = true + break + } + } + } else { + cfg['yesGroup'] = [] + } + if (isExist) { + sendMsg.push(`操作失败~白名单中已经添加了[${group_id}]\n当前白名单列表:\n`) + sendMsg.push(cfg['yesGroup'].join('\n')) + } else { + cfg['yesGroup'].push(group_id) + sendMsg.push(`操作成功~向白名单中添加了[${group_id}]!\n当前白名单列表:\n`) + sendMsg.push(cfg['yesGroup'].join('\n')) + } + } + break + default: + break + } + } + try { + for (const key in cfg) { + Config.modify('msg-config', key, cfg[key]) + } + } catch (error) { + sendMsg = ['操作失败...'] + logger.error(error) + } + if (sendMsg.length > 0) this.reply(sendMsg) + return true + } + + async modifyWs() { + let reg = new RegExp(wsReg) + let regRet = reg.exec(this.e.msg) + if (!regRet) { + return true + } + switch (regRet[1]) { + case '添加': + // if (regRet[2]) { + // let msg = regRet[2].split(/,|,/g) + // await this.addWs(msg) + // } else { + this.setContext('checkAddWs', this.e.isGroup) + await this.reply([ + '请输入以下参数,用逗号分割\n', + '---------------------------------\n', + '连接名字,连接类型\n', + '---------------------------------\n', + '连接名字: 用来区分每个连接\n', + '连接类型: 1:反向ws连接 2:正向ws连接 3:gscore连接 4:red连接 5:正向http 6:反向http' + ]) + // await this.reply([ + // '请一次性发送以下参数:\n', + // '-----------------------\n', + // '连接名字,连接地址,连接类型,重连间隔,最大重连次数,access-token(没有可不加)\n', + // '-----------------------\n', + // '用逗号分割,例如:\nNoneBot2,ws://127.0.0.1:8080/onebot/v11/ws,1,5,0\n', + // '如果对参数不懂意思,可以发送#ws连接说明' + // ]) + // } + break + case '删除': + if (regRet[2]) { + await this.delWs(regRet[2]) + } else { + this.setContext('checkDelWs', this.e.isGroup) + await this.reply('请继续发送需要删除的ws连接名字') + } + break + case '打开': + if (regRet[2]) { + await this.openWs(regRet[2]) + } else { + this.setContext('checkOpenWs', this.e.isGroup) + this.reply('请继续发送需要打开的ws连接名字') + } + break + case '关闭': + if (regRet[2]) { + await this.closeWs(regRet[2]) + } else { + this.setContext('checkCloseWs', this.e.isGroup) + this.reply('请继续发送需要关闭的ws连接名字') + } + break + case '重新': + if (regRet[2]) { + await this.resetWs(regRet[2]) + } else { + this.setContext('checkResetWs', this.e.isGroup) + this.reply('请继续发送需要重新连接的ws连接名字') + } + break + case '查看': + this.view() + break + default: + break + } + } + + async checkAddWs() { + if (!this.e.msg || !this.e.isMaster) { + return false + } + const msg = this.e.msg.split(/,|,/g) + let cache = await redis.get('ws-plugin:addWs:' + this.e.user_id) + let addWsMsg + if (cache) { + await redis.del('ws-plugin:addWs:' + this.e.user_id) + addWsMsg = JSON.parse(cache) + addWsMsg.push(...msg) + } else { + addWsMsg = [...msg] + } + if (addWsMsg.length < 2) { + await this.reply('格式有误,请检查后重新发送#ws添加连接') + this.finish('checkAddWs', this.e.isGroup) + return false + } + if (addWsMsg.length == 2) { + switch (addWsMsg[1]) { + case '1': + await this.reply([ + '请继续发送以下参数,用逗号分割\n', + '---------------------------------\n', + '连接地址,重连间隔(默认5),最大重连次数(默认0),access-token(默认空)\n', + '---------------------------------\n', + '连接地址: 需要连接的ws地址,比如ws://127.0.0.1:8080/onebot/v11/ws\n', + '重连间隔: 断开连接时每隔多少秒进行重新连接\n', + '最大重连次数: 达到这个数之后不进行重连,为0时会不断重连\n', + 'access-token: 访问秘钥' + ]) + break; + case '2': + await this.reply([ + '请继续发送以下参数,用逗号分割\n', + '---------------------------------\n', + '连接地址,access-token(默认空)\n', + '---------------------------------\n', + '连接地址: 需要启动的ws地址,比如127.0.0.1:8080\n', + 'access-token: 访问秘钥' + ]) + break; + case '3': + await this.reply([ + '请继续发送以下参数,用逗号分割\n', + '---------------------------------\n', + '连接地址,重连间隔(默认5),最大重连次数(默认0),access-token(默认空)\n', + '---------------------------------\n', + '连接地址: 需要连接的ws地址,比如ws://127.0.0.1:8765/ws/yunzai\n', + '重连间隔: 断开连接时每隔多少秒进行重新连接\n', + '最大重连次数: 达到这个数之后不进行重连,为0时会不断重连\n', + 'access-token: 访问秘钥' + ]) + break; + case '4': + await this.reply([ + '请继续发送以下参数,用逗号分割\n', + '---------------------------------\n', + '连接地址,Token(为空尝试自动获取),重连间隔(默认5),最大重连次数(默认0)\n', + '---------------------------------\n', + '连接地址: Host:Port,比如127.0.0.1:16530\n', + 'Token: Chronocat 连接 Token\n', + '重连间隔: 断开连接时每隔多少秒进行重新连接\n', + '最大重连次数: 达到这个数之后不进行重连,为0时会不断重连', + ]) + break; + case '5': + await this.reply([ + '请继续发送以下参数,用逗号分割\n', + '---------------------------------\n', + '连接地址,access-token(默认空)\n', + '---------------------------------\n', + '连接地址: Host:Port,比如127.0.0.1:3000\n', + 'access-token: 访问秘钥', + ]) + break; + case '6': + await this.reply([ + '请继续发送以下参数,用逗号分割\n', + '---------------------------------\n', + '连接地址\n', + '---------------------------------\n', + '连接地址: http://Host:Port,比如http://127.0.0.1:3001\n', + // 'secret: 秘钥', + ]) + break; + default: + await this.reply('格式有误,请检查后重新发送#ws添加连接') + this.finish('checkAddWs', this.e.isGroup) + await redis.del('ws-plugin:addWs:' + this.e.user_id) + return false + } + this.setContext('checkAddWs', this.e.isGroup) + await redis.setEx('ws-plugin:addWs:' + this.e.user_id, 120, JSON.stringify(addWsMsg)) + } else { + const config = { + name: addWsMsg[0], + address: addWsMsg[2], + type: Number(addWsMsg[1]), + } + switch (addWsMsg[1]) { + case '1': + case '3': + config['reconnectInterval'] = Number(addWsMsg[3]) || 5 + config['maxReconnectAttempts'] = Number(addWsMsg[4]) || 0 + config['accessToken'] = addWsMsg[5] + break; + case '4': + config['accessToken'] = addWsMsg[3] + config['reconnectInterval'] = Number(addWsMsg[4]) || 5 + config['maxReconnectAttempts'] = Number(addWsMsg[5]) || 0 + break + case '2': + case '5': + config['accessToken'] = addWsMsg[3] + break + default: + break; + } + // config.uin = Number(this.e.bot.uin || this.e.self_id) || String(this.e.bot.uin || this.e.self_id) + if (this.e.group) { + const seld_id = this.e.group?.bot?.uin || this.e.self_id + config.uin = Number(seld_id) || String(seld_id) + } else if (this.e.friend) { + const seld_id = this.e.friend?.bot?.uin || this.e.self_id + config.uin = Number(seld_id) || String(seld_id) + } + await this.addWs(config) + this.finish('checkAddWs', this.e.isGroup) + await redis.del('ws-plugin:addWs:' + this.e.user_id) + } + return false + } + + async setting(e) { + let cfgReg = sysCfgReg + let regRet = cfgReg.exec(e.msg) + let cfgSchemaMap = Config.getCfgSchemaMap() + if (!regRet) { + return true + } + + if (regRet[1]) { + // 设置模式 + let val = regRet[2] || '' + + if (regRet[1] == '全部') { + val = !/关闭/.test(val) + for (const i of keys) { + if (typeof cfgSchemaMap[i].def == 'boolean') { + if (cfgSchemaMap[i].key == '全部') { + await redis.set('Yz:ws-plugin:setAll', val ? 1 : 0) + } else { + Config.modify(cfgSchemaMap[i].fileName, cfgSchemaMap[i].cfgKey, val) + } + } + } + } else { + let cfgSchema = cfgSchemaMap[regRet[1]] + if (cfgSchema.input) { + val = cfgSchema.input(val) + } else { + val = cfgSchema.type === 'num' ? (val * 1 || cfgSchema.def) : !/关闭/.test(val) + } + Config.modify(cfgSchema.fileName, cfgSchema.cfgKey, val) + } + } + + let schema = Config.getCfgSchema() + let cfg = Config.getCfg() + cfg.setAll = (await redis.get('Yz:ws-plugin:setAll')) == 1 + + // 渲染图像 + return await Render.render('admin/index', { + schema, + cfg, + isMiao: Version.isMiao + }, { e, scale: 1.4 }) + } + + async addWs(msg) { + if (Array.isArray(msg) && msg.length != 5 && msg.length != 6 && msg.length != 7) { + await this.reply('格式有误,请检查后重新发送#ws添加连接') + return false + } else { + let value + if (Array.isArray(msg)) { + value = { + name: msg[0], + address: msg[1], + type: msg[2], + reconnectInterval: msg[3], + maxReconnectAttempts: msg[4], + } + if (msg[5]) { + value.accessToken = msg[5] + } + } else { + value = msg + } + let old = Config.servers + if (Array.isArray(old) && old.length > 0) { + for (const item of old) { + if (item.name == value.name) { + this.reply(`已经有连接名为${value.name}的连接了\n连接地址为${item.address}\n请删除旧的连接或更改连接名字`) + return false + } + // else if (item.address == value.address) { + // this.reply(`已经有连接地址为${value.address}的连接了\n连接名字为${item.name}\n请删除旧的连接或更改连接地址`) + // return false + // } + } + } + try { + Config.modifyarr('ws-config', 'servers', value) + this.reply('操作成功~请留意控制台输出~') + } catch (error) { + logger.error(error) + this.reply('操作失败~') + } + return true + } + } + + async openWs(msg) { + let servers = Config.servers + for (let i = 0; i < servers.length; i++) { + if (servers[i].name == msg) { + delete servers[i].close + servers[i].closed = false + try { + Config.setArr('ws-config', 'servers', i, servers[i]) + this.reply('操作成功~请留意控制台输出~') + return true + } catch (error) { + logger.error(error) + this.reply('操作失败...') + return true + } + } + } + this.reply(`没有连接名字为${msg}的连接`) + return true + } + + async closeWs(msg) { + let servers = Config.servers + for (let i = 0; i < servers.length; i++) { + if (servers[i].name == msg) { + delete servers[i].close + servers[i].closed = true + try { + Config.setArr('ws-config', 'servers', i, servers[i]) + this.reply('操作成功~请留意控制台输出~') + return true + } catch (error) { + logger.error(error) + this.reply('操作失败...') + return true + } + } + } + this.reply(`没有连接名字为${msg}的连接`) + return true + } + + async checkOpenWs() { + if (!this.e.msg || !this.e.isMaster) { + return false + } + let msg = this.e.msg + await this.openWs(msg) + this.finish('checkOpenWs', this.e.isGroup) + } + + async checkCloseWs() { + if (!this.e.msg || !this.e.isMaster) { + return false + } + let msg = this.e.msg + await this.closeWs(msg) + this.finish('checkCloseWs', this.e.isGroup) + } + + async delWs(msg) { + let servers = Config.servers + for (let i = 0; i < servers.length; i++) { + if (servers[i].name == msg) { + try { + Config.delServersArr(servers[i].name) + this.reply('操作成功~请留意控制台输出~') + return true + } catch (error) { + logger.error(error) + this.reply('操作失败~') + return true + } + } + } + this.reply(`没有连接名字为${msg}的连接`) + return true + } + + async help() { + await this.reply([ + 'ws连接说明:\n', + '1.连接名字:一般代表需要连接的bot名字\n', + '2.连接地址:需要连接的ws地址或者本地开启的地址:端口\n', + '3.连接类型:1.反向ws连接 2.正向ws连接 3.gsuid_core专用连接\n', + '4.重连间隔:连接被断开之后每隔一段时间进行重新连接,单位秒,0代表不重连\n', + '5.最大重连次数:每次连接失败时+1,达到最大重连次数时停止重新连接,0代表一直重连\n', + '6.access-token:访问密钥' + ]) + return true + } + + async checkDelWs() { + if (!this.e.msg || !this.e.isMaster) { + return false + } + let msg = this.e.msg + await this.delWs(msg) + this.finish('checkDelWs', this.e.isGroup) + } + + async checkResetWs() { + if (!this.e.msg || !this.e.isMaster) { + return false + } + let msg = this.e.msg + await this.resetWs(msg) + this.finish('checkResetWs', this.e.isGroup) + } + + async resetWs(msg) { + for (const i of sendSocketList) { + if (i.name == msg) { + i.close() + setTimeout(async () => { + await createWebSocket({ + name: i.name, + address: i.address, + type: i.type, + reconnectInterval: i.reconnectInterval, + maxReconnectAttempts: i.maxReconnectAttempts, + uin: i.uin, + accessToken: i.accessToken + }) + }, 500) + this.reply('操作成功~请留意控制台输出~') + return true + } + } + this.reply(`没有连接名字为${msg}的连接或已关闭连接`) + return true + } + + async view() { + const msg = [] + for (const i of Config.servers) { + // if (i.type == 4) continue + if (msg.length != 0) msg.push('\n----------------\n') + let status = '已关闭' + for (const s of allSocketList) { + if (s.name == i.name) { + switch (s.status) { + case 0: + status = '已关闭' + break; + case 1: + status = '正常' + break + case 3: + status = '断线重连中' + break + default: + break; + } + } + } + msg.push(`连接名字: ${i.name}\n连接类型: ${i.type}\n当前状态: ${status}`) + } + if (msg.length > 0) { + await this.reply(msg) + } else { + await this.reply('暂无连接') + } + return true + } +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/apps/help.js b/Yunzai/plugins/ws-plugin/apps/help.js new file mode 100644 index 0000000000000000000000000000000000000000..12dca07cfaa7c976b073ff5b4c5b51601953f585 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/apps/help.js @@ -0,0 +1,112 @@ +import plugin from '../../../lib/plugins/plugin.js' +import { Render, Version, Config } from '../components/index.js' +import { helpCfg, helpList } from '../config/system/help_system.js' +import { style } from '../resources/help/imgs/config.js' +import _ from 'lodash' + +export class setting extends plugin { + constructor() { + super({ + name: '[ws-plugin] 帮助', + dsc: '[ws-plugin] 帮助', + event: 'message', + priority: 1, + rule: [ + { + reg: '^#ws版本$', + fnc: 'version' + }, + { + reg: '^#ws帮助$', + fnc: 'help', + permission: 'master' + } + ] + }) + + } + async version(e) { + return await Render.render('help/version-info', { + currentVersion: Version.version, + changelogs: Version.changelogs, + elem: 'cryo' + }, { e, scale: 1.2 }) + } + + async help(e) { + let helpGroup = [] + _.forEach(helpList, (group) => { + _.forEach(group.list, (help) => { + let icon = help.icon * 1 + if (!icon) { + help.css = 'display:none' + } else { + let x = (icon - 1) % 10 + let y = (icon - x - 1) / 10 + help.css = `background-position:-${x * 50}px -${y * 50}px` + } + }) + + helpGroup.push(group) + }) + + let themeData = await getThemeData(helpCfg, helpCfg) + return await Render.render('help/index', { + helpCfg, + helpGroup, + ...themeData, + element: 'default' + }, { e, scale: 1.6 }) + } + +} + +async function getThemeCfg() { + let resPath = '{{_res_path}}/help/imgs/' + return { + main: `${resPath}/main.png`, + bg: `${resPath}/bg.jpg`, + style: style + } +} + +async function getThemeData(diyStyle, sysStyle) { + let helpConfig = _.extend({}, sysStyle, diyStyle) + let colCount = Math.min(5, Math.max(parseInt(helpConfig?.colCount) || 3, 2)) + let colWidth = Math.min(500, Math.max(100, parseInt(helpConfig?.colWidth) || 265)) + let width = Math.min(2500, Math.max(800, colCount * colWidth + 30)) + let theme = await getThemeCfg() + let themeStyle = theme.style || {} + let ret = [` + body{background-image:url(${theme.bg});width:${width}px;} + .container{background-image:url(${theme.main});width:${width}px;} + .help-table .td,.help-table .th{width:${100 / colCount}%} + `] + let css = function (sel, css, key, def, fn) { + let val = getDef(themeStyle[key], diyStyle[key], sysStyle[key], def) + if (fn) { + val = fn(val) + } + ret.push(`${sel}{${css}:${val}}`) + } + css('.help-title,.help-group', 'color', 'fontColor', '#ceb78b') + css('.help-title,.help-group', 'text-shadow', 'fontShadow', 'none') + css('.help-desc', 'color', 'descColor', '#eee') + css('.cont-box', 'background', 'contBgColor', 'rgba(43, 52, 61, 0.8)') + css('.cont-box', 'backdrop-filter', 'contBgBlur', 3, (n) => diyStyle.bgBlur === false ? 'none' : `blur(${n}px)`) + css('.help-group', 'background', 'headerBgColor', 'rgba(34, 41, 51, .4)') + css('.help-table .tr:nth-child(odd)', 'background', 'rowBgColor1', 'rgba(34, 41, 51, .2)') + css('.help-table .tr:nth-child(even)', 'background', 'rowBgColor2', 'rgba(34, 41, 51, .4)') + return { + style: ``, + colCount + } +} + +function getDef() { + for (let idx in arguments) { + if (!_.isUndefined(arguments[idx])) { + return arguments[idx] + } + } +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/apps/message/message.js b/Yunzai/plugins/ws-plugin/apps/message/message.js new file mode 100644 index 0000000000000000000000000000000000000000..e1908bec0f81100cf6bac154e435b9ced4586b6e --- /dev/null +++ b/Yunzai/plugins/ws-plugin/apps/message/message.js @@ -0,0 +1,277 @@ +import { sendSocketList, Config, Version } from '../../components/index.js' +import { makeOneBotReportMsg, makeGSUidReportMsg, setGuildLatestMsgId, setMsgMap } from '../../model/index.js' +import _ from 'lodash' +import cfg from '../../../../lib/config/config.js' + + +Bot.on('message', async e => { + if (e.self_id == '88888'){ + if (e.group?.bot?.uin) { + e.self_id = e.group.bot.uin + } else if (e.friend?.bot?.uin) { + e.self_id = e.friend.bot.uin + } + e.bot = Bot[e.self_id] + } + // 被禁言或者全体禁言 + if (Config.muteStop && (e.group?.mute_left > 0 || e.group?.all_muted)) return false + // 如果没有已连接的Websocket + if (sendSocketList.length == 0) return false + if (e.group_id) { + // 判断云崽白名单 + const whiteGroup = Config.whiteGroup + if (Array.isArray(whiteGroup) && whiteGroup.length > 0) { + if (!whiteGroup.some(i => i == e.group_id)) return false + } + // 判断插件白名单 + const yesGroup = Config.yesGroup + if (Array.isArray(yesGroup) && yesGroup.length > 0) { + if (!yesGroup.some(i => i == e.group_id)) return false + } + // 判断云崽黑名单 + const blackGroup = Config.blackGroup + if (Array.isArray(blackGroup) && blackGroup.length > 0) { + if (blackGroup.some(i => i == e.group_id)) return false + } + // 判断插件黑名单 + const noGroup = Config.noGroup + if (Array.isArray(noGroup) && noGroup.length > 0) { + if (noGroup.some(i => i == e.group_id)) return false + } + } + // 判断插件前缀 + if (Array.isArray(Config.noMsgStart) && Config.noMsgStart.length > 0) { + if (e.message?.[0]?.type === 'text') { + if (Config.noMsgStart.some(i => e.message[0].text.startsWith(i))) return false + } + } + let isMaster = e.isMaster + if (Version.isTrss) { + if (e.user_id && cfg.master[e.self_id]?.includes(String(e.user_id))) { + isMaster = true + } + } + const message_id = Math.floor(Math.random() * Math.pow(2, 32)) | 0 + let msg = { + time: e.time, + message_id: e.message_id, + message: _.cloneDeep(e.message), + rand: e.rand, + seq: e.seq, + source: e.source, + user_id: e.user_id, + self_id: e.self_id, + isMaster, + sender: e.sender, + param: { + time: e.time, + self_id: e.self_id, + post_type: e.post_type, + message_type: e.message_type, + sub_type: e.sub_type, + message_id, + user_id: e.user_id, + font: 0, + sender: e.sender, + anonymous: e.anonymous ? { + id: e.anonymous.id, + name: e.anonymous.name, + flag: e.anonymous.flag + } : null + } + } + let message = [] + //增加isGroup e.isPrivate + if (e.guild_id) { + setGuildLatestMsgId(e.message_id) + //处理成message + if (e.content) { + let content = toMsg(e.content) + message.push(...content) + } + if (e.attachments) { + e.attachments.forEach(i => { + if (i.content_type.startsWith('image')) { + message.push({ + type: 'image', + file: i.filename, + url: i.url + }) + } + }) + } + msg.message = message + + msg.isGuild = true + msg.param = { + time: Math.floor(new Date(msg.timestamp).getTime() / 1000), + post_type: 'message', + message_type: 'guild', + sub_type: 'channel', + guild_id: e.guild_id, + channel_id: e.channel_id, + user_id: e.author.id, + message_id: e.message_id, + self_id: e.bot.appID, + sender: { + user_id: e.author.id, + nickname: e.author.username, + tiny_id: e.author.id, + }, + self_tiny_id: e.bot.appID, + } + } else if (e.message_type == 'group') { + msg.isGroup = true + msg.group_id = e.group_id + msg.param.group_id = e.group_id + msg.self_id = e.group?.bot?.uin || msg.self_id + } else if (e.message_type == 'private') { + msg.isPrivate = true + msg.self_id = e.friend?.bot?.uin || msg.self_id + } else { + return false + } + // 判断云崽前缀 + msg = onlyReplyAt(msg) + if (!msg) return false + for (const i of sendSocketList) { + if (i.status == 1) { + let reportMsg = null + switch (Number(i.type)) { + case 1: + case 2: + case 6: + if (Version.isTrss) { + if (i.uin != e.self_id) continue + if (!Version.protocol.some(i => i == e.bot?.version?.name)) continue + } + e.reply = reply(e) + reportMsg = await makeOneBotReportMsg(msg) + break; + case 3: + reportMsg = await makeGSUidReportMsg(msg) + break + default: + break; + } + if (reportMsg) i.ws.send(reportMsg) + } + } +}) + +function reply(e) { + if (!Version.isTrss) { + const replyNew = e.reply + return async function (massage, quote = false, data = {}) { + const ret = await replyNew(massage, quote, data) + if (ret) { + setMsgMap({ + message_id: ret.message_id, + time: ret.time, + seq: ret.seq, + rand: ret.rand, + user_id: e.user_id, + group_id: e.group_id, + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + }) + } + return ret + } + } else { + if (e.bot?.version?.name == 'ICQQ') { + return async function (massage, quote = false) { + let ret + if (e.isGroup) { + if (e.group?.sendMsg) { + ret = await e.group.sendMsg(massage, quote) + } else { + ret = await e.bot.pickGroup(e.group_id).sendMsg(massage, quote) + } + } else { + if (e.friend?.sendMsg) { + ret = await e.friend.sendMsg(massage, quote) + } else { + ret = await e.bot.pickFriend(e.user_id).sendMsg(massage, quote) + } + } + if (ret) { + setMsgMap({ + message_id: ret.message_id, + time: ret.time, + seq: ret.seq, + rand: ret.rand, + user_id: e.user_id, + group_id: e.group_id, + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + }) + } + return ret + } + } + return e.reply + } +} + +function onlyReplyAt(e) { + if (!e.message) return false + + let groupCfg = Version.isTrss ? cfg.getGroup(e.self_id, e.group_id) : cfg.getGroup(e.group_id) + if (groupCfg.onlyReplyAt != 1 || !groupCfg.botAlias || e.isPrivate) return e + + let at = atBot(e) + if (at) return e + e = hasAlias(e, groupCfg) + if (e) return e + + return false +} + +function atBot(e) { + for (const i of e.message) { + if (i.type === 'at') { + if (i.qq == e.self_id) return true + } + } + return false +} + +function hasAlias(e, groupCfg) { + if (e.message[0].type === 'text') { + let alias = groupCfg.botAlias + if (!Array.isArray(alias)) { + alias = [alias] + } + for (let name of alias) { + if (e.message[0].text.startsWith(name)) { + e.message[0].text = _.trimStart(e.message[0].text, name).trim() + return e + } + } + } + return false +} + +function toMsg(content) { + const regex = /<@!(\d+)>||([^<]+)/g; + let match; + const result = []; + while ((match = regex.exec(content)) !== null) { + if (match[1]) { + result.push({ + type: 'at', + qq: match[1] + }); + } else if (match[2]) { + result.push({ + type: 'face', + id: parseInt(match[2]) + }); + } else if (match[3]) { + result.push({ + type: 'text', + text: match[3] + }); + } + } + return result; +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/apps/notice/notice.js b/Yunzai/plugins/ws-plugin/apps/notice/notice.js new file mode 100644 index 0000000000000000000000000000000000000000..443ad25e5a6bfe89abb9d3f01e52511e549f9f9f --- /dev/null +++ b/Yunzai/plugins/ws-plugin/apps/notice/notice.js @@ -0,0 +1,184 @@ +import { sendSocketList, Config, Version } from '../../components/index.js' +import { setMsgMap } from '../../model/index.js' + +Bot.on('notice', async e => { + if (e.self_id == '88888'){ + if (e.group?.bot?.uin) { + e.self_id = e.group.bot.uin + } else if (e.friend?.bot?.uin) { + e.self_id = e.friend.bot.uin + } + e.bot = Bot[e.self_id] + } + if (Config.muteStop && (e.group?.mute_left > 0 || e.group?.all_muted)) return false + if (sendSocketList.length == 0) return false + if (e.group_id) { + // 判断云崽白名单 + const whiteGroup = Config.whiteGroup + if (Array.isArray(whiteGroup) && whiteGroup.length > 0) { + if (!whiteGroup.some(i => i == e.group_id)) return false + } + // 判断插件白名单 + const yesGroup = Config.yesGroup + if (Array.isArray(yesGroup) && yesGroup.length > 0) { + if (!yesGroup.some(i => i == e.group_id)) return false + } + // 判断云崽黑名单 + const blackGroup = Config.blackGroup + if (Array.isArray(blackGroup) && blackGroup.length > 0) { + if (blackGroup.some(i => i == e.group_id)) return false + } + // 判断插件黑名单 + const noGroup = Config.noGroup + if (Array.isArray(noGroup) && noGroup.length > 0) { + if (noGroup.some(i => i == e.group_id)) return false + } + } + e.reply = reply(e) + let other = {} + if (e.notice_type == 'group') { + other.group_id = e.group_id + other.user_id = e.user_id + other.operator_id = e.operator_id + switch (e.sub_type) { + //群员增加 + case 'increase': + if (!Config.groupIncrease) return false + other.notice_type = 'group_increase' + other.sub_type = 'approve' + other.operator_id = e.user_id + break; + //群员减少 + case 'decrease': + if (!Config.groupDecrease) return false + other.notice_type = 'group_decrease' + other.sub_type = e.operator_id == e.user_id ? 'leave' : 'kick' + if (e.user_id == Bot.uin) other.sub_type = 'kick_me' + break + //戳一戳 + case 'poke': + if (!Config.groupPoke) return false + other.notice_type = 'notify' + other.sub_type = 'poke' + other.user_id = e.operator_id + other.target_id = e.target_id + break + //群管理变动 + case 'admin': + if (!Config.groupAdmin) return false + other.notice_type = 'group_admin' + other.sub_type = e.set ? 'set' : 'unset' + break + //禁言 + case 'ban': + if (!Config.groupBan) return false + other.notice_type = 'group_ban' + other.sub_type = e.duration == 0 ? 'lift_ban' : 'ban' + other.duration = e.duration + break + //群消息撤回 + case 'recall': + if (!Config.groupRecall) return false + other.notice_type = 'group_recall' + other.message_id = e.rand + break + default: + return false + } + } else if (e.notice_type == 'friend') { + other.user_id = e.user_id + switch (e.sub_type) { + //好友添加 + case 'increase': + if (!Config.friendIncrease) return false + other.notice_type = 'friend_add' + break + //好友消息撤回 + case 'recall': + if (!Config.friendRecall) return false + other.notice_type = 'friend_recall' + other.message_id = e.rand + break + default: + return false + } + } else { + return false + } + let msg = { + time: Date.parse(new Date()) / 1000, + self_id: e.self_id, + post_type: 'notice', + ...other + } + msg = JSON.stringify(msg) + for (const i of sendSocketList) { + if (i.status == 1) { + switch (Number(i.type)) { + case 1: + case 2: + if (Version.isTrss) { + if (i.uin != e.self_id) continue + if (!Version.protocol.some(i => i == e.bot?.version?.name)) continue + } + i.ws.send(msg) + break; + default: + break; + } + } + } +}) + +function reply(e) { + if (!Version.isTrss) { + const replyNew = e.reply + return async function (massage, quote = false, data = {}) { + const ret = await replyNew(massage, quote, data) + if (ret) { + setMsgMap({ + message_id: ret.message_id, + time: ret.time, + seq: ret.seq, + rand: ret.rand, + user_id: e.user_id, + group_id: e.group_id, + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + }) + } + return ret + } + } else { + if (e.bot?.version?.name == 'ICQQ') { + return async function (massage, quote = false) { + let ret + if (e.isGroup) { + if (e.group?.sendMsg) { + ret = await e.group.sendMsg(massage, quote) + } else { + ret = await e.bot.pickGroup(e.group_id).sendMsg(massage, quote) + } + } else { + if (e.friend?.sendMsg) { + ret = await e.friend.sendMsg(massage, quote) + } else { + ret = await e.bot.pickFriend(e.user_id).sendMsg(massage, quote) + } + } + if (ret) { + setMsgMap({ + message_id: ret.message_id, + time: ret.time, + seq: ret.seq, + rand: ret.rand, + user_id: e.user_id, + group_id: e.group_id, + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + }) + } + return ret + } + } + return e.reply + } +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/apps/request/request.js b/Yunzai/plugins/ws-plugin/apps/request/request.js new file mode 100644 index 0000000000000000000000000000000000000000..a6b6121bcace2412f0a14e902a15bff2e677839c --- /dev/null +++ b/Yunzai/plugins/ws-plugin/apps/request/request.js @@ -0,0 +1,65 @@ +import { sendSocketList, Config, Version } from '../../components/index.js' + +Bot.on('request', async e => { + if (sendSocketList.length == 0) return false + let other = {} + switch (e.request_type) { + case 'friend': + other.request_type = 'friend' + switch (e.sub_type) { + case 'add': + if (!Config.friendAdd) return false + break; + default: + return false + } + break; + case 'group': + other.request_type = 'group' + other.group_id = e.group_id + switch (e.sub_type) { + case 'invite': + if (!Config.groupInvite) return false + other.sub_type = 'invite' + break; + case 'add': + if (!Config.groupAdd) return false + other.sub_type = 'add' + break; + + default: + return false; + } + break; + + default: + return false; + } + + let msg = { + time: e.time, + self_id: e.self_id, + post_type: 'request', + flag: e.flag, + user_id: e.user_id, + comment: e.comment, + ...other + } + msg = JSON.stringify(msg) + sendSocketList.forEach(i => { + if (i.status == 1) { + switch (Number(i.type)) { + case 1: + case 2: + if (Version.isTrss) { + if (i.uin != e.self_id) return + if (!Version.protocol.some(i => i == e.bot?.version?.name)) return + } + i.ws.send(msg) + break; + default: + break; + } + } + }) +}) \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/apps/update.js b/Yunzai/plugins/ws-plugin/apps/update.js new file mode 100644 index 0000000000000000000000000000000000000000..bbc1655c0582857d37233d174f90c3da826525b5 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/apps/update.js @@ -0,0 +1,218 @@ +import plugin from '../../../lib/plugins/plugin.js' +import lodash from 'lodash' +import { createRequire } from 'module' +import { Restart } from '../../other/restart.js' +import common from '../../../lib/common/common.js' + +const require = createRequire(import.meta.url) +const { exec, execSync } = require('child_process') + +let uping = false + +export class update extends plugin { + constructor() { + super({ + name: '[ws-plugin] 插件更新', + dsc: '[ws-plugin] 插件更新', + event: 'message', + priority: 1, + rule: [ + { + reg: '^#ws(插件)?(强制)?更新$', + fnc: 'update' + }, + { + reg: '^#ws(插件)?更新日志$', + fnc: 'updateLog' + } + ] + }) + this.typeName = 'ws-plugin' + } + + async update() { + if (!this.e.isMaster) return false + if (uping) { + await this.reply('已有命令更新中..请勿重复操作') + return + } + /** 获取插件 */ + let plugin = 'ws-plugin' + + /** 检查git安装 */ + if (!await this.checkGit()) return + + /** 执行更新 */ + await this.runUpdate(plugin) + + /** 是否需要重启 */ + if (this.isUp) { + // await this.reply('即将执行重启,以应用更新') + setTimeout(() => this.restart(), 2000) + } + } + + restart() { + new Restart(this.e).restart() + } + + async checkGit() { + let ret = await execSync('git --version', { encoding: 'utf-8' }) + if (!ret || !ret.includes('git version')) { + await this.reply('请先安装git') + return false + } + + return true + } + + async runUpdate(plugin = '') { + this.isNowUp = false + + let cm = `cd "plugins/${plugin}" && git pull --no-rebase` + + let type = '更新' + if (this.e.msg.includes('强制')) { + type = '强制更新' + cm = `cd "plugins/${plugin}" && git reset --hard && git pull --rebase --allow-unrelated-histories` + } + + this.oldCommitId = await this.getcommitId(plugin) + + await this.reply(`开始执行${type}操作...`) + uping = true + let ret = await this.execSync(cm) + uping = false + + if (ret.error) { + logger.mark(`${this.e.logFnc} 更新失败:${this.typeName}`) + this.gitErr(ret.error, ret.stdout) + return false + } + + let time = await this.getTime(plugin) + + if (/Already up|已经是最新/g.test(ret.stdout)) { + await this.reply(`${this.typeName}已经是最新\n最后更新时间:${time}`) + } else { + await this.reply(`${this.typeName}更新成功\n更新时间:${time}`) + this.isUp = true + let log = await this.getLog(plugin) + await this.reply(log) + } + + logger.mark(`${this.e.logFnc} 最后更新时间:${time}`) + + return true + } + + async gitErr(err, stdout) { + let msg = '更新失败!' + let errMsg = err.toString() + stdout = stdout.toString() + + if (errMsg.includes('Timed out')) { + let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') + await this.reply(msg + `\n连接超时:${remote}`) + return + } + + if (/Failed to connect|unable to access/g.test(errMsg)) { + let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '') + await this.reply(msg + `\n连接失败:${remote}`) + return + } + + if (errMsg.includes('be overwritten by merge')) { + await this.reply(msg + `存在冲突:\n${errMsg}\n` + '请解决冲突后再更新,或者执行#ws强制更新,放弃本地修改') + return + } + + if (stdout.includes('CONFLICT')) { + await this.reply([msg + '存在冲突\n', errMsg, stdout, '\n请解决冲突后再更新,或者执行#ws强制更新,放弃本地修改']) + return + } + + await this.reply([errMsg, stdout]) + } + + async getcommitId(plugin = '') { + let cm = `cd "plugins/${plugin}" && git rev-parse --short HEAD` + + let commitId = await execSync(cm, { encoding: 'utf-8' }) + commitId = lodash.trim(commitId) + + return commitId + } + + async getTime(plugin = '') { + let cm = `cd "plugins/${plugin}" && git log -1 --pretty=format:"%cd" --date=format:"%F %T"` + + let time = '' + try { + time = await execSync(cm, { encoding: 'utf-8' }) + time = lodash.trim(time) + } catch (error) { + logger.error(error.toString()) + time = '获取时间失败' + } + + return time + } + + async execSync(cmd) { + return new Promise((resolve, reject) => { + exec(cmd, { windowsHide: true }, (error, stdout, stderr) => { + resolve({ error, stdout, stderr }) + }) + }) + } + + async getLog(plugin = '') { + let cm = 'git log -100 --pretty="%h||[%cd] %s" --date=format:"%F %T"' + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + + let logAll + try { + logAll = await execSync(cm, { encoding: 'utf-8' }) + } catch (error) { + logger.error(error.toString()) + await this.reply(error.toString()) + } + + if (!logAll) return false + + logAll = logAll.trim().split('\n') + + let log = [] + for (let str of logAll) { + str = str.split('||') + if (str[0] == this.oldCommitId) break + if (str[1].includes('Merge branch')) continue + log.push(str[1]) + } + let line = log.length + log = log.join('\n\n') + + if (log.length <= 0) return '' + + let end = '' + try { + cm = 'git config -l' + if (plugin) cm = `cd "plugins/${plugin}" && ${cm}` + end = await execSync(cm, { encoding: 'utf-8' }) + end = end.match(/remote\..*\.url=.+/g).join('\n\n').replace(/remote\..*\.url=/g, '') + } catch (error) { + logger.error(error.toString()) + await this.reply(error.toString()) + } + + return common.makeForwardMsg(this.e, [log, end], `${plugin || 'ws-plugin'} 更新日志,共${line}条`) + } + + async updateLog() { + let log = await this.getLog('ws-plugin') + await this.reply(log) + } + +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/components/Client.js b/Yunzai/plugins/ws-plugin/components/Client.js new file mode 100644 index 0000000000000000000000000000000000000000..d66894fa336ffc885091447306c3b6b998c6f845 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/Client.js @@ -0,0 +1,446 @@ +import WebSocket, { WebSocketServer } from 'ws' +import { getApiData, makeGSUidSendMsg, lifecycle, heartbeat, setMsgMap } from '../model/index.js' +import { Version, Config } from './index.js' +import express from "express" +import http from "http" +import fetch from 'node-fetch' + +export default class Client { + constructor({ name, address, type, reconnectInterval, maxReconnectAttempts, accessToken, uin = Bot.uin, closed = false }) { + this.name = name; + this.address = address; + this.type = type; + this.reconnectInterval = reconnectInterval; + this.maxReconnectAttempts = maxReconnectAttempts; + this.accessToken = accessToken; + this.uin = Number(uin) + this.ws = null + this.status = 0 + this.closed = closed + } + + reconnectCount = 1 + + timer = null + + stopReconnect = false + + createWs() { + try { + const headers = { + 'X-Self-ID': this.uin, + 'X-Client-Role': 'Universal', + 'User-Agent': `ws-plugin/${Version.version}` + } + if (this.accessToken) headers["Authorization"] = 'Token ' + this.accessToken + this.ws = new WebSocket(this.address, { headers }) + } catch (error) { + logger.error(`[ws-plugin] 出错了,可能是ws地址填错了~\nws名字: ${this.name}\n地址: ${this.address}\n类型: 1`) + return + } + this.ws.on('open', async () => { + logger.mark(`[ws-plugin] ${this.name} 已连接`); + if (this.status == 3 && this.reconnectCount > 1 && Config.reconnectToMaster) { + await this.sendMasterMsg(`${this.name} 重连成功~`) + } else if (this.status == 0 && Config.firstconnectToMaster) { + await this.sendMasterMsg(`${this.name} 连接成功~`) + } + this.ws.send(lifecycle(this.uin)) + this.status = 1 + this.reconnectCount = 1 + if (Config.heartbeatInterval > 0) { + this.timer = setInterval(async () => { + this.ws.send(heartbeat(this.uin)) + }, Config.heartbeatInterval * 1000) + } + }) + this.ws.on('message', async (event) => { + let data + if (Buffer.isBuffer(event)) { + data = JSON.parse(event.toString()) + } else { + data = JSON.parse(event.data); + } + let result = await this.getData(data.action, data.params, data.echo) + this.ws.send(JSON.stringify(result)); + }) + this.ws.on('close', async code => { + logger.warn(`[ws-plugin] ${this.name} 连接已关闭`); + clearInterval(this.timer) + if (Config.disconnectToMaster && this.reconnectCount == 1 && this.status == 1) { + await this.sendMasterMsg(`${this.name} 已断开连接...`) + } else if (Config.firstconnectToMaster && this.reconnectCount == 1 && this.status == 0) { + await this.sendMasterMsg(`${this.name} 连接失败...`) + } + this.status = 3 + if (!this.stopReconnect && ((this.reconnectCount < this.maxReconnectAttempts) || this.maxReconnectAttempts <= 0)) { + if (code === 1005) { + logger.warn(`[ws-plugin] ${this.name} 连接异常,停止重连`); + this.status = 0 + } else { + logger.warn(`[ws-plugin] ${this.name} 开始尝试重新连接第${this.reconnectCount}次`); + this.reconnectCount++ + setTimeout(() => { + this.createWs() + }, this.reconnectInterval * 1000); + } + } else { + this.stopReconnect = false + this.status = 0 + logger.warn(`[ws-plugin] ${this.name} 达到最大重连次数或关闭连接,停止重连`); + } + }) + this.ws.on('error', (event) => { + logger.error(`[ws-plugin] ${this.name} 连接失败\n${event}`); + }) + } + + createServer() { + const parts = this.address.split(':'); + this.host = parts[0]; + this.port = parts[1]; + this.arr = [] + this.express = express() + this.server = http.createServer(this.express) + this.server.on("upgrade", (req, socket, head) => { + if (this.accessToken) { + const token = req.headers['authorization']?.replace('Token ', '') + if (!token) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return + } else if (this.accessToken != token) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + this.wss.handleUpgrade(req, socket, head, conn => { + if (req.url === '/') { + conn.id = req.headers["sec-websocket-key"] + let time = null + conn.send(lifecycle(this.uin)) + if (Config.heartbeatInterval > 0) { + time = setInterval(async () => { + conn.send(heartbeat(this.uin)) + }, Config.heartbeatInterval * 1000) + } + logger.mark(`[ws-plugin] ${this.name} 接受 WebSocket 连接: ${req.connection.remoteAddress}`); + conn.on("error", (event) => { + logger.error(`[ws-plugin] ${this.name} 接受 WebSocket 连接时出现错误: ${event}`) + }) + conn.on("close", () => { + if (this.stopReconnect = false) { + logger.warn(`[ws-plugin] ${this.name} 关闭 WebSocket 连接`); + } + this.arr = this.arr.filter(i => i.id != req.headers["sec-websocket-key"]) + clearInterval(time) + }) + conn.on("message", async event => { + const data = JSON.parse(event) + const result = await this.getData(data.action, data.params, data.echo) + conn.send(JSON.stringify(result)); + }) + this.arr.push(conn) + } else if (req.url === '/api' || req.url === '/api/') { + logger.mark(`[ws-plugin] ${this.name} 接受 WebSocket api 连接: ${req.connection.remoteAddress}`); + conn.on("error", (event) => { + logger.error(`[ws-plugin] ${this.name} 接受 WebSocket api 连接时出现错误: ${event}`) + }) + conn.on("close", () => { + if (this.stopReconnect = false) { + logger.warn(`[ws-plugin] ${this.name} 关闭 WebSocket api 连接`); + } + }) + conn.on("message", async event => { + const data = JSON.parse(event) + const result = await this.getData(data.action, data.params, data.echo) + conn.send(JSON.stringify(result)); + }) + } else if (req.url === '/event' || req.url === '/event/') { + conn.id = req.headers["sec-websocket-key"] + let time = null + conn.send(lifecycle(this.uin)) + if (Config.heartbeatInterval > 0) { + time = setInterval(async () => { + conn.send(heartbeat(this.uin)) + }, Config.heartbeatInterval * 1000) + } + logger.mark(`[ws-plugin] ${this.name} 接受 WebSocket event 连接: ${req.connection.remoteAddress}`); + conn.on("error", (event) => { + logger.error(`[ws-plugin] ${this.name} 接受 WebSocket event 连接时出现错误: ${event}`) + }) + conn.on("close", () => { + if (this.stopReconnect = false) { + logger.warn(`[ws-plugin] ${this.name} 关闭 WebSocket event 连接`); + } + this.arr = this.arr.filter(i => i.id != req.headers["sec-websocket-key"]) + clearInterval(time) + }) + this.arr.push(conn) + } + }) + + }) + this.ws = { + send: (msg) => { + for (const i of this.arr) { + i.send(msg) + } + }, + close: () => { + this.server.close() + logger.warn(`[ws-plugin] CQ WebSocket 服务器已关闭: ${this.host}:${this.port}`) + for (const i of this.arr) { + i.close() + } + } + } + this.server.on('error', error => { + logger.error(`[ws-plugin] ${this.name} CQ WebSocket 服务器启动失败: ${this.host}:${this.port}`) + logger.error(error) + }) + this.wss = new WebSocketServer({ noServer: true }) + this.server.listen(this.port, this.host, () => { + this.status = 1 + logger.mark(`[ws-plugin] CQ WebSocket 服务器已启动: ${this.host}:${this.port}`) + }) + } + + createGSUidWs() { + try { + this.ws = new WebSocket(this.address) + } catch (error) { + logger.error(`[ws-plugin] 出错了,可能是ws地址填错了~\nws名字: ${this.name}\n地址: ${this.address}\n类型: 3`) + return + } + this.ws.on('open', async () => { + logger.mark(`[ws-plugin] ${this.name} 已连接`); + if (this.status == 3 && this.reconnectCount > 1 && Config.reconnectToMaster) { + await this.sendMasterMsg(`${this.name} 重连成功~`) + } else if (this.status == 0 && Config.firstconnectToMaster) { + await this.sendMasterMsg(`${this.name} 连接成功~`) + } + this.status = 1 + this.reconnectCount = 1 + }) + + this.ws.on('message', async event => { + const data = JSON.parse(event.toString()); + const { sendMsg, quote } = await makeGSUidSendMsg(data) + if (sendMsg.length > 0) { + let sendRet, group_id, user_id + // const bot = Version.isTrss ? Bot[data.bot_self_id] : Bot + const bot = Bot[data.bot_self_id] || Bot + switch (data.target_type) { + case 'group': + case 'channel': + group_id = data.target_id + sendRet = await bot.pickGroup(group_id).sendMsg(sendMsg, quote) + break; + case 'direct': + user_id = data.target_id + sendRet = await bot.pickFriend(user_id).sendMsg(sendMsg, quote) + break; + default: + break; + } + if (sendRet.rand) { + setMsgMap({ + message_id: sendRet.message_id, + time: sendRet.time, + seq: sendRet.seq, + rand: sendRet.rand, + user_id: user_id, + group_id: group_id, + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + }) + } + logger.mark(`[ws-plugin] 连接名字:${this.name} 处理完成`) + } + }) + + this.ws.on('close', async code => { + logger.warn(`[ws-plugin] ${this.name} 连接已关闭`); + if (Config.disconnectToMaster && this.reconnectCount == 1 && this.status == 1) { + await this.sendMasterMsg(`${this.name} 已断开连接...`) + } else if (Config.firstconnectToMaster && this.reconnectCount == 1 && this.status == 0) { + await this.sendMasterMsg(`${this.name} 连接失败...`) + } + this.status = 3 + if (!this.stopReconnect && ((this.reconnectCount < this.maxReconnectAttempts) || this.maxReconnectAttempts <= 0)) { + if (code === 1005) { + logger.warn(`[ws-plugin] ${this.name} 连接异常,停止重连`); + this.status = 0 + } else { + logger.warn(`[ws-plugin] ${this.name} 开始尝试重新连接第 ${this.reconnectCount} 次`); + this.reconnectCount++ + setTimeout(() => { + this.createGSUidWs() + }, this.reconnectInterval * 1000); + } + } else { + this.stopReconnect = false + this.status = 0 + logger.warn(`[ws-plugin] ${this.name} 达到最大重连次数或关闭连接,停止重连`); + } + }) + + this.ws.on('error', (event) => { + logger.error(`[ws-plugin] ${this.name} 连接失败\n${event}`); + }) + } + + createHttp() { + const parts = this.address.split(':'); + this.host = parts[0]; + this.port = parts[1]; + this.express = express(); + this.server = http.createServer(this.express); + this.express.use(express.json({ limit: '50mb' })); + this.express.use(express.urlencoded({ extended: true, limit: '50mb' })); + this.express.use((req, res, next) => this.authorization(req, res, next)) + + this.express.get('/:action', async (req, res) => { + const { action } = req.params; + const { query: params } = req; + const data = await this.getData(action, params) + res.status(200).json(data || {}) + }); + + this.express.post('/:action', async (req, res) => { + const { action } = req.params; + const { body: params } = req; + const data = await this.getData(action, params) + res.status(200).json(data || {}) + }); + + this.express.post('/', async (req, res) => { + const { action, params } = req.body; + const data = await this.getData(action, params) + res.status(200).json(data || {}) + }); + + this.server.on('error', error => { + logger.error(`[ws-plugin] ${this.name} 正向HTTP 服务器启动失败: ${this.host}:${this.port}`) + logger.error(error) + }) + this.server.listen(this.port, this.host, () => { + this.status = 1 + logger.mark(`[ws-plugin] HTTP 服务器已启动: ${this.host}:${this.port}`) + }) + this.ws = { + close: () => { + this.server.close() + logger.warn(`[ws-plugin] 正向HTTP 服务器已关闭: ${this.host}:${this.port}`) + } + } + } + + createHttpPost() { + if (!this.address.startsWith('http')) { + this.address = 'http://' + this.address + } + this.status = 1 + // 心跳咕一下 + this.ws = { + send: body => { + fetch(this.address, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-self-id': this.uin, + 'user-agent': `ws-plugin/${Version.version}` + }, + body + }) + } + } + } + + close() { + this.stopReconnect = true + if (this.status == 1) { + this.ws?.close?.() + this.status = 0 + } + } + + authorization(req, res, next) { + let code = null + const token = req.headers['authorization']?.replace?.(/^(Token|Bearer) /, '') || req.query.access_token + if (this.accessToken) { + if (!token) { + code = 401 + } else if (this.accessToken != token) { + code = 403 + } + } + if (code) { + res.status(code).end() + return + } + next() + } + + async getData(action, params, echo) { + let result + try { + const data = await getApiData(action, params, this.name, this.uin); + result = { + status: 'ok', + retcode: 0, + data, + echo + } + } catch (error) { + if (!error.noLog) logger.error('ws-plugin出现错误', error) + result = { + status: 'failed', + retcode: -1, + msg: error.message, + wording: 'ws-plugin获取信息失败', + echo + } + } finally { + return result + } + } + + async sendMasterMsg(msg) { + // const bot = Version.isTrss ? Bot[this.uin] : Bot + const bot = Bot[this.uin] || Bot + let masterQQ = [] + const master = Version.isTrss ? Config.master[this.uin] : Config.masterQQ + if (Config.howToMaster > 0) { + masterQQ.push(master?.[Config.howToMaster - 1]) + } else if (Config.howToMaster == 0) { + masterQQ.push(...master) + } + for (const i of masterQQ) { + if (!i) continue + let result + try { + result = await bot?.pickFriend?.(i)?.sendMsg?.(msg) || true + } catch (error) { + result = true + } + if (result) { + logger.mark(`[ws-plugin] 连接名字:${this.name} 通知主人:${i} 处理完成`) + } else { + const timer = setInterval(async () => { + try { + result = await bot?.pickFriend?.(i)?.sendMsg?.(msg) || true + } catch (error) { + result = true + } + if (result) { + clearInterval(timer) + logger.mark(`[ws-plugin] 连接名字:${this.name} 通知主人:${i} 处理完成`) + } + }, 5000) + } + } + } + +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/components/Config.js b/Yunzai/plugins/ws-plugin/components/Config.js new file mode 100644 index 0000000000000000000000000000000000000000..471b247378f214c409c20d2e636f42134e124e02 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/Config.js @@ -0,0 +1,375 @@ + +import YAML from 'yaml' +import chokidar from 'chokidar' +import fs from 'node:fs' +import YamlReader from './YamlReader.js' +import cfg from '../../../lib/config/config.js' +import _ from 'lodash' +import { modifyWebSocket } from './WebSocket.js' +import { cfgSchema } from '../config/system/cfg_system.js' + +const Path = process.cwd() +const Plugin_Name = 'ws-plugin' +const Plugin_Path = `${Path}/plugins/${Plugin_Name}` +class Config { + constructor() { + this.config = {} + this.oldConfig = {} + /** 监听文件 */ + this.watcher = { config: {}, defSet: {} } + + this.initCfg() + } + + /** 初始化配置 */ + initCfg() { + let path = `${Plugin_Path}/config/config/` + if (!fs.existsSync(path)) fs.mkdirSync(path) + let pathDef = `${Plugin_Path}/config/default_config/` + const files = fs.readdirSync(pathDef).filter(file => file.endsWith('.yaml')) + for (let file of files) { + if (!fs.existsSync(`${path}${file}`)) { + fs.copyFileSync(`${pathDef}${file}`, `${path}${file}`) + } + this.watch(`${path}${file}`, file.replace('.yaml', ''), 'config') + } + } + + /** 主人QQ */ + get masterQQ() { + return cfg.masterQQ + } + + /** Bot账号:[主人帐号] */ + get master() { + return cfg.master + } + + /** 云崽黑名单群 */ + get blackGroup() { + return cfg.getOther().blackGroup + } + + /** 云崽白名单群 */ + get whiteGroup() { + return cfg.getOther().whiteGroup + } + + /** 心跳 */ + get heartbeatInterval() { + return this.getDefOrConfig('ws-config').heartbeatInterval + } + + /** 数据上报类型 */ + get messagePostFormat() { + return this.getDefOrConfig('ws-config').messagePostFormat + } + + /** 连接列表 */ + get servers() { + return this.getDefOrConfig('ws-config').servers + } + + get noMsgStart() { + return this.getDefOrConfig('msg-config').noMsgStart + } + + get noMsgInclude() { + return this.getDefOrConfig('msg-config').noMsgInclude + } + + get howToMaster() { + return this.getDefOrConfig('msg-config').howToMaster + } + + /**掉线时否通知主人 */ + get disconnectToMaster() { + return this.getDefOrConfig('msg-config').disconnectToMaster + } + + /**重连成功时是否通知主人 */ + get reconnectToMaster() { + return this.getDefOrConfig('msg-config').reconnectToMaster + } + + /**首次连接成功时是否通知主人 */ + get firstconnectToMaster() { + return this.getDefOrConfig('msg-config').firstconnectToMaster + } + + /**消息存储时间 */ + get msgStoreTime() { + return this.getDefOrConfig('msg-config').msgStoreTime + } + + /**禁用群聊列表 */ + get noGroup() { + return this.getDefOrConfig('msg-config').noGroup + } + + /** 白名单群聊 */ + get yesGroup() { + return this.getDefOrConfig('msg-config').yesGroup + } + + /** 禁言拦截 */ + get muteStop() { + return this.getDefOrConfig('msg-config').muteStop + } + + /** red 发送伪造转发消息方式 */ + get redSendForwardMsgType(){ + return this.getDefOrConfig('msg-config').redSendForwardMsgType + } + + /**群管理员变动是否上报 */ + get groupAdmin() { + return this.getDefOrConfig('notice-config').groupAdmin + } + + /**群成员减少是否上报 */ + get groupDecrease() { + return this.getDefOrConfig('notice-config').groupDecrease + } + + /**群成员增加是否上报 */ + get groupIncrease() { + return this.getDefOrConfig('notice-config').groupIncrease + } + + /**群禁言是否上报 */ + get groupBan() { + return this.getDefOrConfig('notice-config').groupBan + } + + /**好友添加是否上报 */ + get friendIncrease() { + return this.getDefOrConfig('notice-config').friendIncrease + } + + /**群消息撤回是否上报 */ + get groupRecall() { + return this.getDefOrConfig('notice-config').groupRecall + } + + /**好友消息撤回是否上报 */ + get friendRecall() { + return this.getDefOrConfig('notice-config').friendRecall + } + + /**群内戳一戳是否上报 */ + get groupPoke() { + return this.getDefOrConfig('notice-config').groupPoke + } + + /** 好友申请是否上报 */ + get friendAdd() { + return this.getDefOrConfig('request-config').friendAdd + } + + /** 群聊邀请是否上报 (邀请机器人入群) */ + get groupInvite() { + return this.getDefOrConfig('request-config').groupInvite + } + + /** 群聊申请是否上报 (申请加入群聊) */ + get groupAdd() { + return this.getDefOrConfig('request-config').groupAdd + } + + /** 默认配置和用户配置 */ + getDefOrConfig(name) { + let def = this.getdefSet(name) + let config = this.getConfig(name) + return { ...def, ...config } + } + + /** 默认配置 */ + getdefSet(name) { + return this.getYaml('default_config', name) + } + + /** 用户配置 */ + getConfig(name) { + return this.getYaml('config', name) + } + + /** + * 获取配置yaml + * @param type 默认跑配置-defSet,用户配置-config + * @param name 名称 + */ + getYaml(type, name) { + let file = `${Plugin_Path}/config/${type}/${name}.yaml` + let key = `${type}.${name}` + + if (this.config[key]) return this.config[key] + + this.config[key] = YAML.parse( + fs.readFileSync(file, 'utf8') + ) + + this.watch(file, name, type) + + return this.config[key] + } + + /** 监听配置文件 */ + watch(file, name, type = 'default_config') { + let key = `${type}.${name}` + if (!this.oldConfig[key]) this.oldConfig[key] = _.cloneDeep(this.config[key]) + if (this.watcher[key]) return + + const watcher = chokidar.watch(file) + watcher.on('change', path => { + delete this.config[key] + if (typeof Bot == 'undefined') return + logger.mark(`[ws-plugin][修改配置文件][${type}][${name}]`) + + if (name == 'ws-config') { + const oldConfig = this.oldConfig[key] + delete this.oldConfig[key] + const newConfig = this.getYaml(type, name) + const object = this.findDifference(oldConfig, newConfig) + // console.log(object); + for (const key in object) { + if (Object.hasOwnProperty.call(object, key)) { + const value = object[key]; + const arr = key.split('.') + if (arr[0] !== 'servers') continue + let data = newConfig.servers[arr[1]] + if (typeof data === 'undefined') data = oldConfig.servers[arr[1]] + const target = { + type: null, + data + } + if (typeof value['newValue'] === 'object' && typeof value['oldValue'] === 'undefined') { + target.type = 'add' + } + else if (typeof value['newValue'] === 'undefined' && typeof value['oldValue'] === 'object') { + target.type = 'del' + } + else if (value['newValue'] === true && (value['oldValue'] === false || typeof value['oldValue'] === 'undefined')) { + target.type = 'close' + } + else if (value['newValue'] === false && (value['oldValue'] === true || typeof value['oldValue'] === 'undefined')) { + target.type = 'open' + } + modifyWebSocket(target) + } + } + + } + }) + + this.watcher[key] = watcher + } + + getCfgSchemaMap() { + let ret = {} + _.forEach(cfgSchema, (cfgGroup) => { + _.forEach(cfgGroup.cfg, (cfgItem, cfgKey) => { + ret[cfgItem.key] = cfgItem + cfgItem.cfgKey = cfgKey + }) + }) + return ret + } + + getCfgSchema() { + return cfgSchema + } + + getCfg() { + let wsconfig = this.getDefOrConfig('ws-config') + let msgconfig = this.getDefOrConfig('msg-config') + let noticeconfig = this.getDefOrConfig('notice-config') + let requestconfig = this.getDefOrConfig('request-config') + return { + ...wsconfig, + ...msgconfig, + ...noticeconfig, + ...requestconfig + } + } + + /** + * @description: 修改设置 + * @param {String} name 文件名 + * @param {String} key 修改的key值 + * @param {String|Number} value 修改的value值 + * @param {'config'|'default_config'} type 配置文件或默认 + */ + modify(name, key, value, type = 'config') { + let path = `${Plugin_Path}/config/${type}/${name}.yaml` + new YamlReader(path).set(key, value) + this.oldConfig[key] = _.cloneDeep(this.config[key]) + delete this.config[`${type}.${name}`] + } + + /** + * @description: 修改配置数组 + * @param {String} name 文件名 + * @param {String|Number} key key值 + * @param {String|Number} value value + * @param {'add'|'del'} category 类别 add or del + * @param {'config'|'default_config'} type 配置文件或默认 + */ + modifyarr(name, key, value, category = 'add', type = 'config') { + let path = `${Plugin_Path}/config/${type}/${name}.yaml` + let yaml = new YamlReader(path) + if (category == 'add') { + yaml.addIn(key, value) + } else { + let index = yaml.jsonData[key].indexOf(value) + yaml.delete(`${key}.${index}`) + } + } + + setArr(name, key, item, value, type = 'config') { + let path = `${Plugin_Path}/config/${type}/${name}.yaml` + let yaml = new YamlReader(path) + let arr = yaml.get(key).slice(); + arr[item] = value + yaml.set(key, arr) + } + + delServersArr(value, name = 'ws-config', type = 'config') { + let path = `${Plugin_Path}/config/${type}/${name}.yaml` + let yaml = new YamlReader(path) + let key = 'servers' + // let index = yaml.jsonData[key].indexOf(value) + let index = yaml.jsonData[key].findIndex(item => item.name === value); + yaml.delete(`${key}.${index}`) + } + + /** + * @description 对比两个对象不同的值 + * @param {*} oldObj + * @param {*} newObj + * @param {*} parentKey + * @returns + */ + findDifference(obj1, obj2, parentKey = '') { + const result = {}; + for (const key in obj1) { + const fullKey = parentKey ? `${parentKey}.${key}` : key; + if (_.isObject(obj1[key]) && _.isObject(obj2[key])) { + const diff = this.findDifference(obj1[key], obj2[key], fullKey); + if (!_.isEmpty(diff)) { + Object.assign(result, diff); + } + } else if (!_.isEqual(obj1[key], obj2[key])) { + result[fullKey] = { oldValue: obj1[key], newValue: obj2[key] }; + } + } + for (const key in obj2) { + if (!obj1.hasOwnProperty(key)) { + const fullKey = parentKey ? `${parentKey}.${key}` : key; + result[fullKey] = { oldValue: undefined, newValue: obj2[key] }; + } + } + return result; + } +} +export default new Config() \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/components/Render.js b/Yunzai/plugins/ws-plugin/components/Render.js new file mode 100644 index 0000000000000000000000000000000000000000..bfa7f9e151222d5f70463fddb03811137f1a7806 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/Render.js @@ -0,0 +1,51 @@ +import { Version } from '../components/index.js' + +function scale(pct = 1) { + let scale = 100 + scale = Math.min(2, Math.max(0.5, scale / 100)) + pct = pct * scale + return `style=transform:scale(${pct})` +} + +const Render = { + async render(path, params, cfg) { + let { e } = cfg + if (!e.runtime) { + console.log('未找到e.runtime,请升级至最新版Yunzai') + } + + let BotName = Version.isTrss ? 'Trss-Yunzai' : Version.isMiao ? 'Miao-Yunzai' : 'Yunzai-Bot' + return e.runtime.render('ws-plugin', path, params, { + retType: cfg.retMsgId ? 'msgId' : 'default', + beforeRender({ data }) { + let pluginName = '' + if (data.pluginName !== false) { + pluginName = ` & ${data.pluginName || 'ws-plugin'}` + if (data.pluginVersion !== false) { + pluginName += `${data.pluginVersion || Version.version}` + } + } + let resPath = data.pluResPath + const layoutPath = process.cwd() + '/plugins/ws-plugin/resources/common/layout/' + return { + ...data, + _res_path: resPath, + _ws_path: resPath, + _layout_path: layoutPath, + _tpl_path: process.cwd() + '/plugins/ws-plugin/resources/common/tpl/', + defaultLayout: layoutPath + 'default.html', + elemLayout: layoutPath + 'elem.html', + sys: { + scale: scale(cfg.scale || 1) + }, + copyright: `Created By ${BotName}${Version.yunzai}${pluginName}`, + pageGotoParams: { + waitUntil: 'networkidle2' + } + } + } + }) + } +} + +export default Render \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/components/Version.js b/Yunzai/plugins/ws-plugin/components/Version.js new file mode 100644 index 0000000000000000000000000000000000000000..9ccb7243d9052421a37943dbefa02f17fd430844 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/Version.js @@ -0,0 +1,96 @@ +import fs from 'fs' +import lodash from 'lodash' + +let packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8')) + +const getLine = function (line) { + line = line.replace(/(^\s*\*|\r)/g, '') + line = line.replace(/\s*`([^`]+`)/g, '$1') + line = line.replace(/`\s*/g, '') + line = line.replace(/\s*\*\*([^\*]+\*\*)/g, '$1') + line = line.replace(/\*\*\s*/g, '') + line = line.replace(/ⁿᵉʷ/g, '') + return line +} + +const readLogFile = function (root, versionCount = 4) { + let logPath = `${root}/CHANGELOG.md` + let logs = {} + let changelogs = [] + let currentVersion + + try { + if (fs.existsSync(logPath)) { + logs = fs.readFileSync(logPath, 'utf8') || '' + logs = logs.split('\n') + + let temp = {} + let lastLine = {} + lodash.forEach(logs, (line) => { + if (versionCount <= -1) { + return false + } + let versionRet = /^#\s*([0-9a-zA-Z\\.~\s]+?)\s*$/.exec(line) + if (versionRet && versionRet[1]) { + let v = versionRet[1].trim() + if (!currentVersion) { + currentVersion = v + } else { + changelogs.push(temp) + if (/0\s*$/.test(v) && versionCount > 0) { + versionCount = 0 + } else { + versionCount-- + } + } + + temp = { + version: v, + logs: [] + } + } else { + if (!line.trim()) { + return + } + if (/^\*/.test(line)) { + lastLine = { + title: getLine(line), + logs: [] + } + temp.logs.push(lastLine) + } else if (/^\s{2,}\*/.test(line)) { + lastLine.logs.push(getLine(line)) + } + } + }) + } + } catch (e) { + // do nth + } + return { changelogs, currentVersion } +} + +const { changelogs, currentVersion } = readLogFile(`${process.cwd()}/plugins/ws-plugin/`) + +const yunzaiVersion = packageJson.version +const isMiao = packageJson.dependencies.sequelize ? true : false +const isTrss = Array.isArray(Bot.uin) ? true : false +const protocol = ['chronocat', 'ICQQ'] + +let Version = { + isMiao, + isTrss, + protocol, + get version() { + return currentVersion + }, + get yunzai() { + return yunzaiVersion + }, + get changelogs() { + return changelogs + }, + readLogFile +} + +export default Version diff --git a/Yunzai/plugins/ws-plugin/components/WebSocket.js b/Yunzai/plugins/ws-plugin/components/WebSocket.js new file mode 100644 index 0000000000000000000000000000000000000000..73aed11bd67a22eb298eb3a481a1f87384a5a5e8 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/WebSocket.js @@ -0,0 +1,134 @@ +import Client from "./Client.js"; +import { Config, Version } from './index.js' +import { sleep } from '../model/index.js' +import { redAdapter } from '../model/red/index.js' +// import { satoriAdapter } from '../model/satori/index.js' + +let sendSocketList = [] +let allSocketList = [] + +async function createWebSocket(data) { + if (typeof data.close != 'undefined' && typeof data.closed == 'undefined') { + data.closed = data.close + delete data.close + } + const client = new Client(data) + setAllSocketList(client) + if (data.address == 'ws_address') return + if (data.closed) return + sendSocketList = sendSocketList.filter(i => i.name != data.name) + switch (Number(data.type)) { + case 1: + if (!await checkVersion(data)) return + client.createWs() + sendSocketList.push(client) + break; + case 2: + if (!await checkVersion(data)) return + client.createServer() + sendSocketList.push(client) + break + case 3: + client.createGSUidWs() + sendSocketList.push(client) + break + case 4: + if (Version.isTrss) return + // client.createQQNT() + redAdapter.connect(client) + break + case 5: + if (!await checkVersion(data)) return + client.createHttp() + break + case 6: + if (!await checkVersion(data)) return + client.createHttpPost() + sendSocketList.push(client) + break + default: + return; + } +} + +function setAllSocketList(data) { + allSocketList = allSocketList.filter(i => i.name != data.name) + allSocketList.push(data) +} + +async function checkVersion(data) { + if (Version.isTrss) { + if (!data.uin) { + logger.warn(`[ws-plugin] ${data.name} 缺少配置项uin 请删除连接后重新#ws添加连接`) + return false + } else { + let log = false + for (let i = 0; i < 20; i++) { + if (Version.protocol.some(i => i == Bot[data.uin]?.version?.name)) { + return true + } + if (!log) { + logger.warn(`[ws-plugin] ${data.name} 暂未适配当前协议端或未连接对应协议端,20秒后重新判断`) + log = true + } + await sleep(1000) + } + logger.warn(`[ws-plugin] ${data.name} 暂未适配当前协议端或未连接对应协议端 ${data.uin}`) + return false + } + } + return true +} + +function modifyWebSocket(target) { + // if (Version.isTrss) return + switch (target.type) { + case 'add': + case 'open': + if (target.data.type == 4) { + const client = new Client(target.data) + setAllSocketList(client) + redAdapter.connect(client) + } else { + createWebSocket(target.data) + } + break; + case 'del': + case 'close': + for (const i of allSocketList) { + if (i.name == target.data.name) { + i.close() + break + } + } + break + default: + return; + } +} + +function clearWebSocket() { + for (const i of allSocketList) { + i.close() + } +} + + +function initWebSocket() { + // if (Version.isTrss) return + for (const i of Config.servers) { + createWebSocket(i) + } +} + + +export { + initWebSocket, + clearWebSocket, + modifyWebSocket, + allSocketList, + setAllSocketList, + sendSocketList, + createWebSocket +} + diff --git a/Yunzai/plugins/ws-plugin/components/YamlReader.js b/Yunzai/plugins/ws-plugin/components/YamlReader.js new file mode 100644 index 0000000000000000000000000000000000000000..4d06887a6ac23a2e1936f0d90d3a69fc3ba4189a --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/YamlReader.js @@ -0,0 +1,83 @@ +import fs from 'fs' +import YAML from 'yaml' +import _ from 'lodash' +import chokidar from 'chokidar' + +export default class YamlReader { + /** + * 读写yaml文件 + * + * @param yamlPath yaml文件绝对路径 + * @param isWatch 是否监听文件变化 + */ + constructor(yamlPath, isWatch = false) { + this.yamlPath = yamlPath + this.isWatch = isWatch + this.initYaml() + } + + initYaml() { + // parseDocument 将会保留注释 + this.document = YAML.parseDocument(fs.readFileSync(this.yamlPath, 'utf8')) + if (this.isWatch && !this.watcher) { + this.watcher = chokidar.watch(this.yamlPath).on('change', () => { + if (this.isSave) { + this.isSave = false + return + } + this.initYaml() + }) + } + } + + /** 返回读取的对象 */ + get jsonData() { + if (!this.document) { + return null + } + return this.document.toJSON() + } + + /* 检查集合是否包含key的值 */ + has(keyPath) { + return this.document.hasIn(keyPath.split('.')) + } + + /* 返回key的值 */ + get(keyPath) { + return _.get(this.jsonData, keyPath) + } + + /* 修改某个key的值 */ + set(keyPath, value) { + this.document.setIn([keyPath], value) + this.save() + } + + /* 删除key */ + delete(keyPath) { + this.document.deleteIn(keyPath.split('.')) + this.save() + } + + // 数组添加数据 + addIn(keyPath, value) { + this.document.addIn(keyPath.split('.'), value) + this.save() + } + + // 彻底删除某个key + deleteKey(keyPath) { + let keys = keyPath.split('.') + keys = this.mapParentKeys(keys) + this.document.deleteIn(keys) + this.save() + } + + // 保存yaml文件,写入文件 + save() { + this.isSave = true + let yaml = this.document.toString() + fs.writeFileSync(this.yamlPath, yaml, 'utf8') + } +} diff --git a/Yunzai/plugins/ws-plugin/components/index.js b/Yunzai/plugins/ws-plugin/components/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fd29eaaae037ef72618d17ae54f2781cdc1aaf5e --- /dev/null +++ b/Yunzai/plugins/ws-plugin/components/index.js @@ -0,0 +1,20 @@ +import Version from './Version.js' +import YamlReader from './YamlReader.js' +import Config from './Config.js' +import { initWebSocket, createWebSocket, allSocketList, setAllSocketList, sendSocketList, clearWebSocket, modifyWebSocket } from './WebSocket.js' +import Render from './Render.js' +const Path = process.cwd() +export { + Version, + Path, + YamlReader, + Config, + initWebSocket, + clearWebSocket, + createWebSocket, + modifyWebSocket, + allSocketList, + setAllSocketList, + sendSocketList, + Render +} diff --git a/Yunzai/plugins/ws-plugin/config/config/msg-config.yaml b/Yunzai/plugins/ws-plugin/config/config/msg-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..017693a7408128dd5223a2fcdd49adb4cbbc1195 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/config/msg-config.yaml @@ -0,0 +1,36 @@ +#以数组内开头的消息不上传 +noMsgStart: + - "示例1" + +#包含了数组内的消息不上传 +noMsgInclude: + - 示例1 + +# 通知哪个主人 +howToMaster: 1 + +#断开连接时否通知主人 +disconnectToMaster: false + +#重新连接成功时是否通知主人 +reconnectToMaster: false + +#首次连接时是否通知主人成功还是失败 +firstconnectToMaster: false + +#消息存储时间,用于撤回和回复消息,单位秒 +msgStoreTime: 600 + +#黑名单群 +noGroup: + - 123456 + +#白名单群 +yesGroup: + - "755269874" + - "962589204" + - "551081559" + - "733413020" + +#被禁言或者全体禁言时候拦截消息不再上报 +muteStop: false diff --git a/Yunzai/plugins/ws-plugin/config/config/notice-config.yaml b/Yunzai/plugins/ws-plugin/config/config/notice-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ecb863919dfd6d38e7a8abfffc34e7949f1f5d79 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/config/notice-config.yaml @@ -0,0 +1,23 @@ +# 群管理员变动是否上报 +groupAdmin: false + +# 群成员减少是否上报 +groupDecrease: false + +# 群成员增加是否上报 +groupIncrease: false + +# 群禁言是否上报 +groupBan: false + +# 好友添加是否上报 +friendIncrease: false + +# 群消息撤回是否上报 +groupRecall: false + +# 好友消息撤回是否上报 +friendRecall: false + +# 群内戳一戳是否上报 +groupPoke: false \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/config/request-config.yaml b/Yunzai/plugins/ws-plugin/config/config/request-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae07b52c68bf49f444188e68bc5d2cd29c0f8aad --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/config/request-config.yaml @@ -0,0 +1,8 @@ +# 好友申请是否上报 +friendAdd: false + +# 群聊邀请是否上报 (邀请机器人入群) +groupInvite: false + +# 群聊申请是否上报 (申请加入群聊) +groupAdd: false \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/config/ws-config.yaml b/Yunzai/plugins/ws-plugin/config/config/ws-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a21d0954604afedb17a5223c6067fc2890d62f6e --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/config/ws-config.yaml @@ -0,0 +1,21 @@ +# 心跳频率, 单位秒 +# 0 为关闭心跳 +heartbeatInterval: 5 + +# 上报数据类型 +# 可选: 1:string, 2:array +messagePostFormat: 2 + +# 连接服务列表 +servers: + # 添加连接方式, 可添加多个 + # 连接名字 请保证每个名字都不相同,否则会出问题 + - name: ws_name + # 连接地址 + address: ws_address + # 连接类型 1:反向 Websocket 2:正向 Websocket 3:gsuid_core + type: 1 + # 重连间隔 单位:秒 + reconnectInterval: 5 + # 最大连接次数 0 为无限制 + maxReconnectAttempts: 0 \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/default_config/msg-config.yaml b/Yunzai/plugins/ws-plugin/config/default_config/msg-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0a77b51c09446040bd5b4b284254672a51f1e2ed --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/default_config/msg-config.yaml @@ -0,0 +1,35 @@ +#以数组内开头的消息不上传 +noMsgStart: + - "示例1" + +#包含了数组内的消息不上传 +noMsgInclude: + - 示例1 + +# 通知哪个主人 +howToMaster: 1 + +#断开连接时否通知主人 +disconnectToMaster: false + +#重新连接成功时是否通知主人 +reconnectToMaster: false + +#首次连接时是否通知主人成功还是失败 +firstconnectToMaster: false + +#消息存储时间,用于撤回和回复消息,单位秒 +msgStoreTime: 600 + +#黑名单群 +noGroup: + - 123456 + +#白名单群 +yesGroup: [] + +#被禁言或者全体禁言时候拦截消息不再上报 +muteStop: false + +#red 发送伪造转发消息方式 1:伪造转发 2:直接发送 +redSendForwardMsgType: 1 \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/default_config/notice-config.yaml b/Yunzai/plugins/ws-plugin/config/default_config/notice-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ecb863919dfd6d38e7a8abfffc34e7949f1f5d79 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/default_config/notice-config.yaml @@ -0,0 +1,23 @@ +# 群管理员变动是否上报 +groupAdmin: false + +# 群成员减少是否上报 +groupDecrease: false + +# 群成员增加是否上报 +groupIncrease: false + +# 群禁言是否上报 +groupBan: false + +# 好友添加是否上报 +friendIncrease: false + +# 群消息撤回是否上报 +groupRecall: false + +# 好友消息撤回是否上报 +friendRecall: false + +# 群内戳一戳是否上报 +groupPoke: false \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/default_config/request-config.yaml b/Yunzai/plugins/ws-plugin/config/default_config/request-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ae07b52c68bf49f444188e68bc5d2cd29c0f8aad --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/default_config/request-config.yaml @@ -0,0 +1,8 @@ +# 好友申请是否上报 +friendAdd: false + +# 群聊邀请是否上报 (邀请机器人入群) +groupInvite: false + +# 群聊申请是否上报 (申请加入群聊) +groupAdd: false \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/default_config/ws-config.yaml b/Yunzai/plugins/ws-plugin/config/default_config/ws-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a21d0954604afedb17a5223c6067fc2890d62f6e --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/default_config/ws-config.yaml @@ -0,0 +1,21 @@ +# 心跳频率, 单位秒 +# 0 为关闭心跳 +heartbeatInterval: 5 + +# 上报数据类型 +# 可选: 1:string, 2:array +messagePostFormat: 2 + +# 连接服务列表 +servers: + # 添加连接方式, 可添加多个 + # 连接名字 请保证每个名字都不相同,否则会出问题 + - name: ws_name + # 连接地址 + address: ws_address + # 连接类型 1:反向 Websocket 2:正向 Websocket 3:gsuid_core + type: 1 + # 重连间隔 单位:秒 + reconnectInterval: 5 + # 最大连接次数 0 为无限制 + maxReconnectAttempts: 0 \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/config/system/cfg_system.js b/Yunzai/plugins/ws-plugin/config/system/cfg_system.js new file mode 100644 index 0000000000000000000000000000000000000000..663c0a4afcbc980e879cb90542551c6456202f57 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/system/cfg_system.js @@ -0,0 +1,201 @@ +export const cfgSchema = { + ws: { + title: 'ws连接设置,改动此设置会将所有已连接强制断开重连', + cfg: { + heartbeatInterval: { + title: '心跳频率', + key: '心跳', + type: 'num', + def: 5, + input: (n) => { + if (n >= 0) { + return n * 1 + } else { + return 5 + } + }, + desc: '单位:秒,0为关闭心跳', + fileName: 'ws-config' + }, + messagePostFormat: { + title: '上报数据类型', + key: '上报', + type: 'num', + def: 2, + input: (n) => Math.min(2, Math.max(n * 1 || 0, 1)), + desc: '上报数据类型: 1:string 2:array', + fileName: 'ws-config' + } + } + }, + msg: { + title: '发送消息相关设置', + cfg: { + disconnectToMaster: { + title: '断连通知', + key: '断连通知', + def: false, + desc: '断开连接时是否通知主人', + fileName: 'msg-config' + }, + reconnectToMaster: { + title: '重连通知', + key: '重连通知', + def: false, + desc: '重新连接成功时是否通知主人', + fileName: 'msg-config' + }, + firstconnectToMaster: { + title: '首连通知', + key: '首连通知', + def: false, + desc: '首次连接时是否通知主人成功还是失败', + fileName: 'msg-config' + }, + howToMaster: { + title: '通知哪个主人', + key: '主人', + type: 'num', + input: (n) => { + if (n >= 0) { + return n * 1 + } else { + return 1 + } + }, + def: 1, + desc: `通知主人列表的第几个主人,为0时通知全部主人`, + fileName: 'msg-config' + }, + muteStop: { + title: '禁言拦截', + key: '禁言拦截', + def: false, + desc: '被禁言或者全体禁言时是否拦截消息不上报', + fileName: 'msg-config' + }, + redSendForwardMsgType: { + title: 'red转发方式', + key: 'red转发', + type: 'num', + def: 1, + desc: 'red 发送伪造转发消息方式 1:伪造转发 2:陆续发送 3:合并发送', + input: (n) => Math.min(3, Math.max(n * 1 || 0, 1)), + fileName: 'msg-config' + }, + msgStoreTime: { + title: '消息存储时间', + key: '存储', + type: 'num', + input: (n) => { + if (n >= 0) { + return n * 1 + } else { + return 600 + } + }, + def: 600, + desc: '用于撤回和回复消息,如果超过时间去获取就会获取不到,单位秒,0不存储', + fileName: 'msg-config' + } + } + }, + notice: { + title: '通知相关设置', + cfg: { + groupAdmin: { + title: '管理员变动', + key: '管理', + def: false, + desc: '群管理员变动是否上报', + fileName: 'notice-config' + }, + groupDecrease: { + title: '群成员减少', + key: '群员减少', + def: false, + desc: '群成员减少是否上报', + fileName: 'notice-config' + }, + groupIncrease: { + title: '群成员增加', + key: '群员增加', + def: false, + desc: '群成员增加是否上报', + fileName: 'notice-config' + }, + groupBan: { + title: '群禁言', + key: '禁言', + def: false, + desc: '群禁言是否上报', + fileName: 'notice-config' + }, + friendIncrease: { + title: '好友添加', + key: '好友添加', + def: false, + desc: '好友添加是否上报', + fileName: 'notice-config' + }, + groupRecall: { + title: '群消息撤回', + key: '群撤回', + def: false, + desc: '群消息撤回是否上报', + fileName: 'notice-config' + }, + friendRecall: { + title: '好友消息撤回', + key: '好友撤回', + def: false, + desc: '好友消息撤回是否上报', + fileName: 'notice-config' + }, + groupPoke: { + title: '群内戳一戳', + key: '戳一戳', + def: false, + desc: '群内戳一戳是否上报', + fileName: 'notice-config' + }, + } + }, + request: { + title: '请求相关设置', + cfg: { + friendAdd: { + title: '好友申请', + key: '好友申请', + def: false, + desc: '好友申请是否上报', + fileName: 'request-config' + }, + groupInvite: { + title: '群聊邀请', + key: '群邀请', + def: false, + desc: '群聊邀请是否上报 (邀请机器人入群)', + fileName: 'request-config' + }, + groupAdd: { + title: '群聊申请', + key: '群申请', + def: false, + desc: '群聊申请是否上报 (申请加入群聊)', + fileName: 'request-config' + }, + } + }, + setAll: { + title: '一键操作', + cfg: { + setAll: { + title: '全部设置', + key: '全部', + def: false, + desc: '一键 开启/关闭 全部设置项' + } + } + } +} diff --git a/Yunzai/plugins/ws-plugin/config/system/help_system.js b/Yunzai/plugins/ws-plugin/config/system/help_system.js new file mode 100644 index 0000000000000000000000000000000000000000..b927bf3fcdb819caac33ef290d774e68a51b250b --- /dev/null +++ b/Yunzai/plugins/ws-plugin/config/system/help_system.js @@ -0,0 +1,84 @@ +export const helpCfg = { + "themeSet": false, + "title": "ws帮助", + "subTitle": "Yunzai-Bot & ws-plugin", + "colWidth": 265, + "theme": "all", + "themeExclude": [ + "default" + ], + "colCount": 3, + "bgBlur": true +} +export const helpList = [ + { + "group": "连接管理", + "list": [ + { + "icon": 80, + "title": "#ws添加连接", + "desc": "添加一个新的连接" + }, + { + "icon": 63, + "title": "#ws删除连接", + "desc": "删除一个已有的连接 " + }, + { + "icon": 66, + "title": "#ws关闭连接", + "desc": "不会删除已有连接,同时不进行连接" + }, + { + "icon": 65, + "title": "#ws打开连接", + "desc": "打开已关闭的连接" + }, + { + "icon": 79, + "title": "#ws查看连接", + "desc": "查看已有的所有连接名字和状态" + }, + { + "icon": 64, + "title": "#ws重新连接", + "desc": "断开连接并重新连接" + } + ] + }, + { + "group": "其他设置", + "list": [ + { + "icon": 81, + "title": "#ws(增加/删除)(禁用/启用)群123456", + "desc": "精确处理黑名单白名单,不带群号为当前群" + }, + { + "icon": 84, + "title": "#ws(禁用/启用)群123456", + "desc": "模糊匹配,比如禁用群则优先看白名单,如果有就删除,否则添加到黑名单" + }, + { + "icon": 85, + "title": "#ws查看(禁用/启用)群", + "desc": "查看当前(禁用/启用)的群聊列表" + }, + ] + }, + { + "group": "其他说明", + "list": [ + { + "icon": 71, + "title": "#ws连接说明", + "desc": "查看添加连接时的说明" + }, + { + "icon": 94, + "title": "#ws设置", + "desc": "插件设置" + } + ] + } +] \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/guoba.support.js b/Yunzai/plugins/ws-plugin/guoba.support.js new file mode 100644 index 0000000000000000000000000000000000000000..50067c93593466fac7199f3749c8d2129159843e --- /dev/null +++ b/Yunzai/plugins/ws-plugin/guoba.support.js @@ -0,0 +1,233 @@ +import lodash from 'lodash' +import { Config } from './components/index.js' + +// 支持锅巴 +export function supportGuoba() { + let groupList = Array.from(Bot.gl.values()) + groupList = groupList.map(item => item = { label: `${item.group_name}-${item.group_id}`, value: item.group_id }) + return { + // 插件信息,将会显示在前端页面 + // 如果你的插件没有在插件库里,那么需要填上补充信息 + // 如果存在的话,那么填不填就无所谓了,填了就以你的信息为准 + pluginInfo: { + name: 'ws-plugin', + title: 'ws-plugin', + author: '@小叶', + authorLink: 'https://gitee.com/xiaoye12123', + link: 'https://gitee.com/xiaoye12123/ws-plugin', + isV3: true, + isV2: false, + description: 'Yunzai-Bot 的扩展插件 ws-plugin 提供ontbot协议适配,通过ws连接onebot实现的bot', + // 显示图标,此为个性化配置 + // 图标可在 https://icon-sets.iconify.design 这里进行搜索 + icon: 'bx:atom', + // 图标颜色,例:#FF0000 或 rgb(255, 0, 0) + iconColor: 'rgb(241,212,152)', + // 如果想要显示成图片,也可以填写图标路径(绝对路径) + // iconPath: path.join(_paths.pluginRoot, 'resources/images/icon.png'), + }, + // 配置项信息 + configInfo: { + // 配置项 schemas + schemas: [ + { + component: 'Divider', + label: '通知设置' + }, + { + field: 'msg.noMsgStart', + label: '上报设置1', + bottomHelpMessage: '以数组内开头的消息不上报', + component: 'GTags', + componentProps: { + allowAdd: true, + allowDel: true, + }, + }, + { + field: 'msg.noMsgInclude', + label: '上报设置2', + bottomHelpMessage: '包含了数组内的消息不上报', + component: 'GTags', + componentProps: { + allowAdd: true, + allowDel: true, + }, + }, + { + field: 'msg.noGroup', + label: '黑名单群聊', + bottomHelpMessage: '数组内的群消息不上报', + component: 'Select', + componentProps: { + allowAdd: true, + allowDel: true, + mode: 'multiple', + options: groupList + } + }, + { + field: 'msg.yesGroup', + label: '白名单群聊', + bottomHelpMessage: '只上报数组内的群消息', + component: 'Select', + componentProps: { + allowAdd: true, + allowDel: true, + mode: 'multiple', + options: groupList + } + }, + { + field: 'msg.disconnectToMaster', + label: '断开连接', + bottomHelpMessage: '断开连接时否通知主人', + component: 'Switch', + }, + { + field: 'msg.reconnectToMaster', + label: '重新连接', + bottomHelpMessage: '重新连接成功时是否通知主人', + component: 'Switch', + }, + { + field: 'msg.firstconnectToMaster', + label: '首次连接', + bottomHelpMessage: '首次连接时是否通知主人成功还是失败', + component: 'Switch', + }, + { + field: 'msg.msgStoreTime', + label: '消息存储时间', + bottomHelpMessage: '消息存储时间,用于撤回和回复消息,单位秒', + component: 'InputNumber', + required: true, + componentProps: { + min: 0, + placeholder: '请输入时间', + }, + }, + { + component: 'Divider', + label: '上报设置' + }, + { + field: 'notice.groupAdmin', + label: '管理变动', + bottomHelpMessage: '群管理员变动是否上报', + component: 'Switch', + }, + { + field: 'notice.groupDecrease', + label: '群员减少', + bottomHelpMessage: '群成员减少是否上报', + component: 'Switch', + }, + { + field: 'notice.groupIncrease', + label: '群员增加', + bottomHelpMessage: '群成员增加是否上报', + component: 'Switch', + }, + { + field: 'notice.groupBan', + label: '群内禁言', + bottomHelpMessage: '群禁言是否上报', + component: 'Switch', + }, + { + field: 'notice.friendIncrease', + label: '好友添加', + bottomHelpMessage: '好友添加是否上报(添加成功之后)', + component: 'Switch', + }, + { + field: 'notice.groupRecall', + label: '群内撤回', + bottomHelpMessage: '群消息撤回是否上报', + component: 'Switch', + }, + { + field: 'notice.friendRecall', + label: '好友撤回', + bottomHelpMessage: '好友消息撤回是否上报', + component: 'Switch', + }, + { + field: 'notice.groupPoke', + label: '群戳一戳', + bottomHelpMessage: '群内戳一戳是否上报', + component: 'Switch', + }, + { + component: 'Divider', + label: '请求设置' + }, + { + field: 'request.friendAdd', + label: '好友申请', + bottomHelpMessage: '好友申请是否上报', + component: 'Switch', + }, + { + field: 'request.groupInvite', + label: '群聊邀请', + bottomHelpMessage: '群聊邀请是否上报 (邀请机器人入群)', + component: 'Switch', + }, + { + field: 'request.groupAdd', + label: '群聊申请', + bottomHelpMessage: '群聊申请是否上报 (申请加入群聊)', + component: 'Switch', + }, + { + component: 'Divider', + label: '连接设置' + }, + { + field: 'ws.heartbeatInterval', + label: '心跳频率', + bottomHelpMessage: '心跳频率, 单位秒', + component: 'InputNumber', + required: true, + componentProps: { + min: 0, + placeholder: '请输入心跳频率时间', + }, + }, + { + field: 'ws.messagePostFormat', + label: '上报类型', + bottomHelpMessage: '可选: 1:string, 2:array', + component: 'RadioGroup', + componentProps: { + options: [ + { label: 'string', value: 1 }, + { label: 'array', value: 2 }, + ], + }, + }, + ], + // 获取配置数据方法(用于前端填充显示数据) + getConfigData() { + return { + ws: Config.getDefOrConfig('ws-config'), + msg: Config.getDefOrConfig('msg-config'), + notice: Config.getDefOrConfig('notice-config'), + request: Config.getDefOrConfig('request-config') + } + }, + // 设置配置的方法(前端点确定后调用的方法) + setConfigData(data, { Result }) { + let config = Config.getCfg() + for (const key in data) { + let split = key.split('.') + if (lodash.isEqual(config[split[1]], data[key])) continue + Config.modify(split[0] + '-config', split[1], data[key]) + } + return Result.ok({}, '保存成功~') + }, + }, + } +} diff --git a/Yunzai/plugins/ws-plugin/index.js b/Yunzai/plugins/ws-plugin/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0218fd0a8e10c1eb49303ed7b5c731c00b4d34ce --- /dev/null +++ b/Yunzai/plugins/ws-plugin/index.js @@ -0,0 +1,103 @@ +import fs from 'node:fs' +import { initWebSocket, Config, Version } from './components/index.js' +import { TMP_DIR, mimeTypes } from './model/index.js' +import { join, extname } from 'path' +const files = fs.readdirSync('./plugins/ws-plugin/apps').filter(file => file.endsWith('.js')) + +let ret = [] + +logger.info('-----------------') +logger.info(`ws-plugin${Version.version}插件初始化~`) + + +files.forEach((file) => { + ret.push(import(`./apps/${file}`)) +}) + +ret = await Promise.allSettled(ret) + +let apps = {} +for (let i in files) { + let name = files[i].replace('.js', '') + + if (ret[i].status != 'fulfilled') { + logger.error(`载入插件错误:${logger.red(name)}`) + logger.error(ret[i].reason) + continue + } + apps[name] = ret[i].value[Object.keys(ret[i].value)[0]] +} +let path = ['./apps/message/message.js', './apps/notice/notice.js', './apps/request/request.js'] +for (const item of path) { + try { + await import(`${item}`) + } catch (e) { + logger.error(`载入事件错误:${item}`) + logger.error(e) + } +} + +initWebSocket() +if (Version.isTrss) { + Bot.express.get('/ws-plugin*', async (req, res) => { + const file = req.query.file + if (file) { + const ext = extname(file) + const contentType = mimeTypes[ext] + fs.readFile(join(TMP_DIR, file), (err, content) => { + if (err) { + res.writeHead(404) + res.end('File not found') + } else { + const name = file.split('-') + const filename = encodeURIComponent(name[1]) || encodeURIComponent(name[0]) || encodeURIComponent(file) + res.writeHead(200, { + 'Content-Type': contentType, + 'Content-Disposition': `attachment; filename=${filename}` + }) + res.end(content) + } + }) + return + } + res.writeHead(404); + res.end('Page not found') + }) +} else { + const getGroupMemberInfo = Bot.getGroupMemberInfo + /** 劫持修改getGroupMemberInfo方法 */ + Bot.getGroupMemberInfo = async function (group_id, user_id) { + let result + try { + result = await getGroupMemberInfo(group_id, user_id) + } catch (error) { + let nickname + if (error.stack.includes('ws-plugin')) { + nickname = 'chronocat' + } else { + nickname = String(group_id).includes("qg_") ? "QQGuild-Bot" : "WeChat-Bot" + } + result = { + group_id, + user_id, + nickname, + card: "", + sex: "female", + age: 6, + join_time: "", + last_sent_time: "", + level: 1, + role: "member", + title: "", + title_expire_time: "", + shutup_time: 0, + update_time: "", + area: "南极洲", + rank: "潜水", + } + } + return result + } +} + +export { apps } diff --git a/Yunzai/plugins/ws-plugin/model/CQCode.js b/Yunzai/plugins/ws-plugin/model/CQCode.js new file mode 100644 index 0000000000000000000000000000000000000000..3e60e7b5fef08b1c605af412f6ca67d1c82e102f --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/CQCode.js @@ -0,0 +1,65 @@ + +/** + * cq码转换Msg + * @param {*} cq + */ +function CQToMsg(cq) { + let msg = []; + let matches = cq.matchAll(/(\[CQ:(.*?),(.*?)\]|.)/gs); + let text = ''; + for (const match of matches) { + if (match[2]) { + if (text) { + msg.push({ + type: 'text', + data: { + text + } + }); + text = ''; + } + let type = match[2]; + let data = {}; + let pairs = match[3].split(','); + for (const pair of pairs) { + let [key, value] = pair.split('='); + data[key] = value; + } + msg.push({ type, data }); + } else { + text += match[0]; + } + } + if (text) { + msg.push({ + type: 'text', + data: { + text + } + }); + } + return msg; +} + +/** + * msg转换cq码 + * @param {*} msg + * @returns + */ +function MsgToCQ(msg) { + let cq = ''; + for (const item of msg) { + if (item.type === 'text') { + cq += item.data.text; + } else { + let data = Object.entries(item.data).map(([key, value]) => `${key}=${value}`).join(','); + cq += `[CQ:${item.type},${data}]`; + } + } + return cq; +} + +export { + CQToMsg, + MsgToCQ +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/api.js b/Yunzai/plugins/ws-plugin/model/api.js new file mode 100644 index 0000000000000000000000000000000000000000..8fb872308fe2be32534ebf3af5fb44f5eb1248cf --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/api.js @@ -0,0 +1,855 @@ +import { makeSendMsg, makeForwardMsg, msgToOneBotMsg } from './makeMsg.js' +import { getMsgMap, setMsgMap, getGuildLatestMsgId, getLatestMsg } from './msgMap.js' +import { MsgToCQ, CQToMsg } from './CQCode.js' +import { Version } from '../components/index.js' +import fetch from 'node-fetch' + +async function getApiData(api, params = {}, name, uin) { + const bot = Bot[uin] || Bot + let sendRet = null + let ResponseData = null + let publicApi = { + // -------------------------------------------------------- + // Bot 账号 + // 有关 Bot 账号的相关 API + // -------------------------------------------------------- + + // 获取登录号信息 + 'get_login_info': async params => { + ResponseData = { + user_id: bot.uin, + nickname: bot.nickname + } + }, + // 设置登录号资料 + 'set_qq_profile': async params => { + // company公司 email邮箱 college学校 在icqq文档中没找到 + if (params.nickname) { + await bot.setNickname?.(params.nickname) + } + if (params.personal_note) { + await bot.setDescription?.(params.personal_note) + } + }, + // 获取企点账号信息 + // TODO qidian_get_account_info + // 获取在线机型 + // TODO _get_model_show + // 设置在线机型 + '_set_model_show': async params => { + // TODO 不会改 + }, + // 获取当前账号在线客户端列表 + 'get_online_clients': async params => { + // TODO 不会获取 + ResponseData = { + clients: [] + } + }, + + // -------------------------------------------------------- + // 好友信息 + // -------------------------------------------------------- + + // 获取陌生人信息 + 'get_stranger_info': async (params) => { + ResponseData = await bot.getStrangerInfo?.(params.user_id) + }, + // 获取好友列表 + 'get_friend_list': async params => { + let list = await bot.getFriendList?.() + if (Array.isArray(list)) { + ResponseData = list + } else if (list instanceof Map) { + ResponseData = Array.from(list.values()) + } + }, + // 获取单向好友列表 + 'get_unidirectional_friend_list': async params => { + // 感觉不像这个 + // ResponseData = Array.from(bot.sl.values()) + ResponseData = [] + }, + + // -------------------------------------------------------- + // 好友操作 + // 好友操作 API + // -------------------------------------------------------- + + // 删除好友 + 'delete_friend': async params => { + await bot.deleteFriend?.(params.user_id) + }, + // 删除单向好友 + // TODO delete_unidirectional_friend + + // -------------------------------------------------------- + // 消息 + // 有关消息操作的 API + // -------------------------------------------------------- + + // 发送私聊消息 + 'send_private_msg': async (params) => { + let { sendMsg, quote } = await makeSendMsg(params, uin) + if (sendMsg.length > 0) sendRet = await bot.pickFriend?.(params.user_id).sendMsg?.(sendMsg, quote) + logger.mark(`[ws-plugin] 连接名字:${name} 处理完成`) + }, + // 发送群聊消息 + 'send_group_msg': async (params) => { + let { sendMsg, quote } = await makeSendMsg(params, uin) + if (sendMsg.length > 0) sendRet = await bot.pickGroup?.(params.group_id).sendMsg?.(sendMsg, quote) + logger.mark(`[ws-plugin] 连接名字:${name} 处理完成`) + }, + // 发送消息 + 'send_msg': async (params) => { + let { sendMsg, quote } = await makeSendMsg(params, uin) + if (params.message_type == 'group' || params.group_id) { + if (sendMsg.length > 0) sendRet = await bot.pickGroup?.(params.group_id).sendMsg?.(sendMsg, quote) + } else if (params.message_type == 'private' || params.user_id) { + if (sendMsg.length > 0) sendRet = await bot.pickFriend?.(params.user_id).sendMsg?.(sendMsg, quote) + } + logger.mark(`[ws-plugin] 连接名字:${name} 处理完成`) + }, + // 获取消息 + 'get_msg': async (params) => { + ResponseData = await getMsgMap({ onebot_id: params.message_id }) + if (ResponseData) { + ResponseData = await bot.getMsg?.(ResponseData.message_id) + if (ResponseData) { + if (ResponseData.bot) delete ResponseData.bot + if (ResponseData.friend) delete ResponseData.friend + if (ResponseData.group) delete ResponseData.group + if (ResponseData.member) delete ResponseData.member + ResponseData.group = ResponseData.message_type == 'group' ? true : false + ResponseData.real_id = Number(ResponseData.seq) + ResponseData.message_id = Number(ResponseData.rand) + ResponseData.message = await msgToOneBotMsg(ResponseData.message) + ResponseData.raw_message = MsgToCQ(ResponseData.message) + } else { + throw { message: 'get_msg API error', noLog: true } + } + } else { + throw { message: 'get_msg API error', noLog: true } + } + }, + // 撤回消息 + 'delete_msg': async (params) => { + let msg = await getMsgMap({ onebot_id: params.message_id }) + if (msg) { + await bot.deleteMsg?.(msg.message_id) + } + }, + // 标记消息已读 + 'mark_msg_as_read': async params => { + // TODO + }, + // 获取合并转发内容 + 'get_forward_msg': async params => { + let result = await bot.getForwardMsg?.(params.message_id) || [] + let messages = [] + for (const item of result) { + messages.push({ + content: MsgToCQ(await msgToOneBotMsg(item.message)), + sender: { + nickname: item.nickname, + user_id: item.user_id + }, + time: item.time + }) + } + ResponseData = { + messages + } + }, + // 发送合并转发 ( 群聊 ) + 'send_group_forward_msg': async (params) => { + let forwardMsg = await makeForwardMsg(params, uin) + let forward_id + if (typeof (forwardMsg.data) === 'object') { + let detail = forwardMsg.data?.meta?.detail + if (detail) forward_id = detail.resid + } else { + let match = forwardMsg.data.match(/m_resid="(.*?)"/); + if (match) forward_id = match[1]; + } + sendRet = await bot.pickGroup(params.group_id).sendMsg(forwardMsg) + sendRet.forward_id = forward_id + logger.mark(`[ws-plugin] 连接名字:${name} 处理完成`) + }, + // 发送合并转发 ( 好友 ) + 'send_private_forward_msg': async (params) => { + let forwardMsg = await makeForwardMsg(params, uin) + let forward_id + if (typeof (forwardMsg.data) === 'object') { + let detail = forwardMsg.data?.meta?.detail + if (detail) forward_id = detail.resid + } else { + let match = forwardMsg.data.match(/m_resid="(.*?)"/); + if (match) forward_id = match[1]; + } + sendRet = await bot.pickFriend(params.group_id).sendMsg(forwardMsg) + sendRet.forward_id = forward_id + logger.mark(`[ws-plugin] 连接名字:${name} 处理完成`) + }, + // 获取群消息历史记录 + 'get_group_msg_history': async params => { + let messages, flag = true + if (params.message_seq) { + let message_id = (await getMsgMap({ onebot_id: params.message_id }))?.message_id + if (message_id) { + messages = await bot.getChatHistory?.(message_id) + flag = false + } + } + if (flag) { + messages = await bot.pickGroup(params.group_id).getChatHistory?.() + } + if (messages) { + for (let i = 0; i < messages.length; i++) { + messages[i] = await msgToOneBotMsg(messages[i]) + } + } + ResponseData = { + messages + } + }, + + // -------------------------------------------------------- + // 图片 + // 图片相关 API + // -------------------------------------------------------- + + // 获取图片信息 + // TODO get_image 不会 + // 检查是否可以发送图片 + // TODO can_send_image 不会 + // 图片 OCR + // TODO ocr_image .ocr_image 没找到例子 + + // -------------------------------------------------------- + // 语音 + // 语音相关 API + // -------------------------------------------------------- + + // 获取语音 + // TODO get_record + // 检查是否可以发送语音 + // TODO can_send_record 不会 + + // -------------------------------------------------------- + // 处理 + // 上报处理相关 API + // -------------------------------------------------------- + + // 处理加好友请求 + 'set_friend_add_request': async params => { + let ret = (await bot.getSystemMsg?.() || []).filter(i => i.request_type == 'friend' && i.flag == params.flag) + if (ret.length > 0) { + ret = ret[0] + if (ret.approve(params.approve)) { + if (params.remark) { + bot.pickFriend(ret.user_id).setRemark(params.remark) + } + } + } + }, + // 处理加群请求/邀请 + 'set_group_add_request': async params => { + let type = params.sub_type || params.type + let ret = (await bot.getSystemMsg?.() || []).filter(i => i.request_type == 'group' && i.sub_type == type && i.flag == params.flag) + if (ret.length > 0) { + ret = ret[0] + ret.approve(params.approve) + // 不会写拒绝理由捏 + } + }, + + // -------------------------------------------------------- + // 群信息 + // 群信息相关 API + // -------------------------------------------------------- + + // 获取群信息 + 'get_group_info': async params => { + const group = await bot.pickGroup(params.group_id) + ResponseData = group.info || group.info?.() || group.getInfo?.() + if (ResponseData.group_name) { + ResponseData.group_memo = ResponseData.group_name + } + if (ResponseData.create_time) { + ResponseData.group_create_time = ResponseData.create_time + } + if (ResponseData.grade) { + ResponseData.group_level = ResponseData.grade + } + }, + // 获取群列表 + 'get_group_list': async params => { + let list = await bot.getGroupList?.() + if (list instanceof Map) { + list = Array.from(list.values()) + } + list.map(item => { + if (item.group_name) { + item.group_memo = item.group_name + } + if (item.create_time) { + item.group_create_time = item.create_time + } + if (item.grade) { + item.group_level = item.grade + } + }) + ResponseData = list + }, + // 获取群成员信息 + 'get_group_member_info': async (params) => { + const group = await bot.pickGroup(params.group_id).pickMember(params.user_id) + ResponseData = group?.info || group.info?.() || group.getInfo?.() || await bot.getGroupMemberInfo?.(params.group_id, params.user_id); + if (ResponseData.shutup_time) { + ResponseData.shut_up_timestamp = ResponseData.shutup_time + } + if (!ResponseData.last_sent_time) { + ResponseData.last_sent_time = Date.now() + } + }, + // 获取群成员列表 + 'get_group_member_list': async (params) => { + const group = await bot.pickGroup(params.group_id) + let list = await group.getMemberMap?.() || await group.getMemberList?.() || [] + if (list instanceof Map) { + list = Array.from(list.values()) + } + list.map(item => { + if (item.shutup_time) { + item.shut_up_timestamp = item.shutup_time + } + if (!item.last_sent_time) { + item.last_sent_time = Date.now() + } + }) + ResponseData = list + }, + // 获取群荣誉信息 + // TODO get_group_honor_info + // 获取群系统消息 + 'get_group_system_msg': async params => { + let invited_requests = [] + let join_requests = [] + for (const i of (await bot.getSystemMsg?.() || [])) { + if (i.request_type == 'group') { + switch (i.sub_type) { + case 'add': + join_requests.push({ + request_id: i.seq, + requester_uin: i.user_id, + requester_nick: i.nickname, + message: i.comment, + group_id: i.group_id, + group_name: i.group_name, + checked: false, //好像这个只能获取没处理的 + actor: 0 + }) + break; + case 'invite': + invited_requests.push({ + request_id: i.seq, + invitor_uin: i.user_id, + invitor_nick: i.nickname, + group_id: i.group_id, + group_name: i.group_name, + checked: false, //同上 + actor: 0 + }) + break; + default: + break; + } + } + } + ResponseData = { + invited_requests, + join_requests + } + }, + // 获取精华消息列表 + 'get_essence_msg_list': async params => { + ResponseData = [] + let is_end = false, page_start = 0, page_limit = 50 + while (!is_end && !Version.isTrss) { + let res = await fetch(`https://qun.qq.com/cgi-bin/group_digest/digest_list?bkn=${bot.bkn}&group_code=${params.group_id}&page_start=${page_start}&page_limit=${page_limit}`, { + headers: { + Cookie: bot.cookies['qun.qq.com'] + } + }).then(r => r.json()) + if (res.retcode !== 0) return + if (res.data?.is_end === false) { + page_start++ + } else if (res.data?.is_end === true) { + is_end = true + } + for (const i of res.data.msg_list) { + ResponseData.push({ + sender_id: i.sender_uin, + sender_nick: i.sender_nick, + sender_time: i.sender_time, + operator_id: i.add_digest_uin, + operator_nick: i.add_digest_nick, + operator_time: add_digest_time, + message_id: i.msg_random + }) + } + } + }, + // 获取群 @全体成员 剩余次数 + 'get_group_at_all_remain': async params => { + let ret = await bot.pickGroup(params.group_id) + ResponseData = { + can_at_all: ret?.is_admin || false, + // 群内所有管理当天剩余 @全体成员 次数 不会获取捏 + remain_at_all_count_for_group: ret.getAtAllRemainder?.() || 0, + remain_at_all_count_for_uin: ret.getAtAllRemainder?.() || 0 + } + }, + + // -------------------------------------------------------- + // 群设置 + // 群设置相关 API + // -------------------------------------------------------- + + // 设置群名 + 'set_group_name': async params => { + await bot.setGroupName?.(params.group_id, params.group_name) + }, + // 设置群头像 + 'set_group_portrait': async params => { + await bot.setGroupPortrait?.(params.group_id, params.file) + }, + // 设置群管理员 + 'set_group_admin': async params => { + await bot.setGroupAdmin?.(params.group_id, params.user_id, params.enable) + }, + // 设置群名片 ( 群备注 ) + 'set_group_card': async params => { + await bot.setGroupCard?.(params.group_id, params.user_id, params.card) + }, + //设置群组专属头衔 + 'set_group_special_title': async params => { + await bot.setGroupSpecialTitle?.(params.group_id, params.user_id, params.special_title, params.duration || -1) + }, + + // -------------------------------------------------------- + // 群操作 + // 群操作相关 API + // -------------------------------------------------------- + + // 群单人禁言 + 'set_group_ban': async (params) => { + await bot.setGroupBan?.(params.group_id, params.user_id, params.duration) + }, + // 群全员禁言 + 'set_group_whole_ban': async params => { + await bot.setGroupWholeBan?.(params.group_id, params.enable) + }, + // 群匿名用户禁言 + 'set_group_anonymous_ban': async params => { + let flag = params.anonymous?.flag || params.anonymous_flag || params.flag + await bot.setGroupAnonymousBan?.(params.group_id, flag, params.duration) + }, + // 设置精华消息 + 'set_essence_msg': async params => { + let message_id = (await getMsgMap({ onebot_id: params.message_id }))?.message_id + if (message_id) await bot.setEssenceMessage?.(message_id) + }, + // 移出精华消息 + 'delete_essence_msg': async params => { + let message_id = (await getMsgMap({ onebot_id: params.message_id }))?.message_id + if (message_id) await bot.removeEssenceMessage?.(message_id) + }, + // 群打卡 + 'send_group_sign': async params => { + await bot.sendGroupSign?.(params.group_id) + }, + // 群设置匿名 + 'set_group_anonymous': async params => { + await bot.setGroupAnonymous?.(params.group_id, params.enable) + }, + // 发送群公告 + '_send_group_notice': async params => { + // await bot.sendGroupNotice(params.group_id, params.content) + if (!Version.isTrss) { + await fetch(`https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${bot.bkn}`, { + method: 'POST', + body: `qid=${params.group_id}&bkn=${bot.bkn}&text=${params.content}&pinned=0&type=1&settings={"is_show_edit_card":1,"tip_window_type":1,"confirm_required":1}`, + headers: { + Cookie: bot.cookies['qun.qq.com'] + } + }) + } + }, + // 获取群公告 + '_get_group_notice': async params => { + if (!Version.isTrss) { + let res = await fetch(`https://web.qun.qq.com/cgi-bin/announce/get_t_list?bkn=${bot.bkn}&qid=${params.group_id}&ft=23&s=-1&n=20`, { + headers: { + Cookie: bot.cookies['qun.qq.com'] + } + }).then(r => r.json()) + ResponseData = [] + if (res.feeds) { + for (const i of res.feeds) { + let item = { + sender_id: i.u, + publish_time: i.pubt, + message: { + text: i.msg.text + }, + images: [] + } + if (i.pics) { + for (const pic of i.pics) { + item.images.push({ + height: pic.h, + width: pic.w, + id: pic.id + }) + } + } + ResponseData.push(item) + } + } + } + }, + // 群组踢人 + 'set_group_kick': async params => { + await bot.setGroupKick?.(params.group_id, params.user_id, params.reject_add_request || false) + }, + // 退出群组 + 'set_group_leave': async params => { + await bot.setGroupLeave?.(params.group_id) + }, + + // -------------------------------------------------------- + // 文件 + // -------------------------------------------------------- + + // 上传群文件 + 'upload_group_file': async params => { + await bot.pickGroup(params.group_id).fs?.upload?.(params.file, params.folder || '/', params.name) + }, + // 删除群文件 + 'delete_group_file': async params => { + await bot.pickGroup(params.group_id).fs?.rm?.(params.file_id) + }, + // 创建群文件文件夹 + 'create_group_file_folder': async params => { + await bot.pickGroup(params.group_id).fs?.mkdir?.(params.name) + }, + // 删除群文件文件夹 + 'delete_group_folder': async params => { + await bot.pickGroup(params.group_id).fs?.rm?.(params.folder_id) + }, + // 获取群文件系统信息 + 'get_group_file_system_info': async params => { + let ret = await bot.pickGroup(params.group_id).fs?.df?.() + ResponseData = { + file_count: ret?.file_count || 0, + limit_count: ret?.max_file_count || 0, + used_space: ret?.used || 0, + total_space: ret?.total || 0 + } + }, + // 获取群根目录文件列表 + 'get_group_root_files': async (params) => { + let list = await bot.pickGroup(params.group_id).fs?.ls?.() + let files = [] + let folders = [] + let nickname = {} + if (Array.isArray(list) && list.length > 0) { + for (const item of list) { + let user_id = item.user_id + if (!nickname[user_id]) { + nickname[user_id] = (await bot.getStrangerInfo(item.user_id)).nickname + } + if (item.is_dir) { + folders.push({ + group_id: params.group_id, + folder_id: item.fid, + folder_name: item.name, + create_time: item.create_time, + creator: item.user_id, + creator_name: nickname[user_id], + total_file_count: item.file_count + }) + } else { + files.push({ + group_id: params.group_id, + file_id: item.fid, + file_name: item.name, + busid: item.busid, + file_size: item.size, + upload_time: item.create_time, + dead_time: item.duration, + modify_time: item.create_time, + download_times: item.download_times, + uploader: item.user_id, + uploader_name: nickname[user_id] + }) + } + } + } + ResponseData = { + files, + folders + } + }, + // 获取群子目录文件列表 + 'get_group_files_by_folder': async params => { + let list = await bot.pickGroup(params.group_id).fs?.ls?.(params.folder_id) + let files = [] + let folders = [] + let nickname = {} + if (Array.isArray(list) && list.length > 0) { + for (const item of list) { + let user_id = item.user_id + if (!nickname[user_id]) { + nickname[user_id] = (await bot.getStrangerInfo(item.user_id)).nickname + } + if (item.is_dir) { + folders.push({ + group_id: params.group_id, + folder_id: item.fid, + folder_name: item.name, + create_time: item.create_time, + creator: item.user_id, + creator_name: nickname[user_id], + total_file_count: item.file_count + }) + } else { + files.push({ + group_id: params.group_id, + file_id: item.fid, + file_name: item.name, + busid: item.busid, + file_size: item.size, + upload_time: item.create_time, + dead_time: item.duration, + modify_time: item.create_time, + download_times: item.download_times, + uploader: item.user_id, + uploader_name: nickname[user_id] + }) + } + } + } + ResponseData = { + files, + folders + } + }, + // 获取群文件资源链接 + 'get_group_file_url': async params => { + let file = await bot.pickGroup(params.group_id).fs?.download?.(params.file_id) + ResponseData = { + url: file?.url + } + }, + // 上传私聊文件 + 'upload_private_file': async params => { + await bot.pickFriend(params.user_id).sendFile?.(params.file, params.name) + }, + + // -------------------------------------------------------- + // Go-CqHttp 相关 + // 获取 Cookies + // -------------------------------------------------------- + + // 获取 Cookies + 'get_cookies': async params => { + ResponseData = { + cookies: await bot.getCookies?.(params.domain || null) + } + }, + // 获取 CSRF Token + 'get_csrf_token': async params => { + ResponseData = { + token: await bot.getCsrfToken?.() + } + }, + // 获取 QQ 相关接口凭证 + 'get_credentials': async params => { + ResponseData = { + cookies: await bot.getCookies?.(params.domain || null), + token: await bot.getCsrfToken?.() + } + }, + // 获取版本信息 + 'get_version_info': async params => { + ResponseData = { + app_name: 'ws-plugin', + app_version: Version.version, + protocol_version: 'v11' + } + }, + // 获取状态 + 'get_status': async params => { + ResponseData = { + online: bot.isOnline?.() || true, + good: bot.isOnline?.() || true, + app_initialized: true, + app_enabled: true, + plugins_good: true, + app_good: true, + stat: { + packet_receivend: bot.stat?.recv_pkt_cnt || 0, + packet_send: bot.stat?.sent_pkt_cnt || 0, + packet_lost: bot.stat?.lost_pkt_cnt || 0, + message_received: bot.stat?.recv_msg_cnt || 0, + message_send: bot.stat?.sent_msg_cnt || 0, + disconnect_times: 0, + lost_times: bot.stat?.lost_times || 0, + last_message_time: getLatestMsg()?.time || 0 + } + } + }, + // 重启 Go-CqHttp + // set_restart 什么?已经没了? + // 清理缓存 + 'clean_cache': async params => { + await bot.cleanCache?.() + }, + // 重载事件过滤器 + // TODO reload_event_filter 这是啥 + // 下载文件到缓存目录 + // TODO download_file 这又是啥 + // 检查链接安全性 + // TODO check_url_safely 不会 + // 获取中文分词 ( 隐藏 API ) + // .get_word_slices + // 对事件执行快速操作 ( 隐藏 API ) + '.handle_quick_operation': async ({ context, operation }) => { + switch (context.post_type) { + case 'message': + switch (context.message_type) { + case 'group': + if (operation.reply) { + if (!operation.auto_escape) { + operation.reply = CQToMsg(operation.reply) + } + if (!Array.isArray(operation.reply)) { + operation.reply = [{ type: 'text', data: { text: operation.reply } }] + } + let { sendMsg, quote } = await makeSendMsg({ message: operation.reply }, uin) + if (operation.at_sender) { + sendMsg.unshift(segment.at(context.user_id)) + } + await bot.pickGroup?.(context.group_id).sendMsg?.(sendMsg, quote) + } + if (operation.delete) { + let msg = await getMsgMap({ onebot_id: context.message_id }) + if (msg) { + await bot.deleteMsg?.(msg.message_id) + } + } + if (operation.kick) { + await bot.setGroupKick?.(context.group_id, context.user_id, true) + } + if (operation.ban) { + await bot.setGroupBan?.(context.group_id, context.user_id, context.ban_duration) + } + break; + case 'private': + if (operation.reply) { + if (operation.auto_escape) { + operation.reply = CQToMsg(operation.reply) + } + if (!Array.isArray(operation.reply)) { + operation.reply = [{ type: 'text', data: { text: operation.reply } }] + } + let { sendMsg, quote } = await makeSendMsg({ message: operation.reply }, uin) + await bot.pickFriend?.(context.user_id).sendMsg?.(sendMsg, quote) + } + break + } + break; + case 'request': + switch (context.request_type) { + case 'friend': + if (operation.approve) { + let ret = (await bot.getSystemMsg?.() || []).filter(i => i.request_type == 'friend' && i.flag == context.flag) + if (ret.length > 0) { + ret = ret[0] + if (ret.approve(operation.approve)) { + if (operation.remark) { + bot.pickFriend(ret.user_id).setRemark(operation.remark) + } + } + } + } + break; + case 'group': + let type = context.sub_type + let ret = (await bot.getSystemMsg?.() || []).filter(i => i.request_type == 'group' && i.sub_type == type && i.flag == context.flag) + if (ret.length > 0) { + ret = ret[0] + ret.approve(operation.approve) + } + } + } + }, + + + 'send_guild_channel_msg': async params => { + let { sendMsg } = await makeSendMsg(params, uin) + sendMsg.unshift({ + type: 'reply', + data: { + id: getGuildLatestMsgId() + } + }) + await bot.pickGroup?.(`qg_${params.guild_id}-${params.channel_id}`)?.sendMsg?.(sendMsg) + logger.mark(`[ws-plugin] 连接名字:${name} 处理完成`) + }, + 'get_guild_service_profile': async params => { + ResponseData = { + avatar_url: bot.avatar, + nickname: bot.nickname, + tiny_id: bot.tiny_id + } + }, + 'get_guild_list': async params => { + ResponseData = await bot.getGuildList?.() + }, + 'get_guild_channel_list': async params => { + + }, + + } + api = api.replace(/_async$/, '') + if (typeof publicApi[api] === 'function') { + await publicApi[api](params) + if (sendRet) { + const onebot_id = Math.floor(Math.random() * Math.pow(2, 32)) | 0 + ResponseData = { + ...sendRet, + message_id: onebot_id, + } + setMsgMap({ + message_id: sendRet.message_id, + time: sendRet.time, + seq: sendRet.seq, + rand: sendRet.rand, + user_id: params.user_id, + group_id: params.group_id, + onebot_id, + }) + } + return ResponseData + } else { + logger.warn(`[ws-plugin] 未适配的api: ${api}`); + } +} + +export { + getApiData +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/db/base.js b/Yunzai/plugins/ws-plugin/model/db/base.js new file mode 100644 index 0000000000000000000000000000000000000000..999e51aed8bcad8eaee3e4240e5475a9e85f071a --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/db/base.js @@ -0,0 +1,43 @@ +import { dirname, resolve } from 'path'; +import { fileURLToPath } from 'url' + +let Sequelize, DataTypes, sequelize, Op, existSQL = true +try { + const modules = await import('sequelize'); + Sequelize = modules.Sequelize; + DataTypes = modules.DataTypes; + Op = modules.Op + + const __filename = fileURLToPath(import.meta.url); + const __dirname = dirname(__filename); + + sequelize = new Sequelize({ + dialect: 'sqlite', + storage: resolve(__dirname, 'data.db'), + logging: false, + }) + + await sequelize.authenticate() +} catch (error) { + logger.warn('[ws-plugin] Yunzai-Bot暂不支持sqlite3数据库,建议切换至Miao-Yunzai获得最佳体验') + existSQL = false + sequelize = new Proxy({}, { + get: () => { + return () => { + return new Promise((resolve, reject) => { + resolve(); + }); + } + }, + }); + DataTypes = {}; +} + + + +export { + sequelize, + DataTypes, + Op, + existSQL +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/db/index.js b/Yunzai/plugins/ws-plugin/model/db/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fe6b0c475af022bdd6e24532f8f329398d60773e --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/db/index.js @@ -0,0 +1,8 @@ +import { existSQL } from './base.js' +import { setMessage_id, getMessage_id } from './message_id.js' + +export { + existSQL, + setMessage_id, + getMessage_id +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/db/message_id.js b/Yunzai/plugins/ws-plugin/model/db/message_id.js new file mode 100644 index 0000000000000000000000000000000000000000..aa1584627fe5443c907b25ac60e5c1e83ee61b10 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/db/message_id.js @@ -0,0 +1,105 @@ +import { sequelize, DataTypes, Op, existSQL } from './base.js' +import schedule from "node-schedule" + +const message_id_table = sequelize.define('message_id', { + id: { + type: DataTypes.INTEGER, + primaryKey: true, + autoIncrement: true, + }, + message_id: { + type: DataTypes.STRING, + unique: true + }, + seq: DataTypes.INTEGER, + rand: DataTypes.BIGINT, + time: DataTypes.BIGINT, + user_id: DataTypes.BIGINT, + group_id: DataTypes.BIGINT, + onebot_id: DataTypes.INTEGER, +}) + + +await sequelize.sync() + +let lock = Promise.resolve() + +async function setMessage_id({ message_id, seq, rand, time, user_id, group_id, onebot_id }) { + let _lock = lock + lock = new Promise((resolve, reject) => { + _lock.then(async () => { + try { + const [result, created] = await message_id_table.upsert({ + message_id, + seq, + rand, + time, + user_id, + group_id, + onebot_id + }, { + returning: true + }) + resolve(result?.dataValues) + } catch (error) { + reject(error) + } + }) + }) + + return await lock +} + +async function getMessage_id(where, order = [['createdAt', 'DESC']]) { + let _lock = lock + + lock = new Promise((resolve, reject) => { + _lock.then(async () => { + try { + const result = await message_id_table.findOne({ + where, + order, + }) + resolve(result?.dataValues) + } catch (error) { + reject(error) + } + }) + }) + return await lock +} +if (existSQL) { + const job = schedule.scheduleJob('0 30 0 * * ?', async function () { + let _lock = lock + + lock = new Promise((resolve, reject) => { + _lock.then(async () => { + try { + const staleData = new Date() + // TODO 自定义存储时间 + staleData.setDate(staleData.getDate() - 7) + + await message_id_table.destroy({ + where: { + createdAt: { + [Op.lt]: staleData + } + } + }) + await sequelize.query('VACUUM'); + resolve() + } catch (error) { + reject(error) + } + }) + }) + + await lock + }) +} + + +export { + setMessage_id, + getMessage_id +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/index.js b/Yunzai/plugins/ws-plugin/model/index.js new file mode 100644 index 0000000000000000000000000000000000000000..37e9bbe158050914c38103c6301985ce6adfe856 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/index.js @@ -0,0 +1,21 @@ +import { lifecycle, heartbeat } from './meta.js' +import { makeOneBotReportMsg, makeGSUidReportMsg, makeGSUidSendMsg } from './makeMsg.js' +import { getApiData } from './api.js' +import { setGuildLatestMsgId, getGuildLatestMsgId, setMsgMap } from './msgMap.js' +import { TMP_DIR, sleep, mimeTypes, decodeHtml } from './tool.js' + +export { + lifecycle, + heartbeat, + makeOneBotReportMsg, + makeGSUidReportMsg, + getApiData, + makeGSUidSendMsg, + setGuildLatestMsgId, + getGuildLatestMsgId, + setMsgMap, + TMP_DIR, + sleep, + mimeTypes, + decodeHtml +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/makeMsg.js b/Yunzai/plugins/ws-plugin/model/makeMsg.js new file mode 100644 index 0000000000000000000000000000000000000000..ddd5ce7ded467644a3e25cd0644831a17ae4ddf0 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/makeMsg.js @@ -0,0 +1,446 @@ +import { Config, Version } from '../components/index.js' +import { MsgToCQ, CQToMsg } from './CQCode.js' +import { getMsgMap, setMsgMap } from './msgMap.js' +import { SendMusicShare, TMP_DIR, decodeHtml } from './tool.js' +import common from '../../../lib/common/common.js' +import { randomUUID } from 'crypto' +import fs from 'fs' +import _ from 'lodash' +import fetch from 'node-fetch' + +/** + * 制作OneBot上报消息 + * @param {*} e + * @returns + */ +async function makeOneBotReportMsg(e) { + let reportMsg = await msgToOneBotMsg(e.message, e.source) + + if (!reportMsg) { + return false + } + let raw_message = MsgToCQ(reportMsg) + if (Config.messagePostFormat == 'string' || Config.messagePostFormat == '1') { + reportMsg = raw_message + } + setMsgMap({ + message_id: e.message_id, + time: e.time, + seq: e.seq, + rand: e.rand, + user_id: e.user_id, + group_id: e.group_id, + onebot_id: e.param.message_id, + }) + let Message = { + message: reportMsg, + raw_message: raw_message, + ...e.param + } + + return JSON.stringify(Message) +} + +/** + * 制作gsuid_core上报消息 + * @param {*} e + * @returns + */ +async function makeGSUidReportMsg(e) { + let message = [] + let msg = e.message + if (e.source) { + message.push({ + type: "reply", + data: String(e.source.message_id) + }) + } + for (const i of msg) { + switch (i.type) { + case 'at': + message.push({ + type: 'at', + data: i.qq + }) + break; + case 'text': + if (Config.noMsgInclude.length > 0 && Array.isArray(Config.noMsgInclude)) { + if (Config.noMsgInclude.some(item => i.text.includes(item))) { + return false + } + } + message.push({ + type: 'text', + data: i.text + }) + break; + case 'image': + message.push({ + type: 'image', + data: i.url + }) + break; + case 'file': + if (e.isGroup || Version.isTrss) break + let fileUrl = await e.friend.getFileUrl(e.file.fid); + let res = await fetch(fileUrl); + let arrayBuffer = await res.arrayBuffer(); + let buffer = Buffer.from(arrayBuffer); + let base64 = buffer.toString('base64'); + let name = i.name + message.push({ + type: 'file', + data: `${name}|${base64}` + }) + break; + case 'reply': + message.push({ + type: "reply", + data: String(i.id) + }) + break + default: + break; + } + } + if (message.length == 0) { + return false + } + let user_pm = 6 + if (e.isMaster) { + user_pm = 1 + } else if (e.isGroup) { + if (e.sender.role === 'owner') { + user_pm = 2 + } else if (e.sender.role === 'admin') { + user_pm = 3 + } + } + const MessageReceive = { + bot_id: 'Yunzai_Bot', + bot_self_id: String(e.self_id), + msg_id: String(e.message_id), + user_id: String(e.user_id), + user_pm: user_pm, + content: message + }; + if (e.isGroup) { + MessageReceive.user_type = 'group' + MessageReceive.group_id = String(e.group_id) + } else if (e.isGuild) { + MessageReceive.user_type = 'channel' + MessageReceive.group_id = String(e.group_id) + } else { + MessageReceive.user_type = 'direct' + } + return Buffer.from(JSON.stringify(MessageReceive)) +} + +/** + * 制作gsuid发送消息 + * @param {*} data + */ +async function makeGSUidSendMsg(data) { + let content = data.content, sendMsg = [], quote = null, bot = Version.isTrss ? Bot[data.bot_self_id] : Bot + if (content[0].type.startsWith('log')) { + logger.info(content[0].data); + } else { + let target = data.target_type == 'direct' ? 'pickFriend' : 'pickGroup' + for (const msg of content) { + switch (msg.type) { + case 'image': + sendMsg.push(segment.image(msg.data)) + break; + case 'text': + sendMsg.push(msg.data) + break; + case 'at': + sendMsg.push(segment.at(Number(msg.data) || String(msg.data))) + break; + case 'reply': + quote = await bot.getMsg?.(msg.data) || await bot[target].getChatHistory?.(msg.data, 1)?.[0] || null + break; + case 'file': + let file = msg.data.split('|') + let buffer = Buffer.from(file[1], 'base64') + bot.pickGroup(data.target_id)?.fs?.upload?.(buffer, '/', file[0]) + break; + case 'node': + let arr = [] + for (const i of msg.data) { + const { sendMsg: message } = await makeGSUidSendMsg({ content: [i], target_type: data.target_type, target_id: data.target_id }) + arr.push({ + message, + nickname: '小助手', + user_id: 2854196310 + }) + } + sendMsg.push(await bot[target](data.target_id).makeForwardMsg?.(arr) || { type: 'node', data: arr }) + break; + default: + break; + } + } + } + return { sendMsg, quote } +} + +/** + * 制作onebot发送的消息 + * @param {*} params + * @returns sendMsg , quote + */ +async function makeSendMsg(params, uin) { + const bot = Bot[uin] || Bot + let msg = params.message + if (typeof msg == 'string') msg = CQToMsg(msg) + let target, uid, sendMsg = [], quote = null + for (const i of msg) { + switch (i.type) { + case 'reply': + if (i.data.text) { + quote = { + message: i.data.text, + user_id: i.data.qq, + time: i.data.time, + seq: i.data.seq + } + } else { + quote = await getMsgMap({ onebot_id: i.data.id }) + if (quote) { + quote = await bot.getMsg?.(quote.message_id) + } else { + sendMsg.push(MsgToCQ([i])) + } + } + break + case 'image': + sendMsg.push(segment.image(decodeURIComponent(i.data.file))) + break + case 'text': + let text = decodeHtml(i.data.text) + sendMsg.push(text) + break + case 'at': + sendMsg.push(segment.at(Number(i.data.qq) || 'all')) + break + case 'video': + i.data.file = decodeURIComponent(i.data.file) + if (i.data.file.startsWith('http')) { + const path = TMP_DIR + '/' + randomUUID({ disableEntropyCache: true }) + '.mp4' + if (await common.downFile(i.data.file, path)) { + sendMsg.push(segment.video(path)) + setTimeout(() => { + fs.unlinkSync(path) + }, 100000) + } else { + sendMsg.push(MsgToCQ([i])) + } + } else { + sendMsg.push(segment.video(i.data.file)) + } + break + case 'music': + if (params.message_type == 'group') { + target = 'pickGroup' + uid = params.group_id + } else { + target = 'pickFriend' + uid = params.user_id + } + if (i.data.type == 'custom') { + let data = i.data + data.bot_id = uin + data.message_type = params.message_type + data.user_id = params.user_id + data.group_id = params.group_id + await SendMusicShare(data) + } else { + await bot[target](uid).shareMusic(i.data.type, i.data.id) + } + break + case 'poke': + await bot.pickGroup(params.group_id).pokeMember(Number(i.data.qq)) + break + case 'record': + sendMsg.push(segment.record(decodeURIComponent(i.data.file))) + break + case 'face': + sendMsg.push(segment.face(i.data.id)) + break + case 'node': + let data = { + ...params, + messages: [{ data: i.data }] + } + sendMsg.push(await makeForwardMsg(data)) + break + case 'json': + let json = decodeHtml(i.data.data) + sendMsg.push(segment.json(json)) + break + default: + sendMsg.push(MsgToCQ([i])) + logger.warn(`[ws-plugin] 出现了未适配的消息的类型${JSON.stringify(i)}`) + break + } + } + return { sendMsg, quote } +} + +/** + * 制作合并转发的消息 + * @param {*} params + */ +async function makeForwardMsg(params, uin) { + let forwardMsg = [] + for (const msg of params.messages) { + if (typeof msg.data.content == 'string') { + msg.data.content = [CQToMsg(msg.data.content)] + } + if (msg.data.content.type == 'image') { + msg.data.content = [{ + type: 'image', + data: { + file: msg.data.content.file || msg.data.content.data.file + } + }] + } + let node = null + for (let i of msg.data.content) { + if (i.type == 'node') { + if (node) { + node.messages.push({ data: i.data }) + } else { + node = { + ...params, + messages: [{ data: i.data }] + } + } + continue + } + if (!Array.isArray(i)) i = [i] + const data = { + ...params, + message: i + } + let { sendMsg } = await makeSendMsg(data) + forwardMsg.push({ + nickname: msg.data.name, + user_id: Number(msg.data.uin), + message: sendMsg + }) + } + if (node) { + forwardMsg.push({ + nickname: msg.data.name, + user_id: Number(msg.data.uin), + message: await makeForwardMsg(node) + }) + } + } + const bot = Bot[uin] || Bot + if (params.group_id) { + forwardMsg = await bot.pickGroup(params.group_id).makeForwardMsg?.(forwardMsg) || { type: "node", data: forwardMsg } + } else if (params.user_id) { + forwardMsg = await bot.pickFriend(params.user_id).makeForwardMsg?.(forwardMsg) || { type: "node", data: forwardMsg } + } + return forwardMsg +} + +/** + * 转换成onebot消息 + * @returns + */ +async function msgToOneBotMsg(msg, source = null) { + let reportMsg = [] + if (source) { + const keys = ['message_id', 'rand', 'time', 'seq'] + const getData = keys.reduce((obj, key) => { + if (source[key] !== undefined) { + obj[key] = source[key] + } + return obj + }, {}); + const msg = await getMsgMap(getData) + if (msg) { + reportMsg.push({ + "type": "reply", + "data": { + "id": msg.onebot_id + } + }) + } + } + for (let i = 0; i < msg.length; i++) { + switch (msg[i].type) { + case 'at': + reportMsg.push({ + "type": "at", + "data": { + "qq": msg[i].qq + } + }) + break + case 'text': + if (Array.isArray(Config.noMsgStart) && Config.noMsgInclude.length > 0) { + if (Config.noMsgInclude.some(item => msg[i].text.includes(item))) { + return false + } + } + reportMsg.push({ + "type": "text", + "data": { + "text": msg[i].text + } + }) + break + case 'image': + reportMsg.push({ + "type": "image", + "data": { + file: msg[i].file, + subType: msg[i].asface ? 1 : 0, + url: msg[i].url + } + }) + break + case 'json': + reportMsg.push({ + "type": 'json', + "data": { + "data": msg[i].data + } + }) + break + case 'face': + reportMsg.push({ + 'type': 'face', + 'data': { + 'id': msg[i].id + } + }) + break + case 'record': + reportMsg.push({ + 'type': 'record', + 'data': { + 'file': msg[i].file + } + }) + break + default: + break + } + } + return reportMsg +} + +export { + makeOneBotReportMsg, + makeGSUidReportMsg, + makeSendMsg, + makeForwardMsg, + makeGSUidSendMsg, + msgToOneBotMsg +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/meta.js b/Yunzai/plugins/ws-plugin/model/meta.js new file mode 100644 index 0000000000000000000000000000000000000000..7ccbe710f3af046d991e1540519efad1e1f39e7a --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/meta.js @@ -0,0 +1,64 @@ +import { Config, Version } from '../components/index.js' +import { getLatestMsg } from './msgMap.js' +/** + * 生命周期 + * @param {*} socket + */ +function lifecycle(uin) { + return JSON.stringify({ + meta_event_type: 'lifecycle', + post_type: 'meta_event', + self_id: uin, + sub_type: 'connect', + time: Date.parse(new Date()) / 1000 + }) +} + +/** + * 心跳 + * @param {*} socket + */ +function heartbeat(uin) { + let latestMsg = getLatestMsg() + let time = 0 + if (latestMsg) { + time = latestMsg.time + } + let status + if (Version.isTrss) { + status = { + online: true, + good: true, + stat: {} + } + } else { + status = { + online: Bot.isOnline(), + good: Bot.isOnline(), + stat: { + packet_receivend: Bot.stat.recv_pkt_cnt, + packet_send: Bot.stat.sent_pkt_cnt, + packet_lost: Bot.stat.lost_pkt_cnt, + message_received: Bot.stat.recv_msg_cnt, + message_send: Bot.stat.sent_msg_cnt, + disconnect_times: 0, + lost_times: Bot.stat.lost_times, + last_message_time: time + } + + } + } + return JSON.stringify({ + time: Date.parse(new Date()) / 1000, + self_id: uin, + post_type: 'meta_event', + meta_event_type: 'heartbeat', + status, + interval: Config.heartbeatInterval * 1000 + }) +} + +export { + lifecycle, + heartbeat +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/msgMap.js b/Yunzai/plugins/ws-plugin/model/msgMap.js new file mode 100644 index 0000000000000000000000000000000000000000..c66ecd6ec14f7a1c26910efc151fc83400793bcd --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/msgMap.js @@ -0,0 +1,53 @@ +import { Config } from "../components/index.js" +import { setMessage_id, getMessage_id, existSQL } from './db/index.js' + +let latestMsg = null + +let guildLatestMesId = null + +async function getMsgMap(where, other) { + if (existSQL) { + const msg = await getMessage_id(where, other) + return msg + } else { + let key = where.onebot_id || where.message_id + let msg = await redis.get(`Yz:ws-plugin:msg:${key}`) + if (!msg) { + return null + } + return JSON.parse(msg) + } +} + +async function setMsgMap(value) { + if (existSQL) { + await setMessage_id(value) + } else { + const EX = Config.msgStoreTime + if (EX > 0) { + await redis.set(`Yz:ws-plugin:msg:${value.onebot_id}`, JSON.stringify(value), { EX }) + await redis.set(`Yz:ws-plugin:msg:${value.message_id}`, JSON.stringify(value), { EX }) + } + } + latestMsg = value +} + +function getLatestMsg() { + return latestMsg +} + +function getGuildLatestMsgId() { + return guildLatestMesId +} + +function setGuildLatestMsgId(message_id) { + guildLatestMesId = message_id +} + +export { + getMsgMap, + setMsgMap, + getLatestMsg, + getGuildLatestMsgId, + setGuildLatestMsgId +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/red/bot.js b/Yunzai/plugins/ws-plugin/model/red/bot.js new file mode 100644 index 0000000000000000000000000000000000000000..05968b42475f2d2645bbce3c64eeedc7eba79b9c --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/red/bot.js @@ -0,0 +1,361 @@ +import { makeSendMsg, makeMessage } from './message.js' +import { setMsgMap, getMsgMap } from '../msgMap.js' +import { roleMap } from './tool.js' + +export class QQRedBot { + constructor(bot) { + this.bot = bot + this.self_id = bot.self_id + this.nickname = bot.nickname + this.adapter = { + id: "QQ", + name: "chronocat" + } + this.avatar = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${bot.uin}` + this.ws = bot.ws + this.sendApi = bot.sendApi + this.uin = bot.self_id + this.uid = bot.info.uid + this.nickname = bot.nickname + this.self_id = bot.self_id + this.stat = { + start_time: Date.now() / 1000, + recv_msg_cnt: 0 + } + this.version = { + id: "QQ", + name: "chronocat" + } + this.fl = new Map() + this.gl = new Map() + this.gml = new Map() + this.getConfig = {} + this.init() + } + + async init() { + await this.getFriendList() + await this.getGroupList() + } + + pickGroup(group_id) { + if (!this.getConfig[group_id]) { + this.getGroupMemberList(group_id) + this.getConfig[group_id] = true + } + const i = { + ...this.gl.get(Number(group_id)), + self_id: this.uin, + bot: this.bot, + group_id + } + return { + ...i, + sendMsg: async (msg) => await this.sendGroupMsg(group_id, msg), + pickMember: user_id => this.pickMember(group_id, user_id), + getMemberMap: async () => await this.getGroupMemberList(group_id), + recallMsg: async message_id => await this.deleteMsg(message_id), + sendFile: async file => await this.sendGroupMsg(group_id, [{ type: 'file', file }]), + getChatHistory: async (seq, count) => await this.getChatHistory(seq, count, 'group', group_id), + getInfo: async () => await this.getGroupInfo(group_id), + muteMember: async (user_id, duration) => await this.setGroupBan(group_id, user_id, duration), + muteAll: async (enable) => await this.setGroupWholeBan(group_id, enable), + kickMember: async (user_id, message, block) => await this.setGroupKick(group_id, user_id, false, message), + makeForwardMsg: (msg) => { return { type: "node", data: msg } } + } + } + + pickFriend(user_id) { + const user = this.fl.get(Number(user_id)) + const i = { + ...user, + self_id: this.uin, + bot: this.bot, + user_id, + } + const chatType = user?.isGroupMsg ? 100 : 1 + return { + ...i, + sendMsg: async msg => await this.sendPrivateMsg(user_id, msg, chatType), + recallMsg: async message_id => await this.deleteMsg(message_id), + sendFile: async file => await this.sendPrivateMsg(user_id, [{ type: 'file', file }], chatType), + getChatHistory: async (time, count) => await this.getChatHistory(time, count, 'friend', user_id), + getFileUrl: async (fid) => `http://127.0.0.1:${Bot.server.address().port}/ws-plugin?file=${fid}`, + makeForwardMsg: (msg) => { return { type: "node", data: msg } } + } + } + + pickMember(group_id, user_id) { + if (!this.getConfig[group_id]) { + this.getGroupMemberList(group_id) + this.getConfig[group_id] = true + } + const info = this.gml.get(Number(group_id))?.get?.(Number(user_id)) + const i = { + ...info, + self_id: this.uin, + bot: this.bot, + group_id: group_id, + user_id: user_id, + } + return { + ...i, + info, + ...this.pickFriend(user_id), + kick: async (message, block) => await this.setGroupKick(group_id, user_id, false, message), + mute: async (duration) => await this.setGroupBan(group_id, user_id, duration), + getInfo: async () => await this.getGroupMemberInfo(group_id, user_id), + getAvatarUrl: () => `https://q1.qlogo.cn/g?b=qq&s=0&nk=${user_id}` + } + } + + pickUser(user_id) { + return this.pickFriend(user_id) + } + + async sendGroupMsg(group_id, message) { + const data = { + bot: this.bot, + self_id: this.uin, + group_id + } + const { msg: elements, log, message_id: id, rand, seq, time } = await makeSendMsg(data, message) + if (id) return { message_id: id, rand, seq, time } + const result = await this.bot.sendApi('POST', 'message/send', JSON.stringify({ + peer: { + chatType: 2, + peerUin: String(group_id) + }, + elements + })) + if (result.error) { + throw result.error + } else { + logger.info(`${logger.blue(`[${this.uin} => ${group_id}]`)} 发送群消息:${log}`) + } + const sendRet = { + message_id: result.msgId, + seq: Number(result.msgSeq), + rand: Number(result.msgRandom), + time: Number(result.msgTime), + group_id: Number(group_id), + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + } + setMsgMap(sendRet) + sendRet.md5 = elements.filter((i) => i.elementType === 2) + return sendRet + } + + async sendPrivateMsg(user_id, message, chatType = 1) { + if ([1, 100].indexOf(chatType) == -1) chatType = 1 + const data = { + bot: this.bot, + self_id: this.uin, + user_id + } + const { msg: elements, log, message_id: id, rand, seq, time } = await makeSendMsg(data, message) + if (id) return { message_id: id, rand, seq, time } + const result = await this.bot.sendApi('POST', 'message/send', JSON.stringify({ + peer: { + chatType, + peerUin: String(user_id) + }, + elements + })) + if (result.error) { + throw result.error + } else { + logger.info(`${logger.blue(`[${this.uin} => ${user_id}]`)} 发送好友消息:${log}`) + } + const sendRet = { + message_id: result.msgId, + seq: Number(result.msgSeq), + rand: Number(result.msgRandom), + user_id: Number(user_id), + time: Number(result.msgTime), + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + } + setMsgMap(sendRet) + sendRet.md5 = elements.filter((i) => i.elementType === 2) + return sendRet + } + + async getMsg(message_id) { + const retult = await this.getChatHistory(message_id, 1) + if (retult.length > 0) { + return retult[0] + } else { + return null + } + } + + async deleteMsg(message_id) { + const msg = await getMsgMap({ message_id }) + if (msg) { + this.bot.sendApi('POST', 'message/recall', JSON.stringify({ + peer: { + chatType: msg.group_id ? 2 : 1, + peerUin: String(msg.group_id || msg.user_id), + guildId: null + }, + msgIds: [msg.message_id] + })) + } + } + + async getChatHistory(message_id, count, target, target_id) { + let data = {} + if (target === 'group') { + if (!message_id) message_id = (await getMsgMap({ group_id: target_id }, [['seq', 'DESC']])).seq + data = { + seq: message_id, + group_id: target_id, + } + } else if (target === 'friend') { + if (!message_id) message_id = (await getMsgMap({ user_id: target_id }, [['time', 'DESC']])).time + data = { + time: message_id, + user_id: target_id, + } + } else { + data = { + message_id, + } + } + const msg = await getMsgMap(data) + if (msg) { + const result = await this.bot.sendApi('POST', 'message/getHistory', JSON.stringify({ + peer: { + chatType: msg.group_id ? 2 : 1, + peerUin: String(msg.group_id || msg.user_id), + guildId: null + }, + offsetMsgId: msg.message_id, + count: count || 20 + })) + if (result.error) { + throw result.error + } + if (result.msgList) { + const msgList = [] + for (const i of result.msgList) { + const message = await makeMessage(this.uin, i) + if (message.bot) delete message.bot + msgList.push(message) + } + return msgList + } + } + return [] + } + + async getFriendList() { + for (const i of (await this.bot.sendApi('get', 'bot/friends')) || []) { + this.fl.set(Number(i.uin), { + ...i, + bot_id: this.uin, + user_id: i.uin, + nickname: i.nick + }) + } + return this.fl + } + + async getGroupList() { + for (const i of (await this.bot.sendApi('get', 'bot/groups')) || []) { + const data = { + ...i, + bot_id: this.uin, + group_id: i.groupCode, + group_name: i.groupName, + max_member_count: i.maxMember, + member_count: i.memberCount, + } + switch (i.memberRole) { + case 3: + data.is_admin = true + break + case 4: + data.is_owner = true + break + default: + break; + } + this.gl.set(Number(i.groupCode), data) + if (!this.gml.has(Number(i.groupCode))) { + this.gml.set(Number(i.groupCode), new Map()) + } + } + return this.gl + } + + async getGroupMemberList(group_id) { + const body = { + group: Number(group_id), + size: 9999 + } + const memberList = await this.bot.sendApi('POST', 'group/getMemberList', JSON.stringify(body)) + if (memberList.error) throw memberList.error + for (const i of memberList) { + this.gml.get(Number(group_id)).set(Number(i.detail.uin), { + ...i.detail, + card: i.detail.cardName || i.detail.nick, + nickname: i.detail.nick, + group_id, + user_id: i.detail.uin, + role: roleMap[i.detail.role], + shutup_time: i.detail.shutUpTime, + sex: 'unknown' + }) + } + return this.gml.get(Number(group_id)) + } + + async getGroupMemberInfo(group_id, user_id) { + if (!this.getConfig[group_id]) { + await this.getGroupMemberList(group_id) + this.getConfig[group_id] = true + } + return this.gl.get(Number(group_id))?.get?.(Number(user_id)) || {} + } + + async getGroupInfo(group_id) { + return this.gl.get(Number(group_id)) + } + + async setGroupBan(group_id, user_id, duration) { + const result = this.bot.sendApi('POST', 'group/muteMember', JSON.stringify({ + group: String(group_id), + memList: [{ + uin: String(user_id), + timeStamp: duration + }] + })) + if (result.error) { + throw result.error + } + } + + async setGroupWholeBan(group_id, enable = true) { + const result = this.bot.sendApi('POST', 'group/muteEveryone', JSON.stringify({ + group: String(group_id), + enable + })) + if (result.error) { + throw result.error + } + } + + async setGroupKick(group_id, user_id, reject_add_request = false, message = '') { + const result = this.bot.sendApi('POST', 'group/kick', JSON.stringify({ + uidList: [String(user_id)], + group: String(group_id), + refuseForever: reject_add_request, + reason: message + })) + if (result.error) { + throw result.error + } + return true + } +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/red/cli.exe b/Yunzai/plugins/ws-plugin/model/red/cli.exe new file mode 100644 index 0000000000000000000000000000000000000000..0826bb00fe1668300a1a7427cfa41de32ec97f76 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/model/red/cli.exe differ diff --git a/Yunzai/plugins/ws-plugin/model/red/index.js b/Yunzai/plugins/ws-plugin/model/red/index.js new file mode 100644 index 0000000000000000000000000000000000000000..47664d813dcdf14993566508b168c4f9045b06c9 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/red/index.js @@ -0,0 +1,161 @@ +import { QQRedBot } from "./bot.js" +import { getToken } from './tool.js' +import { toQQRedMsg } from './message.js' +import { Version, allSocketList, setAllSocketList } from '../../components/index.js' +import WebSocket from 'ws' +import fetch from "node-fetch" + +logger.info(logger.yellow("- 正在加载 Chronocat(red) 适配器插件")) + +export const redAdapter = new class RedAdapter { + constructor() { + this.id = "QQ" + this.name = 'chronocat' + } + + reconnectCount = 1 + + async connect(data) { + if (data.closed) return + const [host, port] = data.address.split(':') + let token = data.accessToken + if (!token) { + token = getToken() + if (!token) return + } + const bot = { + host, + port, + token + } + bot.sendApi = async (method, api, body) => { + const controller = new AbortController() + const signal = controller.signal + const timeout = 30000 + setTimeout(() => { + controller.abort() + }, timeout); + return await fetch(`http://${bot.host}:${bot.port}/api/${api}`, { + signal, + method, + body, + headers: { + Authorization: 'Bearer ' + bot.token + } + }).then(r => { + if (!r.ok) throw r + const contentType = r.headers.get('content-type'); + if (contentType.includes('application/json')) { + return r.json(); + } else if (contentType.includes('text/plain')) { + return r.text(); + } else { + return r + } + }).catch(error => { + if (error.name === 'AbortError') { + return { error: `${logger.red(`[${this.uin}] ${api} 请求超时, 请检查账号状态或重启QQ!`)}` } + } else { + return { error } + } + }) + } + const reconnect = () => { + if (!data.stopReconnect && ((this.reconnectCount < data.maxReconnectAttempts) || data.maxReconnectAttempts <= 0)) { + logger.warn(`${this.name} 开始尝试重新连接第${this.reconnectCount}次`); + this.reconnectCount++ + setTimeout(() => { + this.connect(data) + }, data.reconnectInterval * 1000); + } else { + this.stopReconnect = false + logger.warn(`${this.name} 达到最大重连次数或关闭连接,停止重连`); + } + } + let info = await bot.sendApi('get', 'getSelfProfile') + if (info.error) { + if (info.error.code == 'ECONNREFUSED') { + logger.error(`${this.name} 请检查是否安装Chronocat并启动QQNT`) + reconnect() + return + } + logger.error(`${this.name} Token错误或其他未知原因`) + logger.error(await info.error.text?.() || info.error) + return + } + if (!info.uin) { + logger.error(`${this.name} 请点击登录`) + reconnect() + return + } + bot.info = { + ...info, + user_id: info.uin, + self_id: info.uin, + nickname: info.nick, + username: info.nick + } + bot.nickname = info.nick + bot.self_id = Number(info.uin) + this.uin = bot.self_id + bot.uin = bot.self_id + bot.ws = new WebSocket(`ws://${bot.host}:${bot.port}`) + bot.send = (type, payload) => bot.ws.send(JSON.stringify({ type, payload })) + bot.ws.on('open', () => bot.send('meta::connect', { token: bot.token })) + bot.ws.on('message', data => toQQRedMsg(bot, data)) + bot.ws.on('close', (code) => { + delete Bot[bot.self_id] + switch (code) { + case 1005: + logger.error(`${this.name}(${bot.self_id}) 主动断开连接`) + return + case 1006: + logger.error(`${this.name}(${bot.self_id}) QQNT被关闭`) + reconnect() + return + default: + return + } + }) + Bot[bot.self_id] = new QQRedBot(bot) + if (!Version.isTrss) { + /** 米游社主动推送、椰奶状态pro */ + if (!Bot?.adapter) { + Bot.adapter = [Bot.uin] + Bot.adapter.push(bot.self_id) + } else { + Bot.adapter.push(bot.self_id) + /** 去重防止断连后出现多个重复的id */ + Bot.adapter = Array.from(new Set(Bot.adapter.map(JSON.stringify))).map(JSON.parse) + } + } + logger.mark(`${logger.blue(`[${bot.self_id}]`)} ${this.name}(${this.id}) 已连接`) + data.ws = { + close: () => { + bot.ws.close() + } + } + data.status = 1 + data.uin = this.uin + setAllSocketList(data) + this.reconnectCount = 1 + Bot.em(`connect.${bot.self_id}`, Bot[bot.self_id]) + return true + } + + async load() { + for (const i of allSocketList) { + if (i.type == 4) { + await new Promise(resolve => { + redAdapter.connect(i).then(resolve) + setTimeout(resolve, 5000) + }) + } + } + } +} + +if (Version.isTrss) { + Bot.adapter.push(redAdapter) +} +logger.info(logger.green("- Chronocat(red) 适配器插件 加载完成")) \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/red/message.js b/Yunzai/plugins/ws-plugin/model/red/message.js new file mode 100644 index 0000000000000000000000000000000000000000..22e588455186c471badf5ec023f671b0fe7112b6 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/red/message.js @@ -0,0 +1,722 @@ +import { uploadImg, uploadAudio, uploadVideo, uploadFile, getNtPath, roleMap, redPath } from './tool.js' +import { TMP_DIR, sleep } from '../tool.js' +import { setMsgMap, getMsgMap } from '../msgMap.js' +import { Config, Version } from '../../components/index.js' +import { randomBytes } from 'crypto' +import { join, extname, basename } from 'path' +import fs from 'fs' +import schedule from "node-schedule" +import _ from 'lodash' +import PluginsLoader from '../../../../lib/plugins/loader.js' + +async function makeSendMsg(data, message) { + if (!Array.isArray(message)) + message = [message] + const msgs = [] + let log = '' + for (let i of message) { + if (typeof i != "object") + i = { type: "text", text: i } + + switch (i.type) { + case "text": + if (typeof i.text === 'boolean') break + log += i.text + i = { + "elementType": 1, + "textElement": { + "content": String(i.text) + } + } + break + case "image": + i = await uploadImg(data.bot, i.file || i.url) + log += `[图片: ${i.picElement.md5HexStr}]` + break + case "record": + const record = await uploadAudio(i.file) + if (record) { + i = record + log += `[语音: ${record.pttElement.md5HexStr}]` + } else { + i = { + "elementType": 1, + "textElement": { + "content": JSON.stringify(i) + } + } + } + break + case "face": + i = { + "elementType": 6, + "faceElement": { + "faceIndex": i.id, + "faceType": 1 + } + } + log += `[表情: ${i.id}]` + break + case "video": + const video = await uploadVideo(data.bot, i.file) + if (video) { + i = video + log += `[视频: ${video.videoElement.videoMd5}]` + } else { + i = { + "elementType": 1, + "textElement": { + "content": JSON.stringify(i) + } + } + } + break + case "file": + const file = await uploadFile(i.file) + if (file) { + i = file + log += `[文件: ${file.fileElement.fileMd5}]` + } else { + i = { + "elementType": 1, + "textElement": { + "content": JSON.stringify(i) + } + } + } + break + case "at": + log += `[提及: ${i.qq}]` + if (i.qq == 'all') { + i = { + "elementType": 1, + "textElement": { + "content": "@全体成员", + "atType": 1 + } + } + } else { + i = { + "elementType": 1, + "textElement": { + // "content": "@时空猫猫", + "atType": 2, + "atNtUin": String(i.qq) + } + } + } + break + case "reply": + const msg = await getMsgMap({ message_id: i.id }) + if (msg) { + log += `[回复: ${i.id}]` + i = { + "elementType": 7, + "replyElement": { + "replayMsgSeq": msg.seq, + "replayMsgId": msg.message_id, + "senderUin": String(msg.user_id), + } + } + } else { + i = { + "elementType": 1, + "textElement": { + "content": JSON.stringify(i) + } + } + } + break + case "node": + if (Config.redSendForwardMsgType == 1) { + return await sendNodeMsg(data, i.data) + } else if (Config.redSendForwardMsgType == 2) { + let message_id, rand, seq, time + for (const { message: msg } of i.data) { + let peer = { + chatType: data.group_id ? 2 : 1, + peerUin: String(data.group_id || data.user_id) + } + const { msg: elements, log } = await makeSendMsg(data, msg) + if (!elements) continue + const result = await data.bot.sendApi('POST', 'message/send', JSON.stringify({ + peer, + elements + })) + if (result.error) { + throw result.error + } else { + const sendRet = { + message_id: result.msgId, + seq: Number(result.msgSeq), + rand: Number(result.msgRandom), + time: Number(result.msgTime), + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + } + if (data.group_id) { + sendRet.group_id = Number(data.group_id) + } else { + sendRet.user_id = Number(data.user_id) + } + setMsgMap(sendRet) + message_id = result.msgId + seq = Number(result.msgSeq) + rand = Number(result.msgRandom) + time = Number(result.msgTime) + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id || data.user_id}]`)} 发送消息:${log}`) + } + // 防止发太快 + // await sleep(500) + } + return { message_id, rand, seq, time } + } else if (Config.redSendForwardMsgType == 3) { + let message_id, rand, seq, time, elements = [], logs = '' + for (let index = 0; index < i.data.length; index++) { + const { msg: element, log } = await makeSendMsg(data, i.data[index].message) + if (!element) continue + if (index != i.data.length - 1) { + element.push({ + "elementType": 1, + "textElement": { + "content": '\n' + } + }) + } + elements.push(...element) + logs += log + } + let peer = { + chatType: data.group_id ? 2 : 1, + peerUin: String(data.group_id || data.user_id) + } + const result = await data.bot.sendApi('POST', 'message/send', JSON.stringify({ + peer, + elements + })) + if (result.error) { + throw result.error + } else { + const sendRet = { + message_id: result.msgId, + seq: Number(result.msgSeq), + rand: Number(result.msgRandom), + time: Number(result.msgTime), + onebot_id: Math.floor(Math.random() * Math.pow(2, 32)) | 0, + } + if (data.group_id) { + sendRet.group_id = Number(data.group_id) + } else { + sendRet.user_id = Number(data.user_id) + } + setMsgMap(sendRet) + message_id = result.msgId + seq = Number(result.msgSeq) + rand = Number(result.msgRandom) + time = Number(result.msgTime) + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id || data.user_id}]`)} 发送消息:${_.truncate(logs, { length: 1000 })}`) + } + return { message_id, rand, seq, time } + } + break + default: + log += JSON.stringify(i) + i = { + "elementType": 1, + "textElement": { + "content": JSON.stringify(i) + } + } + } + msgs.push(i) + } + return { msg: msgs, log } +} + +async function makeMessage(self_id, payload) { + if (!payload) return null + const e = {} + e.bot = Bot[self_id] + e.post_type = 'message' + e.user_id = Number(payload.senderUin) + if (!e.user_id) return null + // e.message_id = `${payload.peerUin}:${payload.msgSeq}` + e.message_id = payload.msgId + e.time = Number(payload.msgTime) + e.seq = Number(payload.msgSeq) + e.rand = Number(payload.msgRandom) + e.nickname = payload.sendMemberName || payload.sendNickName + e.sender = { + user_id: e.user_id, + nickname: e.nickname, + role: roleMap[payload.roleType] || 'member' + } + e.self_id = Number(self_id) + e.message = [] + e.raw_message = '' + for (const i of payload.elements) { + switch (i.elementType) { + case 1: + if (i.textElement.atType == 2) { + const qq = i.textElement.atUid == '0' ? i.textElement.atNtUin : i.textElement.atUid + e.message.push({ type: 'at', qq: Number(qq) }) + e.raw_message += `[提及:${qq}]` + } else if (i.textElement.atType == 1) { + e.message.push({ type: 'at', qq: 'all' }) + e.raw_message += `[提及:全体成员]` + } else if (i.textElement.atType == 0) { + e.message.push({ type: 'text', text: i.textElement.content }) + e.raw_message += i.textElement.content + } + break; + case 2: + const md5 = i.picElement.md5HexStr + e.message.push({ + type: 'image', + url: `https://gchat.qpic.cn/gchatpic_new/0/0-0-${md5.toUpperCase()}/0`, + file: md5 + }) + e.raw_message += `[图片: https://gchat.qpic.cn/gchatpic_new/0/0-0-${md5.toUpperCase()}/0]` + break + case 3: + if (payload.chatType == 2) break + const file = await Bot[self_id].sendApi('POST', 'message/fetchRichMedia', JSON.stringify({ + "msgId": e.message_id, + "chatType": payload.chatType, + "peerUid": payload.peerUin, + "elementId": i.elementId, + "thumbSize": 0, + "downloadType": 2 + })) + if (file.error) throw file.error + const buffer = Buffer.from(await file.arrayBuffer()) + const fid = `${e.time}-${i.fileElement.fileName}` + fs.writeFileSync(join(TMP_DIR, fid), buffer) + e.message.push({ + type: 'file', + name: i.fileElement.fileName, + fid, + md5: i.fileElement.fileMd5, + size: i.fileElement.fileSize, + }) + e.raw_message += `[文件: ${i.fileElement.fileName}]` + break + case 4: + e.message.push({ + type: 'record', + file: i.pttElement.fileName, + md5: i.pttElement.md5HexStr, + size: i.pttElement.fileSize + }) + e.raw_message += `[语音: ${i.pttElement.fileName}]` + break + case 5: + e.message.push({ + type: 'video', + name: i.videoElement.fileName, + fid: i.videoElement.fileUuid, + md5: i.videoElement.thumbMd5, + size: i.videoElement.thumbSize + }) + e.raw_message += `[视频: ${i.videoElement.fileName}]` + break + case 6: + e.message.push({ type: 'face', id: Number(i.faceElement.faceIndex) }) + e.raw_message += `[表情: ${i.faceElement.faceIndex}]` + break + case 7: + // e.message.push({ + // type: 'reply', + // id: `${payload.peerUin}:${i.replyElement.replayMsgSeq}`, + // seq: `${payload.peerUin}:${i.replyElement.replayMsgSeq}`, + // }) + let replyMsg = i.replyElement.sourceMsgTextElems.reduce((acc, item) => acc + item.textElemContent, '') + const getMsgData = { + seq: Number(i.replyElement.replayMsgSeq), + } + if (payload.chatType == 2) { + getMsgData.group_id = Number(payload.peerUin) + } else if (payload.chatType == 1) { + getMsgData.user_id = e.user_id + } + const msg = await getMsgMap(getMsgData) + e.source = { + message_id: msg?.message_id, + seq: Number(i.replyElement.replayMsgSeq), + time: Number(i.replyElement.replyMsgTime), + rand: msg?.rand, + user_id: Number(i.replyElement.senderUid), + message: replyMsg + } + e.raw_message += `[回复: ${msg?.message_id || i.replyElement.replayMsgSeq}]` + break + case 8: + switch (i.grayTipElement.subElementType) { + case 4: + if (i.grayTipElement.groupElement.memberAdd) { + // i.grayTipElement.groupElement.type = 4 + e.post_type = 'notice' + e.notice_type = 'group' + e.sub_type = 'increase' + e.nickname = i.grayTipElement.memberNick + e.user_id = Number(i.grayTipElement.groupElement.memberUin) + // e.nickname = i.grayTipElement.groupElement.memberAdd.otherAdd.name + // e.user_id = Number(i.grayTipElement.groupElement.memberAdd.otherAdd.uin) + } + if (i.grayTipElement.groupElement.shutUp) { + // i.grayTipElement.groupElement.type = 8 + e.post_type = 'notice' + e.notice_type = 'group' + e.sub_type = 'ban' + e.duration = i.grayTipElement.groupElement.shutUp.duration + e.user_id = Number(i.grayTipElement.groupElement.shutUp.member.uin) + e.operator_id = Number(i.grayTipElement.groupElement.shutUp.admin.uin) + } + break; + case 12: + const reg = new RegExp('^ $') + const regRet = reg.exec(i.grayTipElement.xmlElement.content) + if (regRet) { + if (regRet[2] == '邀请' && regRet[4] == '加入了群聊。') { + e.post_type = 'notice' + e.notice_type = 'group' + e.sub_type = 'increase' + e.user_id = Number(regRet[3]) + } + } + break + default: + break; + } + break + case 11: + e.message.push({ + type: 'bface', + file: i.marketFaceElement.emojiId, + text: i.marketFaceElement.faceName + }) + e.raw_message += `[bface: ${i.marketFaceElement.faceName}]` + break + case 16: + e.message.push({ type: 'xml', data: i.multiForwardMsgElement.xmlContent }) + e.raw_message += `[xml: ${i.multiForwardMsgElement.xmlContent}]` + break + default: + break; + } + } + if (payload.chatType == 2) { + if (!e.sub_type) { + e.message_type = 'group' + e.sub_type = 'normal' + } + e.group_id = Number(payload.peerUin) + e.group_name = payload.peerName + } else if (payload.chatType == 1) { + if (!e.sub_type) { + e.message_type = 'private' + e.sub_type = 'friend' + } + } else if (payload.chatType == 100) { + if (!e.sub_type) { + e.message_type = 'private' + e.sub_type = 'group' + } + Bot[self_id].fl.set(e.user_id, { + bot_id: self_id, + user_id: e.user_id, + nickname: e.nickname, + isGroupMsg: true + }) + } + + if (e.group_id) e.group = e.bot.pickGroup(e.group_id) + if (e.user_id) e.friend = e.bot.pickFriend(e.user_id) + if (e.group && e.user_id) e.member = e.group.pickMember(e.user_id) + if (!Version.isTrss) { + e.pickFriend = (user_id) => Bot[self_id].pickFriend(user_id) + e.pickGroup = (group) => Bot[self_id].pickGroup(group) + e.pickMember = (group_id, user_id) => Bot[self_id].pickMember(group_id, user_id) + e.pickUser = (user_id) => Bot[self_id].pickUser(user_id) + e.reply = (msg, quote) => { + if (!Array.isArray(msg)) msg = [msg] + if (quote && e.message_id) { + msg.unshift({ type: 'reply', id: e.message_id }) + } + if (e.isGroup) { + if (e.group?.sendMsg) { + return e.group.sendMsg(msg) + } else { + return e.bot.pickGroup(e.group_id).sendMsg(msg) + } + } else { + if (e.friend?.sendMsg) { + return e.friend.sendMsg(msg) + } else { + return e.bot.pickFriend(e.user_id).sendMsg(msg) + } + } + } + } + return e +} + +async function sendNodeMsg(data, msg) { + const msgElements = await makeNodeMsg(data, msg) + let target + if (data.group_id) { + target = { + chatType: 2, + peerUin: String(data.group_id) + } + } else if (data.user_id) { + target = { + chatType: 1, + peerUin: String(data.user_id) + } + } + const payload = { + msgElements, + srcContact: target, + dstContact: target + } + const result = await data.bot.sendApi('POST', 'message/unsafeSendForward', JSON.stringify(payload)) + if (result.error) { + throw result.error + } + const sendRet = { + message_id: result.msgId, + seq: Number(result.msgSeq), + rand: Number(result.msgRandom), + user_id: Number(data.user_id), + time: Number(result.msgTime), + group_id: Number(data.group_id), + } + setMsgMap(sendRet) + logger.info(`${logger.blue(`[${data.self_id} => ${data.group_id || data.user_id}]`)} 发送${target.chatType == 1 ? '好友' : '群'}消息:[转发消息]`) + return sendRet +} + +async function makeNodeMsg(data, msg) { + const msgElements = [] + let seq = randomBytes(2).readUint16BE() + for (const item of msg) { + if (typeof item.message == 'string') item.message = { type: 'text', text: item.message } + if (!Array.isArray(item.message)) item.message = [item.message] + const elems = [] + for (let i of item.message) { + if (typeof i === 'string') i = { type: 'text', text: i } + switch (i.type) { + case 'text': + elems.push({ + text: { + str: i.text + } + }) + break; + case 'image': + const img = await uploadImg(data.bot, i.file || i.url) + const sendRet = await data.bot.sendApi('POST', 'message/send', JSON.stringify({ + peer: { + chatType: 1, + peerUin: String(data.self_id) + }, + elements: [img] + })) + if (sendRet.error) { + throw sendRet.error + } + data.bot.sendApi('POST', 'message/recall', JSON.stringify({ + peer: { + chatType: 1, + peerUin: String(data.self_id), + guildId: null, + }, + msgIds: [sendRet.msgId] + })) + let formattedStr = convertFileName(img.picElement.sourcePath) + elems.push({ + "customFace": { + "filePath": formattedStr, + "fileId": randomBytes(2).readUint16BE(), + "serverIp": -1740138629, + "serverPort": 80, + "fileType": 1001, + "useful": 1, + "md5": Buffer.from(img.picElement.md5HexStr, 'hex').toString('base64'), + "imageType": 1001, + "width": img.picElement.picWidth, + "height": img.picElement.picHeight, + "size": img.fileSize, + "origin": 0, + "thumbWidth": 0, + "thumbHeight": 0, + // "pbReserve": [2, 0] + // "pbReserve": null + } + }) + break + case 'node': + elems.push(...await makeNodeMsg(data, i.data)) + break + default: + for (const key in i) { + if (typeof i[key] === 'string' && i[key].length > 50) { + i[key] = _.truncate(i[key], { length: 50 }) + } + } + elems.push({ + text: { + str: JSON.stringify(i) + } + }) + break; + } + } + const element = [] + if (!elems[0].head) { + element.push({ + head: { + // field2: Number(data.self_id), + field8: { + // field1: Number(data.group_id), + field4: 'QQ用户' //String(data.bot.nickname) + } + }, + content: { + field1: 82, + field4: randomBytes(4).readUint32BE(), + field5: seq++, + field6: Math.floor(Date.now() / 1000), + field7: 1, + field8: 0, + field9: 0, + field15: { + field1: 0, + field2: 0 + } + }, + body: { + richText: { + elems + } + } + }) + } else { + element.push(...elems) + } + msgElements.push(...element) + } + return msgElements +} + +function convertFileName(filePath) { + // 获取文件名(不包括扩展名) + let fileName = basename(filePath, extname(filePath)); + + // 将文件名转换为大写,并按照指定的格式添加短横线 + let convertedName = fileName.toUpperCase().replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5'); + + // 将转换后的文件名和原始扩展名拼接起来 + let newFileName = `{${convertedName}}${extname(filePath)}`; + + return newFileName; +} + +async function toQQRedMsg(bot, data) { + data = JSON.parse(data) + switch (data.type) { + case 'meta::connect': + const job = schedule.scheduleJob('0 0 4 * * ?', function () { + logger.mark('[ws-plugin] 执行定时任务: 删除Temp') + try { + const files = fs.readdirSync(TMP_DIR) + for (const file of files) { + fs.unlink(join(TMP_DIR, file), () => { }) + } + const path = `${redPath}/redprotocol-upload` + const redTemp = fs.readdirSync(path) + for (const file of redTemp) { + fs.unlink(join(path, file), () => { }) + } + } catch (error) { + + } + }); + setTimeout(() => { + if (Bot[bot.self_id]?.version) { + Bot[bot.self_id].version = { + ...data.payload, + id: 'QQ' + } + } + }, 5000) + break + case 'message::recv': + if (Bot[bot.self_id]?.stat?.recv_msg_cnt) { + Bot[bot.self_id].stat.recv_msg_cnt++ + } else { + Bot[bot.self_id].stat.recv_msg_cnt = 1 + } + const payload = data.payload[0] + const e = await makeMessage(bot.self_id, payload) + if (!e || (e.post_type === 'message' && e.message.length == 0)) return + switch (e.post_type) { + case 'message': + if (e.message_type == 'group') { + logger.info(`${logger.blue(`[${e.self_id}]`)} 群消息:[${e.group_name}(${e.group_id}), ${e.nickname}(${e.user_id})] ${e.raw_message}`) + if (!Bot[bot.self_id].gml.has(Number(e.group_id))) { + Bot[bot.self_id].gml.set(Number(e.group_id), new Map()) + } + if (!Bot[bot.self_id].gml.get(Number(e.group_id)).has(Number(e.user_id))) { + Bot[bot.self_id].gml.get(Number(e.group_id)).set(Number(e.user_id), { + bot_id: e.self_id, + group_id: e.group_id, + nickname: e.nickname, + role: e.sender.role, + user_id: e.user_id, + card: e.nickname, + sex: 'unknown' + }) + } + } else if (e.message_type == 'private') { + logger.info(`${logger.blue(`[${e.self_id}]`)} 好友消息:[${e.nickname}(${e.user_id})] ${e.raw_message}`) + if (!Bot[bot.self_id].fl.has(Number(e.user_id))) { + Bot[bot.self_id].fl.set(Number(e.user_id), { + bot_id: e.self_id, + user_id: e.user_id, + nickname: e.nickname, + }) + } + } + setMsgMap({ + message_id: e.message_id, + seq: Number(e.seq), + rand: Number(e.rand), + user_id: Number(e.user_id), + time: Number(e.time), + group_id: Number(e.group_id), + }) + // Bot.on('message',()=>{})可以监听到消息 但是self_id = 88888 + Bot.em(`${e.post_type}.${e.message_type}.${e.sub_type}`, e) + // Bot.on('message',()=>{})不可以监听到消息 但是self_id正常 + // PluginsLoader.deal(e) + break; + case 'notice': + Bot.em(`${e.post_type}.${e.notice_type}.${e.sub_type}`, e) + break + default: + break; + } + break + default: + break; + } +} + + + +export { + makeSendMsg, + toQQRedMsg, + makeMessage +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/red/tool.js b/Yunzai/plugins/ws-plugin/model/red/tool.js new file mode 100644 index 0000000000000000000000000000000000000000..70685f9a403ce195c0d8770fa0d88d19176d427c --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/red/tool.js @@ -0,0 +1,428 @@ +import fs from 'fs' +import { createHash, randomUUID } from 'crypto' +import { resolve, join, dirname, basename } from 'path' +import fetch, { FormData, Blob } from 'node-fetch' +import { fileURLToPath } from 'url' +import { exec, spawn } from 'child_process' +import os from 'os' +import _ from 'lodash' +import { Stream } from "stream" +import YAML from 'yaml' +import { TMP_DIR } from '../tool.js' + +const user = os.userInfo().username +let redPath = `C:/Users/${user}/.chronocat` +if (!fs.existsSync(redPath)) { + redPath = `C:/Users/${user}/AppData/Roaming/BetterUniverse/QQNT` +} + +const roleMap = { + 2: 'member', + 3: 'admin', + 4: 'owner' +} + +async function uploadImg(bot, msg) { + const file = await upload(bot, msg, 'image/png') + if (!file.imageInfo) throw "获取图片信息失败,请检查图片状态" + return { + elementType: 2, + picElement: { + md5HexStr: file.md5, + fileSize: file.fileSize, + picHeight: file.imageInfo.height, + picWidth: file.imageInfo.width, + fileName: basename(file.ntFilePath), + sourcePath: file.ntFilePath, + picType: file.imageInfo.type === 'gif' ? 2000 : 1000 + } + } +} + +async function upload(bot, msg, contentType) { + if (!msg) throw { noLog: true } + let buffer + if (msg instanceof Stream.Readable) { + buffer = fs.readFileSync(msg.path) + contentType = contentType.split('/')[0] + '/' + msg.path.substring(msg.path.lastIndexOf('.') + 1) + } if (Buffer.isBuffer(msg)) { + buffer = msg + } else if (msg.match(/^base64:\/\//)) { + buffer = Buffer.from(msg.replace(/^base64:\/\//, ""), 'base64') + } else if (msg.startsWith('http')) { + const img = await fetch(msg) + const type = img.headers.get('content-type'); + if (type) contentType = type + const arrayBuffer = await img.arrayBuffer() + buffer = Buffer.from(arrayBuffer) + } else if (msg.startsWith('file://')) { + buffer = fs.readFileSync(msg.replace(/file:\/{2,3}/, '')) + contentType = contentType.split('/')[0] + '/' + msg.substring(msg.lastIndexOf('.') + 1) + } else { + buffer = fs.readFileSync(msg) + contentType = contentType.split('/')[0] + '/' + msg.substring(msg.lastIndexOf('.') + 1) + } + const blob = new Blob([buffer], { type: contentType }) + const formData = new FormData() + formData.append('file', blob, 'ws-plugin.' + contentType.split('/')[1]) + const file = await bot.sendApi('POST', 'upload', formData) + if (file.error) { + throw file.error + } + file.contentType = contentType + return file +} + +async function uploadAudio(file) { + let buffer + if (file.match(/^base64:\/\//)) { + buffer = Buffer.from(file.replace(/^base64:\/\//, ""), 'base64') + } else if (file.startsWith('http')) { + const http = await fetch(file) + const arrayBuffer = await http.arrayBuffer() + buffer = Buffer.from(arrayBuffer) + } else if (file.startsWith('file://')) { + buffer = fs.readFileSync(file.replace(/file:\/{2,3}/, '')) + } + const head = buffer.subarray(0, 7).toString() + let filePath + let duration = 0 + if (!head.includes('SILK')) { + const tmpPath = await saveTmp(buffer) + duration = await getDuration(tmpPath) + const res = await audioTrans(tmpPath) + filePath = res.silkFile + buffer = fs.readFileSync(filePath) + } else { + filePath = await saveTmp(buffer) + } + + const hash = createHash('md5') + hash.update(buffer.toString('binary'), 'binary') + const md5 = hash.digest('hex') + return { + elementType: 4, + pttElement: { + md5HexStr: md5, + fileSize: buffer.length, + fileName: md5 + '.amr', + filePath: filePath, + // waveAmplitudes: [36, 28, 68, 28, 84, 28], + waveAmplitudes: [ + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 + ], + duration: duration + } + } +} + +function audioTrans(tmpPath, samplingRate = '24000') { + return new Promise((resolve, reject) => { + const pcmFile = join(TMP_DIR, randomUUID({ disableEntropyCache: true })) + exec(`ffmpeg -y -i "${tmpPath}" -ar ${samplingRate} -ac 1 -f s16le "${pcmFile}"`, async () => { + fs.unlink(tmpPath, () => { }) + fs.access(pcmFile, fs.constants.F_OK, (err) => { + if (err) { + reject('音频转码失败, 请确保你的 ffmpeg 已正确安装') + } + }) + + const silkFile = join(TMP_DIR, randomUUID({ disableEntropyCache: true })) + try { + await pcmToSilk(pcmFile, silkFile, samplingRate) + } catch (error) { + reject('red发送语音暂不支持非win系统') + } + fs.unlink(pcmFile, () => { }) + + resolve({ + silkFile + }) + }) + }) +} + +function pcmToSilk(input, output, samplingRate) { + return new Promise((resolve, reject) => { + const args = ['-i', input, '-s', samplingRate, '-o', output] + const __filename = fileURLToPath(import.meta.url); + const __dirname = dirname(__filename); + const child = spawn(join(__dirname, './cli.exe'), args) + child.on('exit', () => { + fs.access(output, fs.constants.F_OK, (err) => { + if (err) { + reject('音频转码失败') + } + }) + // fs.stat(output, (err, stats) => { + // if (err) { + // console.error(err); + // return; + // } + // fs.truncate(output, stats.size - 1, err => { + // if (err) { + // console.error(err); + // return; + // } + // }); + // }); + resolve() + }) + }) +} + +function getDuration(file) { + return new Promise((resolve, reject) => { + exec(`ffmpeg -i ${file}`, function (err, stdout, stderr) { + const outStr = stderr.toString() + const regDuration = /Duration\: ([0-9\:\.]+),/ + const rs = regDuration.exec(outStr) + if (rs === null) { + reject("获取音频时长失败, 请确保你的 ffmpeg 已正确安装") + } else if (rs[1]) { + const time = rs[1] + const parts = time.split(":") + const seconds = (+parts[0]) * 3600 + (+parts[1]) * 60 + (+parts[2]) + const round = seconds.toString().split('.')[0] + resolve(+ round) + } + }) + }) +} + +async function saveTmp(data, ext = null) { + ext = ext ? '.' + ext : '' + const filename = randomUUID({ disableEntropyCache: true }) + ext + const tmpPath = resolve(TMP_DIR, filename) + fs.writeFileSync(tmpPath, data) + return tmpPath +} + +async function getNtPath(bot) { + let dataPath + try { + const buffer = fs.readFileSync('./plugins/ws-plugin/resources/common/cont/logo.png') + const blob = new Blob([buffer], { type: 'image/png' }) + const formData = new FormData() + formData.append('file', blob, '1.png') + const file = await bot.sendApi('POST', 'upload', formData) + fs.unlinkSync(file.ntFilePath) + const index = file.ntFilePath.indexOf('nt_data'); + dataPath = file.ntFilePath.slice(0, index + 'nt_data'.length); + } catch (error) { + return null + } + return dataPath +} + +async function uploadVideo(bot, file) { + let type = 'mp4' + if (file.match(/^base64:\/\//)) { + const buffer = Buffer.from(file.replace(/^base64:\/\//, ""), 'base64') + file = join(TMP_DIR, randomUUID({ disableEntropyCache: true }) + '.' + type) + fs.writeFileSync(file, buffer) + } else { + file = file.replace(/file:\/{2,3}/, '') + type = file.substring(file.lastIndexOf('.') + 1) + const Temp = join(TMP_DIR, randomUUID({ disableEntropyCache: true }) + '.' + type) + fs.copyFileSync(file, Temp) + file = Temp + } + const ntPath = await getNtPath(bot) + if (!ntPath) return + const now = new Date(); + const year = now.getFullYear(); + const month = now.getMonth() + 1; + const date = `${year}-${month.toString().padStart(2, '0')}`; + const video = await getVideoInfo(file) + + let oriPath = `${ntPath}/Video` + if (!fs.existsSync(oriPath)) fs.mkdirSync(oriPath) + oriPath = `${oriPath}/${date}` + if (!fs.existsSync(oriPath)) fs.mkdirSync(oriPath) + oriPath = `${oriPath}/Ori` + if (!fs.existsSync(oriPath)) fs.mkdirSync(oriPath) + oriPath = `${oriPath}/${video.videoMd5}.${type}` + + let thumbPath = `${ntPath}/Video/${date}/Thumb` + if (!fs.existsSync(thumbPath)) fs.mkdirSync(thumbPath) + thumbPath = `${thumbPath}/${video.videoMd5}_0.png` + + fs.copyFileSync(file, oriPath) + fs.unlinkSync(file) + const thumb = await getThumbInfo(oriPath, thumbPath) + return { + elementType: 5, + videoElement: { + filePath: oriPath, + fileName: video.videoMd5 + '.' + type, + videoMd5: video.videoMd5, + thumbMd5: thumb.thumbMd5, + fileTime: video.fileTime, + thumbSize: thumb.thumbSize, + fileSize: video.fileSize, + thumbWidth: thumb.thumbWidth, + thumbHeight: thumb.thumbHeight + } + } +} + +async function getVideoInfo(file) { + const fileTime = await getVideoTime(file) + const videoMd5 = await getVideoMd5(file) + const fileSize = fs.readFileSync(file).length + return { + fileTime, + videoMd5, + fileSize + } +} + +function getVideoMd5(file) { + return new Promise((resolve, reject) => { + const stream = fs.createReadStream(file); + const hash = createHash('md5'); + stream.on('data', chunk => { + hash.update(chunk); + }); + stream.on('end', () => { + const md5 = hash.digest('hex'); + resolve(md5) + }); + }) +} + +function getVideoTime(file) { + return new Promise((resolve, reject) => { + exec(`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${file}"`, (error, stdout, stderr) => { + if (error) { + reject('获取视频长度失败, 请确保你的 ffmpeg 已正确安装') + } + const durationInSeconds = parseInt(stdout); + resolve(durationInSeconds) + }); + }) +} + +async function getThumbInfo(file, thumbPath) { + + const tempPath = join(TMP_DIR, randomUUID({ disableEntropyCache: true }) + '.jpg') + + const { thumbMd5, thumbSize } = await extractThumbnail(file, tempPath); + + const { thumbWidth, thumbHeight } = getImageSize(tempPath); + + fs.copyFileSync(tempPath, thumbPath) + fs.unlinkSync(tempPath) + + return { thumbMd5, thumbWidth, thumbHeight, thumbSize }; +} + +function extractThumbnail(inputFile, outputFile) { + return new Promise((resolve, reject) => { + exec(`ffmpeg -i "${inputFile}" -ss 00:00:00.000 -vframes 1 -vf "scale=iw/3:ih/3" "${outputFile}" + `, async () => { + fs.access(outputFile, fs.constants.F_OK, (err) => { + if (err) { + reject('获取视频封面失败, 请确保你的 ffmpeg 已正确安装') + } + }) + + const buffer = fs.readFileSync(outputFile); + const hash = createHash('md5'); + hash.update(buffer); + resolve({ + thumbMd5: hash.digest('hex'), + thumbSize: buffer.length + }) + }) + }) +} + +function getImageSize(file) { + const buffer = fs.readFileSync(file); + const start = buffer.indexOf(Buffer.from([0xff, 0xc0])); + const thumbHeight = buffer.readUInt16BE(start + 5); + const thumbWidth = buffer.readUInt16BE(start + 7); + return { thumbWidth, thumbHeight }; +} + +async function uploadFile(file) { + let buffer, name, path = process.cwd() + '/plugins/ws-plugin/Temp/' + if (file.startsWith('http')) { + const http = await fetch(file) + const arrayBuffer = await http.arrayBuffer() + buffer = Buffer.from(arrayBuffer) + name = file.substring(file.lastIndexOf('/') + 1) + path = path + name + fs.writeFileSync(path, buffer); + } else if (file.startsWith('file://')) { + buffer = fs.readFileSync(file.replace(/file:\/{2,3}/, '')) + name = file.substring(file.lastIndexOf('/') + 1) + path = path + name + fs.copyFileSync(file, path) + } else if (Buffer.isBuffer(file)) { + buffer = file + name = 'buffer' + path = path + name + fs.writeFileSync(path, buffer); + } else { + buffer = fs.readFileSync(file) + name = file.substring(file.lastIndexOf('/') + 1) + path = path + name + fs.copyFileSync(file, path) + } + const size = buffer.length + const hash = createHash('md5'); + hash.update(buffer); + const md5 = hash.digest('hex') + return { + elementType: 3, + fileElement: { + fileMd5: md5, + fileName: name, + filePath: path, + fileSize: size, + } + } +} + +function getToken() { + let tokenPath + try { + if (os.platform() === 'win32') { + tokenPath = `${redPath}/config/chronocat.yml` + if (fs.existsSync(tokenPath)) { + const data = YAML.parse(fs.readFileSync(tokenPath, 'utf-8')) + for (const i of data?.servers || []) { + if (i.type === 'red') { + return i.token + } + } + logger.error('[ws-plugin] 请检查chronocat配置是否开启red服务') + return false + } else { + tokenPath = `${redPath}/RED_PROTOCOL_TOKEN` + return fs.readFileSync(tokenPath, 'utf-8') + } + } else { + logger.error('[ws-plugin] 非Windows系统请自行获取Token') + return false + } + } catch (error) { + logger.error('[ws-plugin] QQNT自动获取Token失败,请检查是否已安装Chronocat并尝试手动获取') + logger.error(error) + return false + } +} + +export { + uploadImg, + uploadAudio, + uploadVideo, + uploadFile, + getToken, + getNtPath, + roleMap, + redPath +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/model/tool.js b/Yunzai/plugins/ws-plugin/model/tool.js new file mode 100644 index 0000000000000000000000000000000000000000..0f03dc352d36e2c4aefa36caf48481743f24c650 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/model/tool.js @@ -0,0 +1,163 @@ +import _ from 'lodash' +import fs from 'fs' +import { Version } from '../components/index.js' + +async function CreateMusicShare(data) { + let appid, appname, appsign, style = 4; + switch (data.subType) { + case 'bilibili': + appid = 100951776, appname = 'tv.danmaku.bili', appsign = '7194d531cbe7960a22007b9f6bdaa38b'; + break; + case 'netease': + appid = 100495085, appname = "com.netease.cloudmusic", appsign = "da6b069da1e2982db3e386233f68d76d"; + break; + case 'kuwo': + appid = 100243533, appname = "cn.kuwo.player", appsign = "bf9ff4ffb4c558a34ee3fd52c223ebf5"; + break; + case 'kugou': + appid = 205141, appname = "com.kugou.android", appsign = "fe4a24d80fcf253a00676a808f62c2c6"; + break; + case 'migu': + appid = 1101053067, appname = "cmccwm.mobilemusic", appsign = "6cdc72a439cef99a3418d2a78aa28c73"; + break; + case 'qq': + default: + appid = 100497308, appname = "com.tencent.qqmusic", appsign = "cbd27cd7c861227d013a25b2d10f0799"; + break; + } + + var text = '', title = data.title, singer = data.content, prompt = '[分享]', jumpUrl = data.url, preview = data.image, musicUrl = data.voice; + + prompt = '[分享]' + title + '-' + singer; + + let recv_uin = 0; + let send_type = 0; + let recv_guild_id = 0; + + if (data.message_type === 'group') {//群聊 + recv_uin = data.group_id; + send_type = 1; + } else if (data.message_type === 'guild') {//频道 + recv_uin = Number(data.channel_id); + recv_guild_id = BigInt(data.guild_id); + send_type = 3; + } else if (data.message_type === 'private') {//私聊 + recv_uin = data.user_id; + send_type = 0; + } + + let body = { + 1: appid, + 2: 1, + 3: style, + 5: { + 1: 1, + 2: "0.0.0", + 3: appname, + 4: appsign, + }, + 6: text, + 10: send_type, + 11: recv_uin, + 12: { + 10: title, + 11: singer, + 12: prompt, + 13: jumpUrl, + 14: preview, + 16: musicUrl, + }, + 19: recv_guild_id + }; + return body; +} + +async function SendMusicShare(data) { + let core, bot + if (Version.isTrss) { + bot = Bot[data.bot_id] + core = bot?.core + } else { + bot = Bot + try { + core = (await import('oicq')).core + } catch (error) { + core = null + } + } + if (!core) { + const msg = [data.url] + if (data.message_type === 'group') {//群聊 + await bot?.pickGroup?.(data.group_id)?.sendMsg?.(msg) + } else if (data.message_type === 'private') {//私聊 + await bot?.pickFriend?.(data.user_id)?.sendMsg?.(msg) + } + return + } + try { + let body = await CreateMusicShare(data) + let payload = await bot.sendOidb("OidbSvc.0xb77_9", core.pb.encode(body)); + let result = core.pb.decode(payload); + if (result[3] != 0) { + if (data.message_type === 'group') {//群聊 + await bot?.pickGroup(data.group_id).sendMsg('歌曲分享失败:' + result[3]) + } else if (data.message_type === 'private') {//私聊 + await bot?.pickFriend(data.user_id).sendMsg('歌曲分享失败:' + result[3]) + } + // e.reply('歌曲分享失败:' + result[3], true); + } + } catch (error) { + const msg = [data.url] + if (data.message_type === 'group') {//群聊 + await bot?.pickGroup?.(data.group_id)?.sendMsg?.(msg) + } else if (data.message_type === 'private') {//私聊 + await bot?.pickFriend?.(data.user_id)?.sendMsg?.(msg) + } + return + } +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +const TMP_DIR = process.cwd() + '/plugins/ws-plugin/Temp' +if (!fs.existsSync(TMP_DIR)) fs.mkdirSync(TMP_DIR) + +const mimeTypes = { + '.html': 'text/html', + '.js': 'text/javascript', + '.css': 'text/css', + '.json': 'application/json', + '.png': 'image/png', + '.jpg': 'image/jpg', + '.gif': 'image/gif', + '.ico': 'image/x-icon', + '.txt': 'text/plain', + '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', +} + +function decodeHtml(html) { + var map = { + '&': '&', + '[': '[', + ']': ']', + ',': ',' + }; + + for (var key in map) { + const value = map[key]; + const regex = new RegExp(key, 'g'); + html = html.replace(regex, value); + } + return html; +} + + +export { + SendMusicShare, + sleep, + TMP_DIR, + mimeTypes, + decodeHtml +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/package.json b/Yunzai/plugins/ws-plugin/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b234f994384452a3628dd741f0813fbbc185fb63 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/package.json @@ -0,0 +1,12 @@ +{ + "name": "ws-plugin", + "version": "0.4.5", + "description": "Yunzai-Bot 的扩展插件", + "main": "index.js", + "type": "module", + "dependencies": { + "ws": "^8.13.0", + "express": "^4.18.2" + }, + "author": "xiaoye12123" +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/admin/imgs/bg.png b/Yunzai/plugins/ws-plugin/resources/admin/imgs/bg.png new file mode 100644 index 0000000000000000000000000000000000000000..da21f1560cbd766d902896475f8772194a2cfc49 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/admin/imgs/bg.png differ diff --git a/Yunzai/plugins/ws-plugin/resources/admin/imgs/cfg-right.jpg b/Yunzai/plugins/ws-plugin/resources/admin/imgs/cfg-right.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5bf552ad52eef0efd261e3efbf836ac303af058b Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/admin/imgs/cfg-right.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/admin/imgs/cfg-right.png b/Yunzai/plugins/ws-plugin/resources/admin/imgs/cfg-right.png new file mode 100644 index 0000000000000000000000000000000000000000..fcee36757d606d5c8f89b5dfe6431bfe8a87b519 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/admin/imgs/cfg-right.png differ diff --git a/Yunzai/plugins/ws-plugin/resources/admin/index.css b/Yunzai/plugins/ws-plugin/resources/admin/index.css new file mode 100644 index 0000000000000000000000000000000000000000..77a4b5dd95a9f1a41aa857375fe5d5d5cccf394b --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/admin/index.css @@ -0,0 +1,75 @@ +body { + transform: scale(1); + width: 660px; +} +.container { + background: url("./imgs/bg.png") #000144 left top repeat-y; + background-size: 700px auto; + width: 660px; +} +.head-box { + margin: 0 0 80px 0; +} +.cfg-box { + border-radius: 15px; + margin-top: 20px; + margin-bottom: 20px; + padding: 5px 15px; + overflow: hidden; + background: #f5f5f5; + box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.15); + position: relative; + background: rgba(35, 38, 57, 0.8); +} +.cfg-group { + color: #ceb78b; + font-size: 18px; + font-weight: bold; + padding: 10px 20px; +} +.cfg-li { + border-radius: 18px; + min-height: 36px; + position: relative; + overflow: hidden; + margin-bottom: 10px; + background: rgba(203, 196, 190, 0); +} +.cfg-line { + color: #4e5769; + line-height: 36px; + padding-left: 20px; + font-weight: bold; + border-radius: 16px; + box-shadow: 0 0 2px rgba(0, 0, 0, 0.5); + background: url("./imgs/cfg-right.jpg") right top #cbc4be no-repeat; + background-size: auto 36px; +} +.cfg-hint { + font-size: 12px; + font-weight: normal; + margin-top: 3px; + margin-bottom: -3px; +} +.cfg-status { + position: absolute; + top: 0; + right: 0; + height: 36px; + width: 160px; + text-align: center; + line-height: 36px; + font-size: 16px; + color: #495366; + font-weight: bold; + border-radius: 0 16px 16px 0; +} +.cfg-status.status-off { + color: #a95151; +} +.cfg-desc { + font-size: 12px; + color: #cbc4be; + margin: 5px 0 5px 20px; +} +/*# sourceMappingURL=index.css.map */ \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/admin/index.html b/Yunzai/plugins/ws-plugin/resources/admin/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4daa4f5b2759b16e919dd9b0a018aae1b856d81b --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/admin/index.html @@ -0,0 +1,42 @@ +{{extend defaultLayout}} +{{block 'css'}} + +{{/block}} +{{block 'main'}} + +
    +
    +
    ws管理面板
    +
    #ws设置
    +
    +
    +{{each schema cfgGroup}} +
    +
    {{cfgGroup.title}}
    +
      + {{each cfgGroup.cfg cfgItem cfgKey}} +
    • +
      + {{cfgItem.title}} + #ws设置{{cfgItem.key}} + {{if cfgItem.type==='num'}} {{cfgItem.def}}{{else}} 开启/关闭{{/if}} + + {{if cfgItem.type === 'num'}} +
      {{cfg[cfgKey]}}
      + {{else}} + {{if cfg[cfgKey]}} +
      已开启
      + {{else}} +
      已关闭
      + {{/if}} + {{/if}} +
      + {{if cfgItem.desc && cfgItem.showDesc!== false}} +
      {{cfgItem.desc}}
      + {{/if}} +
    • + {{/each}} +
    +
    +{{/each}} +{{/block}} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/admin/index.less b/Yunzai/plugins/ws-plugin/resources/admin/index.less new file mode 100644 index 0000000000000000000000000000000000000000..5c7acf7418f2539e46dbb32b84f05fe12fd0f5df --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/admin/index.less @@ -0,0 +1,89 @@ +body { + transform: scale(1); + width: 660px; +} + +.container { + background: url("./imgs/bg.png") #000144 left top no-repeat; + background-size: 700px auto; + width:660px; +} + +.head-box { + margin: 0 0 80px 0; +} + +.cfg-box { + border-radius: 15px; + margin-top: 20px; + margin-bottom: 20px; + padding: 5px 15px; + overflow: hidden; + background: #f5f5f5; + box-shadow: 0 5px 10px 0 rgb(0 0 0 / 15%); + position: relative; + background: rgba(35, 38, 57, .8); +} + + +.cfg-group { + color: #ceb78b; + font-size: 18px; + font-weight: bold; + padding: 10px 20px; +} + +.cfg-ul { + +} + +.cfg-li { + border-radius: 18px; + min-height: 36px; + position: relative; + overflow: hidden; + margin-bottom: 10px; + background: rgba(203, 196, 190, 0); +} + +.cfg-line { + color: #4e5769; + line-height: 36px; + padding-left: 20px; + font-weight: bold; + border-radius: 16px; + box-shadow: 0 0 2px rgba(0, 0, 0, 0.5); + background: url("./imgs/cfg-right.jpg") right top #cbc4be no-repeat; + background-size: auto 36px; +} + +.cfg-hint { + font-size: 12px; + font-weight: normal; + margin-top: 3px; + margin-bottom: -3px; +} + +.cfg-status { + position: absolute; + top: 0; + right: 0; + height: 36px; + width: 160px; + text-align: center; + line-height: 36px; + font-size: 16px; + color: #495366; + font-weight: bold; + border-radius: 0 16px 16px 0; +} + +.cfg-status.status-off { + color: #a95151; +} + +.cfg-desc { + font-size: 12px; + color: #cbc4be; + margin: 5px 0 5px 20px; +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/common/base.css b/Yunzai/plugins/ws-plugin/resources/common/base.css new file mode 100644 index 0000000000000000000000000000000000000000..991618559bde504c24bcc0ebf5ae43d4b6f69dfc --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/base.css @@ -0,0 +1,7 @@ +.font-ys { + font-family: Number, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; +} +.font-nzbz { + font-family: Number, "印品南征北战NZBZ体", NZBZ, PingFangSC-Medium, "PingFang SC", sans-serif; +} +/*# sourceMappingURL=base.css.map */ \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/common/base.less b/Yunzai/plugins/ws-plugin/resources/common/base.less new file mode 100644 index 0000000000000000000000000000000000000000..e065b8b7a8789fee992f2ad3c68ddfce4016d96b --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/base.less @@ -0,0 +1,7 @@ +.font-YS { + font-family: Number, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; +} + +.font-NZBZ { + font-family: Number, "印品南征北战NZBZ体", NZBZ, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-anemo.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-anemo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..985a7d4702b0a06990b94ac2fd639cc2bde30dec Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-anemo.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-cryo.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-cryo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cf4bd1d1b1dfe3e179e83ee68876211a53858bc8 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-cryo.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-dendro.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-dendro.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b900d286b75c2ab95733a60d61df6445f3a78087 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-dendro.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-electro.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-electro.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5dec7463c406d7576048439657ece9b396c2dd17 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-electro.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-geo.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-geo.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d68405f84992798104bfe6a062ba3b37df4972a7 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-geo.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-hydro.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-hydro.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cc262f74817355764243109dc3b33af28539fdd0 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-hydro.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/bg/bg-pyro.jpg b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-pyro.jpg new file mode 100644 index 0000000000000000000000000000000000000000..302d61293eacc3fdef8647baa5441d3decaaf594 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/bg/bg-pyro.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/common.css b/Yunzai/plugins/ws-plugin/resources/common/common.css new file mode 100644 index 0000000000000000000000000000000000000000..f21e5890be2b6622b9db263487f43ad3cd3f3279 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/common.css @@ -0,0 +1,458 @@ +@font-face { + font-family: 'Number'; + src: url("./font/tttgbnumber.woff") format('woff'), url("./font/tttgbnumber.ttf") format('truetype'); +} +@font-face { + font-family: 'NZBZ'; + src: url("./font/NZBZ.woff") format('woff'), url("./font/NZBZ.ttf") format('truetype'); +} +@font-face { + font-family: 'YS'; + src: url("./font/HYWH-65W.woff") format('woff'), url("./font/HYWH-65W.ttf") format('truetype'); +} +.font-YS { + font-family: Number, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; +} +.font-NZBZ { + font-family: Number, "印品南征北战NZBZ体", NZBZ, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; +} +* { + margin: 0; + padding: 0; + box-sizing: border-box; + -webkit-user-select: none; + user-select: none; +} +body { + font-size: 18px; + color: #1e1f20; + font-family: Number, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; + transform: scale(1.4); + transform-origin: 0 0; + width: 600px; +} +.container { + width: 600px; + padding: 20px 15px 10px 15px; + background-size: contain; +} +.head-box { + border-radius: 15px; + padding: 10px 20px; + position: relative; + color: #fff; + margin-top: 30px; +} +.head-box .title { + font-family: Number, "印品南征北战NZBZ体", NZBZ, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; + font-size: 36px; + text-shadow: 0 0 1px #000, 1px 1px 3px rgba(0, 0, 0, 0.9); +} +.head-box .title .label { + display: inline-block; + margin-left: 10px; +} +.head-box .genshin_logo { + position: absolute; + top: 1px; + right: 15px; + width: 97px; +} +.head-box .label { + font-size: 16px; + text-shadow: 0 0 1px #000, 1px 1px 3px rgba(0, 0, 0, 0.9); +} +.head-box .label span { + color: #d3bc8e; + padding: 0 2px; +} +.notice { + color: #888; + font-size: 12px; + text-align: right; + padding: 12px 5px 5px; +} +.notice-center { + color: #fff; + text-align: center; + margin-bottom: 10px; + text-shadow: 1px 1px 1px #333; +} +.copyright { + font-size: 14px; + text-align: center; + color: #fff; + position: relative; + padding-left: 10px; + text-shadow: 1px 1px 1px #000; + margin: 10px 0; +} +.copyright .version { + color: #d3bc8e; + display: inline-block; + padding: 0 3px; +} +/* */ +.cons { + display: inline-block; + vertical-align: middle; + padding: 0 5px; + border-radius: 4px; +} +.cons-0 { + background: #666; + color: #fff; +} +.cons-n0 { + background: #404949; + color: #fff; +} +.cons-1 { + background: #5cbac2; + color: #fff; +} +.cons-2 { + background: #339d61; + color: #fff; +} +.cons-3 { + background: #3e95b9; + color: #fff; +} +.cons-4 { + background: #3955b7; + color: #fff; +} +.cons-5 { + background: #531ba9cf; + color: #fff; +} +.cons-6 { + background: #ff5722; + color: #fff; +} +.cons2-0 { + border-radius: 4px; + background: #666; + color: #fff; +} +.cons2-1 { + border-radius: 4px; + background: #71b1b7; + color: #fff; +} +.cons2-2 { + border-radius: 4px; + background: #369961; + color: #fff; +} +.cons2-3 { + border-radius: 4px; + background: #4596b9; + color: #fff; +} +.cons2-4 { + border-radius: 4px; + background: #4560b9; + color: #fff; +} +.cons2-5 { + border-radius: 4px; + background: #531ba9cf; + color: #fff; +} +.cons2-6 { + border-radius: 4px; + background: #ff5722; + color: #fff; +} +/******** Fetter ********/ +.fetter { + width: 50px; + height: 50px; + display: inline-block; + background: url('./item/fetter.png'); + background-size: auto 100%; +} +.fetter.fetter1 { + background-position: 0% 0; +} +.fetter.fetter2 { + background-position: 11.11111111% 0; +} +.fetter.fetter3 { + background-position: 22.22222222% 0; +} +.fetter.fetter4 { + background-position: 33.33333333% 0; +} +.fetter.fetter5 { + background-position: 44.44444444% 0; +} +.fetter.fetter6 { + background-position: 55.55555556% 0; +} +.fetter.fetter7 { + background-position: 66.66666667% 0; +} +.fetter.fetter8 { + background-position: 77.77777778% 0; +} +.fetter.fetter9 { + background-position: 88.88888889% 0; +} +.fetter.fetter10 { + background-position: 100% 0; +} +/******** ELEM ********/ +.elem-hydro .talent-icon { + background-image: url("./bg/talent-hydro.png"); +} +.elem-hydro .elem-bg, +.hydro-bg { + background-image: url("./bg/bg-hydro.jpg"); +} +.elem-anemo .talent-icon { + background-image: url("./bg/talent-anemo.png"); +} +.elem-anemo .elem-bg, +.anemo-bg { + background-image: url("./bg/bg-anemo.jpg"); +} +.elem-cryo .talent-icon { + background-image: url("./bg/talent-cryo.png"); +} +.elem-cryo .elem-bg, +.cryo-bg { + background-image: url("./bg/bg-cryo.jpg"); +} +.elem-electro .talent-icon { + background-image: url("./bg/talent-electro.png"); +} +.elem-electro .elem-bg, +.electro-bg { + background-image: url("./bg/bg-electro.jpg"); +} +.elem-geo .talent-icon { + background-image: url("./bg/talent-geo.png"); +} +.elem-geo .elem-bg, +.geo-bg { + background-image: url("./bg/bg-geo.jpg"); +} +.elem-pyro .talent-icon { + background-image: url("./bg/talent-pyro.png"); +} +.elem-pyro .elem-bg, +.pyro-bg { + background-image: url("./bg/bg-pyro.jpg"); +} +.elem-dendro .talent-icon { + background-image: url("./bg/talent-dendro.png"); +} +.elem-dendro .elem-bg, +.dendro-bg { + background-image: url("./bg/bg-dendro.jpg"); +} +/* cont */ +.cont { + border-radius: 10px; + background: url("../common/cont/card-bg.png") top left repeat-x; + background-size: auto 100%; + margin: 5px 15px 5px 10px; + position: relative; + box-shadow: 0 0 1px 0 #ccc, 2px 2px 4px 0 rgba(50, 50, 50, 0.8); + overflow: hidden; + color: #fff; + font-size: 16px; +} +.cont-title { + background: rgba(0, 0, 0, 0.4); + box-shadow: 0 0 1px 0 #fff; + color: #d3bc8e; + padding: 10px 20px; + text-align: left; + border-radius: 10px 10px 0 0; +} +.cont-title span { + font-size: 12px; + color: #aaa; + margin-left: 10px; + font-weight: normal; +} +.cont-title.border-less { + background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); + box-shadow: none; + padding-bottom: 5px; +} +.cont-body { + padding: 10px 15px; + font-size: 12px; + background: rgba(0, 0, 0, 0.5); + box-shadow: 0 0 1px 0 #fff; + font-weight: normal; +} +.cont-footer { + padding: 10px 15px; + font-size: 12px; + background: rgba(0, 0, 0, 0.5); + font-weight: normal; +} +.cont > ul.cont-msg { + display: block; + padding: 5px 10px; + background: rgba(0, 0, 0, 0.5); +} +ul.cont-msg, +.cont-footer ul { + padding-left: 15px; +} +ul.cont-msg li, +.cont-footer ul li { + margin: 5px 0; + margin-left: 15px; +} +ul.cont-msg li strong, +.cont-footer ul li strong { + font-weight: normal; + margin: 0 2px; + color: #d3bc8e; +} +.cont-table { + display: table; + width: 100%; +} +.cont-table .tr { + display: table-row; +} +.cont-table .tr:nth-child(even) { + background: rgba(0, 0, 0, 0.4); +} +.cont-table .tr:nth-child(odd) { + background: rgba(50, 50, 50, 0.4); +} +.cont-table .tr > div, +.cont-table .tr > td { + display: table-cell; + box-shadow: 0 0 1px 0 #fff; +} +.cont-table .tr > div.value-full { + display: table; + width: 200%; +} +.cont-table .tr > div.value-none { + box-shadow: none; +} +.cont-table .thead { + text-align: center; +} +.cont-table .thead > div, +.cont-table .thead > td { + color: #d3bc8e; + background: rgba(0, 0, 0, 0.4); + line-height: 40px; + height: 40px; +} +.cont-table .title, +.cont-table .th { + color: #d3bc8e; + padding-right: 15px; + text-align: right; + background: rgba(0, 0, 0, 0.4); + min-width: 100px; + vertical-align: middle; +} +.logo { + font-size: 18px; + text-align: center; + color: #fff; + margin: 20px 0 10px 0; +} +/* item-icon */ +.item-icon { + width: 100%; + height: 100%; + border-radius: 4px; + position: relative; + overflow: hidden; +} +.item-icon .img { + width: 100%; + height: 100%; + display: block; + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} +.item-icon.artis .img { + width: 84%; + height: 84%; + margin: 8%; +} +.item-icon.star1 { + background-image: url("../common/item/bg1.png"); +} +.item-icon.opacity-bg.star1 { + background-image: url("../common/item/bg1-o.png"); +} +.item-icon.star2 { + background-image: url("../common/item/bg2.png"); +} +.item-icon.opacity-bg.star2 { + background-image: url("../common/item/bg2-o.png"); +} +.item-icon.star3 { + background-image: url("../common/item/bg3.png"); +} +.item-icon.opacity-bg.star3 { + background-image: url("../common/item/bg3-o.png"); +} +.item-icon.star4 { + background-image: url("../common/item/bg4.png"); +} +.item-icon.opacity-bg.star4 { + background-image: url("../common/item/bg4-o.png"); +} +.item-icon.star5 { + background-image: url("../common/item/bg5.png"); +} +.item-icon.opacity-bg.star5 { + background-image: url("../common/item/bg5-o.png"); +} +.item-icon.star-w { + background: #fff; +} +.item-list { + display: flex; +} +.item-list .item-card { + width: 70px; + background: #e7e5d9; +} +.item-list .item-icon { + border-bottom-left-radius: 0; + border-bottom-right-radius: 12px; +} +.item-list .item-title { + color: #222; + font-size: 13px; + text-align: center; + padding: 2px; + white-space: nowrap; + overflow: hidden; +} +.item-list .item-icon { + height: initial; +} +.item-list .item-badge { + position: absolute; + display: block; + left: 0; + top: 0; + background: rgba(0, 0, 0, 0.6); + font-size: 12px; + color: #fff; + padding: 4px 5px 3px; + border-radius: 0 0 6px 0; +} +/*# sourceMappingURL=common.css.map */ \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/common/common.less b/Yunzai/plugins/ws-plugin/resources/common/common.less new file mode 100644 index 0000000000000000000000000000000000000000..84fca6b82febbac6516a40b22fb5e0ad9ba73434 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/common.less @@ -0,0 +1,394 @@ +.font(@name, @file) { + @font-face { + font-family: @name; + src: url("./font/@{file}.woff") format('woff'), url("./font/@{file}.ttf") format('truetype'); + } +} + +.font('Number', 'tttgbnumber'); +.font('NZBZ', 'NZBZ'); +.font('YS', 'HYWH-65W'); + +@import "base.less"; + +* { + margin: 0; + padding: 0; + box-sizing: border-box; + -webkit-user-select: none; + user-select: none; +} + +body { + font-size: 18px; + color: #1e1f20; + font-family: Number, "汉仪文黑-65W", YS, PingFangSC-Medium, "PingFang SC", sans-serif; + transform: scale(1.4); + transform-origin: 0 0; + width: 600px; +} + +.container { + width: 600px; + padding: 20px 15px 10px 15px; + background-size: contain; +} + + +.head-box { + border-radius: 15px; + padding: 10px 20px; + position: relative; + color: #fff; + margin-top: 30px; + + .title { + .font-NZBZ; + font-size: 36px; + text-shadow: 0 0 1px #000, 1px 1px 3px rgba(0, 0, 0, .9); + + .label { + display: inline-block; + margin-left: 10px; + } + } + + .genshin_logo { + position: absolute; + top: 1px; + right: 15px; + width: 97px; + } + + .label { + font-size: 16px; + text-shadow: 0 0 1px #000, 1px 1px 3px rgba(0, 0, 0, .9); + + span { + color: #d3bc8e; + padding: 0 2px; + } + } +} + + +.notice { + color: #888; + font-size: 12px; + text-align: right; + padding: 12px 5px 5px; +} + +.notice-center { + color: #fff; + text-align: center; + margin-bottom: 10px; + text-shadow: 1px 1px 1px #333; +} + +.copyright { + font-size: 14px; + text-align: center; + color: #fff; + position: relative; + padding-left: 10px; + text-shadow: 1px 1px 1px #000; + margin: 10px 0; + + .version { + color: #d3bc8e; + display: inline-block; + padding: 0 3px; + } +} + + +/* */ + +.cons { + display: inline-block; + vertical-align: middle; + padding: 0 5px; + border-radius: 4px; +} + + +.cons(@idx, @bg, @color:#fff) { + .cons-@{idx} { + background: @bg; + color: @color; + } +} + +.cons(0, #666); +.cons(n0, #404949); +.cons(1, #5cbac2); +.cons(2, #339d61); +.cons(3, #3e95b9); +.cons(4, #3955b7); +.cons(5, #531ba9cf); +.cons(6, #ff5722); + +.cons2(@idx, @bg, @color:#fff) { + .cons2-@{idx} { + border-radius: 4px; + background: @bg; + color: @color; + } +} + +.cons2(0, #666); +.cons2(1, #71b1b7); +.cons2(2, #369961); +.cons2(3, #4596b9); +.cons2(4, #4560b9); +.cons2(5, #531ba9cf); +.cons2(6, #ff5722); + +/******** Fetter ********/ + +.fetter { + width: 50px; + height: 50px; + display: inline-block; + background: url('./item/fetter.png'); + background-size: auto 100%; + @fetters: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10; + each(@fetters, { + &.fetter@{value} { + background-position: (-100%/9)+(100%/9)*@value 0; + } + }) +} + +/******** ELEM ********/ + +@elems: hydro, anemo, cryo, electro, geo, pyro, dendro; + +each(@elems, { + .elem-@{value} .talent-icon { + background-image: url("./bg/talent-@{value}.png"); + } + + .elem-@{value} .elem-bg, + .@{value}-bg { + background-image: url("./bg/bg-@{value}.jpg"); + } +}) + + +/* cont */ + +.cont { + border-radius: 10px; + background: url("../common/cont/card-bg.png") top left repeat-x; + background-size: auto 100%; + // backdrop-filter: blur(3px); + margin: 5px 15px 5px 10px; + position: relative; + box-shadow: 0 0 1px 0 #ccc, 2px 2px 4px 0 rgba(50, 50, 50, .8); + overflow: hidden; + color: #fff; + font-size: 16px; +} + + +.cont-title { + background: rgba(0, 0, 0, .4); + box-shadow: 0 0 1px 0 #fff; + color: #d3bc8e; + padding: 10px 20px; + text-align: left; + border-radius: 10px 10px 0 0; + + span { + font-size: 12px; + color: #aaa; + margin-left: 10px; + font-weight: normal; + } + + &.border-less { + background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, 0)); + box-shadow: none; + padding-bottom: 5px; + } +} + +.cont-body { + padding: 10px 15px; + font-size: 12px; + background: rgba(0, 0, 0, 0.5); + box-shadow: 0 0 1px 0 #fff; + font-weight: normal; +} + + +.cont-footer { + padding: 10px 15px; + font-size: 12px; + background: rgba(0, 0, 0, 0.5); + font-weight: normal; +} + +.cont > ul.cont-msg { + display: block; + padding: 5px 10px; + background: rgba(0, 0, 0, 0.5); +} + +ul.cont-msg, .cont-footer ul { + padding-left: 15px; + + li { + margin: 5px 0; + margin-left: 15px; + + strong { + font-weight: normal; + margin: 0 2px; + color: #d3bc8e; + } + } +} + +.cont-table { + display: table; + width: 100%; +} + +.cont-table .tr { + display: table-row; +} + +.cont-table .tr:nth-child(even) { + background: rgba(0, 0, 0, .4); +} + +.cont-table .tr:nth-child(odd) { + background: rgba(50, 50, 50, .4); +} + +.cont-table .tr > div, +.cont-table .tr > td { + display: table-cell; + box-shadow: 0 0 1px 0 #fff; +} + +.cont-table .tr > div.value-full { + display: table; + width: 200%; +} + +.cont-table .tr > div.value-none { + box-shadow: none; +} + +.cont-table .thead { + text-align: center; +} + +.cont-table .thead > div, +.cont-table .thead > td { + color: #d3bc8e; + background: rgba(0, 0, 0, .4); + line-height: 40px; + height: 40px; +} + + +.cont-table .title, +.cont-table .th { + color: #d3bc8e; + padding-right: 15px; + text-align: right; + background: rgba(0, 0, 0, .4); + min-width: 100px; + vertical-align: middle; +} + +.logo { + font-size: 18px; + text-align: center; + color: #fff; + margin: 20px 0 10px 0; +} + +/* item-icon */ +.item-icon { + width: 100%; + height: 100%; + border-radius: 4px; + position: relative; + overflow: hidden; + + .img { + width: 100%; + height: 100%; + display: block; + background-size: contain; + background-position: center; + background-repeat: no-repeat; + } + + &.artis { + .img { + width: 84%; + height: 84%; + margin: 8%; + } + } + + @stars: 1, 2, 3, 4, 5; + each(@stars, { + &.star@{value} { + background-image: url("../common/item/bg@{value}.png"); + } + &.opacity-bg.star@{value} { + background-image: url("../common/item/bg@{value}-o.png"); + } + }) + + &.star-w { + background: #fff; + } +} + +.item-list { + display: flex; + + .item-card { + width: 70px; + background: #e7e5d9; + } + + .item-icon { + border-bottom-left-radius: 0; + border-bottom-right-radius: 12px; + } + + .item-title { + color: #222; + font-size: 13px; + text-align: center; + padding: 2px; + white-space: nowrap; + overflow: hidden; + } + + .item-icon { + height: initial; + } + + .item-badge { + position: absolute; + display: block; + left: 0; + top: 0; + background: rgba(0, 0, 0, 0.6); + font-size: 12px; + color: #fff; + padding: 4px 5px 3px; + border-radius: 0 0 6px 0; + } +} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/common/cont/card-bg.png b/Yunzai/plugins/ws-plugin/resources/common/cont/card-bg.png new file mode 100644 index 0000000000000000000000000000000000000000..036d416e692030f7c0a8b07d30c5da5c4598dece Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/cont/card-bg.png differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/cont/logo.png b/Yunzai/plugins/ws-plugin/resources/common/cont/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..a8cb922f6a995d0c9bff6229bae057ffcf6b7168 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/cont/logo.png differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.ttf b/Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.ttf new file mode 100644 index 0000000000000000000000000000000000000000..b74b5b2421d39d1f1d68f3f54784946cddcd7681 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a93c5d18d5feb4c8f9c2c6697742c1c54b41a2c73554f7b668c52c6e788c34d0 +size 3293520 diff --git a/Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.woff b/Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.woff new file mode 100644 index 0000000000000000000000000000000000000000..4183b592b014c6f5e72d40a0310302fed81b671d --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/font/HYWH-65W.woff @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b7147f05859d906bd787cf809d9796621d81294401f5efd3199e043a410f5fd +size 2111996 diff --git a/Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.ttf b/Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.ttf new file mode 100644 index 0000000000000000000000000000000000000000..bb9177e084615ff0da0eecc50b3ea6d17bc0e5ae --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26e130f37e0f59f8d0eaa7c96662de0545595bf04675c01e037e49de84de6bc3 +size 1502040 diff --git a/Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.woff b/Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.woff new file mode 100644 index 0000000000000000000000000000000000000000..edf38df55bf3bf57107e037b7360ed2a4afb5c97 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/font/NZBZ.woff differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/font/tttgbnumber.ttf b/Yunzai/plugins/ws-plugin/resources/common/font/tttgbnumber.ttf new file mode 100644 index 0000000000000000000000000000000000000000..89a392f7d123ec88caebb16e95ce0f35cfdf83bc Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/font/tttgbnumber.ttf differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/font/tttgbnumber.woff b/Yunzai/plugins/ws-plugin/resources/common/font/tttgbnumber.woff new file mode 100644 index 0000000000000000000000000000000000000000..b35ab09736cbdcc3f06848bab80b3c210fc56a57 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/common/font/tttgbnumber.woff differ diff --git "a/Yunzai/plugins/ws-plugin/resources/common/font/\345\215\216\346\226\207\344\270\255\345\256\213.TTF" "b/Yunzai/plugins/ws-plugin/resources/common/font/\345\215\216\346\226\207\344\270\255\345\256\213.TTF" new file mode 100644 index 0000000000000000000000000000000000000000..2ddb8b239f192cc4fe99fd3047f7423989d64f56 Binary files /dev/null and "b/Yunzai/plugins/ws-plugin/resources/common/font/\345\215\216\346\226\207\344\270\255\345\256\213.TTF" differ diff --git a/Yunzai/plugins/ws-plugin/resources/common/layout/default.html b/Yunzai/plugins/ws-plugin/resources/common/layout/default.html new file mode 100644 index 0000000000000000000000000000000000000000..d034f61aa8767ab2c01a82933b7af95770e0e211 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/layout/default.html @@ -0,0 +1,21 @@ + + + + + + + + + + + miao-plugin + {{block 'css'}} + {{/block}} + + +
    + {{block 'main'}}{{/block}} + +
    + + \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/common/layout/elem.html b/Yunzai/plugins/ws-plugin/resources/common/layout/elem.html new file mode 100644 index 0000000000000000000000000000000000000000..16ccaede617f22dccc1c487db65708ca4c921931 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/common/layout/elem.html @@ -0,0 +1,21 @@ + + + + + + + + + + + ws-plugin + {{block 'css'}} + {{/block}} + + +
    + {{block 'main'}}{{/block}} + +
    + + \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/help/icon.png b/Yunzai/plugins/ws-plugin/resources/help/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..04861e4f96fd0873871cb926452e78dc9dcf8084 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5028d65a0cf0b741406f0e5f9cd71be40e6065d25bc28bf50aea227a0f6a866f +size 1262272 diff --git a/Yunzai/plugins/ws-plugin/resources/help/imgs/bg.jpg b/Yunzai/plugins/ws-plugin/resources/help/imgs/bg.jpg new file mode 100644 index 0000000000000000000000000000000000000000..da21f1560cbd766d902896475f8772194a2cfc49 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/help/imgs/bg.jpg differ diff --git a/Yunzai/plugins/ws-plugin/resources/help/imgs/config.js b/Yunzai/plugins/ws-plugin/resources/help/imgs/config.js new file mode 100644 index 0000000000000000000000000000000000000000..fe2ba525fcef6fd3f7fdcb03379b8b0a3318b07d --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/imgs/config.js @@ -0,0 +1,24 @@ +export const style = { + // 主文字颜色 + fontColor: '#ceb78b', + // 主文字阴影: 横向距离 垂直距离 阴影大小 阴影颜色 + // fontShadow: '0px 0px 1px rgba(6, 21, 31, .9)', + fontShadow: 'none', + // 描述文字颜色 + descColor: '#eee', + + /* 面板整体底色,会叠加在标题栏及帮助行之下,方便整体帮助有一个基础底色 + * 若无需此项可将rgba最后一位置为0即为完全透明 + * 注意若综合透明度较低,或颜色与主文字颜色过近或太透明可能导致阅读困难 */ + contBgColor: 'rgba(6, 21, 31, .5)', + + // 面板底图毛玻璃效果,数字越大越模糊,0-10 ,可为小数 + contBgBlur: 3, + + // 板块标题栏底色 + headerBgColor: 'rgba(6, 21, 31, .4)', + // 帮助奇数行底色 + rowBgColor1: 'rgba(6, 21, 31, .2)', + // 帮助偶数行底色 + rowBgColor2: 'rgba(6, 21, 31, .35)' +} diff --git a/Yunzai/plugins/ws-plugin/resources/help/imgs/main.png b/Yunzai/plugins/ws-plugin/resources/help/imgs/main.png new file mode 100644 index 0000000000000000000000000000000000000000..da21f1560cbd766d902896475f8772194a2cfc49 Binary files /dev/null and b/Yunzai/plugins/ws-plugin/resources/help/imgs/main.png differ diff --git a/Yunzai/plugins/ws-plugin/resources/help/index.css b/Yunzai/plugins/ws-plugin/resources/help/index.css new file mode 100644 index 0000000000000000000000000000000000000000..b0db1f8f12bd4945a7d48885ca8e5dc00de36c29 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/index.css @@ -0,0 +1,83 @@ +body { + transform: scale(1); + width: 830px; + background: url("../common/theme/bg-01.jpg"); +} +.container { + background: url(../common/theme/main-01.png) top left no-repeat; + background-size: 100% auto; + width: 830px; +} +.head-box { + margin: 60px 0 0 0; + padding-bottom: 0; +} +.head-box .title { + font-size: 50px; +} +.cont-box { + border-radius: 15px; + margin-top: 20px; + margin-bottom: 20px; + overflow: hidden; + box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.15); + position: relative; +} +.help-group { + font-size: 18px; + font-weight: bold; + padding: 15px 15px 10px 20px; +} +.help-table { + text-align: center; + border-collapse: collapse; + margin: 0; + border-radius: 0 0 10px 10px; + display: table; + overflow: hidden; + width: 100%; + color: #fff; +} +.help-table .tr { + display: table-row; +} +.help-table .td, +.help-table .th { + font-size: 14px; + display: table-cell; + box-shadow: 0 0 1px 0 #888 inset; + padding: 12px 0 12px 50px; + line-height: 24px; + position: relative; + text-align: left; +} +.help-table .tr:last-child .td { + padding-bottom: 12px; +} +.help-table .th { + background: rgba(34, 41, 51, 0.5); +} +.help-icon { + width: 40px; + height: 40px; + display: block; + position: absolute; + background: url("icon.png") 0 0 no-repeat; + background-size: 500px auto; + border-radius: 5px; + left: 6px; + top: 12px; + transform: scale(0.85); +} +.help-title { + display: block; + color: #d3bc8e; + font-size: 16px; + line-height: 24px; +} +.help-desc { + display: block; + font-size: 13px; + line-height: 18px; +} +/*# sourceMappingURL=index.css.map */ \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/help/index.html b/Yunzai/plugins/ws-plugin/resources/help/index.html new file mode 100644 index 0000000000000000000000000000000000000000..cac6d03f219d3ed47e71a9d0e9a5502254ba66a9 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/index.html @@ -0,0 +1,44 @@ +{{extend defaultLayout}} + +{{block 'css'}} + +<% style = style.replace(/{{_res_path}}/g, _res_path) %> +{{@style}} +{{/block}} + +{{block 'main'}} + +
    +
    +
    {{helpCfg.title||"使用帮助"}}
    +
    {{helpCfg.subTitle || "Yunzai-Bot & Miao-Plugin"}}
    +
    +
    + +{{each helpGroup group}} +{{set len = group?.list?.length || 0 }} +
    +
    {{group.group}}
    + {{if len > 0}} +
    +
    + {{each group.list help idx}} +
    + + {{help.title}} + {{help.desc}} +
    + {{if idx%colCount === colCount-1 && idx>0 && idx< len-1}} +
    +
    + {{/if}} + {{/each}} + <% for(let i=(len-1)%colCount; i< colCount-1 ; i++){ %> +
    + <% } %> +
    +
    + {{/if}} +
    +{{/each}} +{{/block}} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/help/index.less b/Yunzai/plugins/ws-plugin/resources/help/index.less new file mode 100644 index 0000000000000000000000000000000000000000..3ea3dad8a06ee5c94f963bd6c0d441d74ebc5ffc --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/index.less @@ -0,0 +1,96 @@ +body { + transform: scale(1); + width: 830px; + background: url("../common/theme/bg-01.jpg"); +} + +.container { + background: url(../common/theme/main-01.png) top left no-repeat; + background-size: 100% auto; + width: 830px; +} + +.head-box { + margin: 60px 0 0 0; + padding-bottom: 0; +} + +.head-box .title { + font-size: 50px; +} + +.cont-box { + border-radius: 15px; + margin-top: 20px; + margin-bottom: 20px; + overflow: hidden; + box-shadow: 0 5px 10px 0 rgb(0 0 0 / 15%); + position: relative; +} + +.help-group { + font-size: 18px; + font-weight: bold; + padding: 15px 15px 10px 20px; +} + +.help-table { + text-align: center; + border-collapse: collapse; + margin: 0; + border-radius: 0 0 10px 10px; + display: table; + overflow: hidden; + width: 100%; + color: #fff; +} + +.help-table .tr { + display: table-row; +} + +.help-table .td, +.help-table .th { + font-size: 14px; + display: table-cell; + box-shadow: 0 0 1px 0 #888 inset; + padding: 12px 0 12px 50px; + line-height: 24px; + position: relative; + text-align: left; +} + +.help-table .tr:last-child .td { + padding-bottom: 12px; +} + +.help-table .th { + background: rgba(34, 41, 51, .5) +} + +.help-icon { + width: 40px; + height: 40px; + display: block; + position: absolute; + background: url("icon.png") 0 0 no-repeat; + background-size: 500px auto; + border-radius: 5px; + left: 6px; + top: 12px; + transform: scale(0.85); +} + +.help-title { + display: block; + color: #d3bc8e; + font-size: 16px; + line-height: 24px; +} + +.help-desc { + display: block; + font-size: 13px; + line-height: 18px; +} + diff --git a/Yunzai/plugins/ws-plugin/resources/help/version-info.css b/Yunzai/plugins/ws-plugin/resources/help/version-info.css new file mode 100644 index 0000000000000000000000000000000000000000..1ae34aaf5fce596dee49433256e8ce65f0275df5 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/version-info.css @@ -0,0 +1,83 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; + user-select: none; +} +body { + font-size: 18px; + color: #1e1f20; + transform: scale(1.3); + transform-origin: 0 0; + width: 600px; +} +.container { + width: 600px; + padding: 10px 0 10px 0; + background-size: 100% 100%; +} +.log-cont { + background-size: cover; + margin: 5px 15px 5px 10px; + border-radius: 10px; +} +.log-cont .cont { + margin: 0; +} +.log-cont .cont-title { + font-size: 16px; + padding: 10px 20px 6px; +} +.log-cont .cont-title.current-version { + font-size: 20px; +} +.log-cont ul { + font-size: 14px; + padding-left: 20px; +} +.log-cont ul li { + margin: 3px 0; +} +.log-cont ul.sub-log-ul li { + margin: 1px 0; +} +.log-cont .cmd { + color: #d3bc8e; + display: inline-block; + border-radius: 3px; + background: rgba(0, 0, 0, 0.5); + padding: 0 3px; + margin: 1px 2px; +} +.log-cont .strong { + color: #24d5cd; +} +.log-cont .new { + display: inline-block; + width: 18px; + margin: 0 -3px 0 1px; +} +.log-cont .new:before { + content: "NEW"; + display: inline-block; + transform: scale(0.6); + transform-origin: 0 0; + color: #d3bc8e; + white-space: nowrap; +} +.dev-cont { + background: none; +} +.dev-cont .cont-title { + background: rgba(0, 0, 0, 0.7); +} +.dev-cont .cont-body { + background: rgba(0, 0, 0, 0.5); +} +.dev-cont .cont-body.dev-info { + background: rgba(0, 0, 0, 0.2); +} +.dev-cont .strong { + font-size: 15px; +} +/*# sourceMappingURL=version-info.css.map */ \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/help/version-info.html b/Yunzai/plugins/ws-plugin/resources/help/version-info.html new file mode 100644 index 0000000000000000000000000000000000000000..b8a780e49df478ec08f35c5ae7a13eefafc8ef36 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/version-info.html @@ -0,0 +1,37 @@ +{{extend elemLayout}} + +{{block 'css'}} + +{{/block}} + +{{block 'main'}} +{{each changelogs ds idx}} +
    + {{set v = ds.version }} + {{set isDev = v[v.length-1] === 'v'}} +
    + {{if idx === 0 }} +
    当前版本 {{v}}
    + {{else}} +
    {{name || 'ws'}}版本 {{v}}
    + {{/if}} +
    +
      + {{each ds.logs log}} +
    • +

      {{@log.title}}

      + {{if log.logs.length > 0}} +
        + {{each log.logs ls}} +
      • {{@ls}}
      • + {{/each}} +
      + {{/if}} +
    • + {{/each}} +
    +
    +
    +
    +{{/each}} +{{/block}} \ No newline at end of file diff --git a/Yunzai/plugins/ws-plugin/resources/help/version-info.less b/Yunzai/plugins/ws-plugin/resources/help/version-info.less new file mode 100644 index 0000000000000000000000000000000000000000..98483650f553dbee40909febcbe34bd956c0bc03 --- /dev/null +++ b/Yunzai/plugins/ws-plugin/resources/help/version-info.less @@ -0,0 +1,110 @@ +.linear-bg(@color) { + background-image: linear-gradient(to right, @color, @color 80%, fade(@color, 0) 100%); +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; + user-select: none; +} + +body { + font-size: 18px; + color: #1e1f20; + transform: scale(1.3); + transform-origin: 0 0; + width: 600px; +} + +.container { + width: 600px; + padding: 10px 0 10px 0; + background-size: 100% 100%; + +} + +.log-cont { + background-size: cover; + margin: 5px 15px 5px 10px; + border-radius: 10px; + + .cont { + margin: 0; + } + + .cont-title { + font-size: 16px; + padding: 10px 20px 6px; + + &.current-version { + font-size: 20px; + } + } + + .cont-body { + } + + ul { + font-size: 14px; + padding-left: 20px; + + li { + margin: 3px 0; + } + + &.sub-log-ul { + li { + margin: 1px 0; + } + } + } + + .cmd { + color: #d3bc8e; + display: inline-block; + border-radius: 3px; + background: rgba(0, 0, 0, 0.5); + padding: 0 3px; + margin: 1px 2px; + } + + .strong { + color: #24d5cd; + } + + .new { + display: inline-block; + width: 18px; + margin: 0 -3px 0 1px; + } + + .new:before { + content: "NEW"; + display: inline-block; + transform: scale(0.6); + transform-origin: 0 0; + color: #d3bc8e; + white-space: nowrap; + } +} + +.dev-cont { + background: none; + + .cont-title { + background: rgba(0, 0, 0, .7); + } + + .cont-body { + background: rgba(0, 0, 0, .5); + + &.dev-info { + background: rgba(0, 0, 0, .2); + } + } + + .strong { + font-size: 15px; + } +} \ No newline at end of file diff --git a/Yunzai/pnpm-workspace.yaml b/Yunzai/pnpm-workspace.yaml new file mode 100644 index 0000000000000000000000000000000000000000..19826ecded71990b3c788bd3133b96263a1128c4 --- /dev/null +++ b/Yunzai/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +packages: + - 'plugins/**' diff --git a/Yunzai/renderers/.gitignore b/Yunzai/renderers/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6ecbe4241031df2896a07b42ef90ff1abc3a882e --- /dev/null +++ b/Yunzai/renderers/.gitignore @@ -0,0 +1,6 @@ +* +!.gitignore + +!puppeteer +!puppeteer/** +puppeteer/config.yaml \ No newline at end of file diff --git a/Yunzai/renderers/puppeteer/config_default.yaml b/Yunzai/renderers/puppeteer/config_default.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7737a551f5e205addaf87d600bf97076ee4a7d59 --- /dev/null +++ b/Yunzai/renderers/puppeteer/config_default.yaml @@ -0,0 +1,23 @@ +# 如需自定义,复制此文件为 config.yaml 进行配置 +# 更新配置后需要重启 + +# chromium 地址,可填写系统的edge/chromium路径,例如(根据实际情况调整): +# chromiumPath: C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe +chromiumPath: + +# puppeteer websocket 地址。连接单独存在的 chromium。 +# puppeteerWS: 'ws://browserless:3000' +puppeteerWS: + +# headless +headless: "new" + +# puppeteer启动args,注意args的--前缀 +args: + - --disable-gpu + - --disable-setuid-sandbox + - --no-sandbox + - --no-zygote + +# puppeteer截图超时时间 +puppeteerTimeout: diff --git a/Yunzai/renderers/puppeteer/index.js b/Yunzai/renderers/puppeteer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1684f12126ed474ceab8ceba5920159b9116ae23 --- /dev/null +++ b/Yunzai/renderers/puppeteer/index.js @@ -0,0 +1,14 @@ +import Puppeteer from './lib/puppeteer.js' + +/** + * + * @param config 本地config.yaml的配置内容 + * @returns renderer 渲染器对象 + * @returns renderer.id 渲染器ID,对应renderer中选择的id + * @returns renderer.type 渲染类型,保留字段,暂时支持image + * @returns renderer.render 渲染入口 + */ +export default function (config) { + // TODO Puppeteer待简化重构 + return new Puppeteer(config) +} \ No newline at end of file diff --git a/Yunzai/renderers/puppeteer/lib/puppeteer.js b/Yunzai/renderers/puppeteer/lib/puppeteer.js new file mode 100644 index 0000000000000000000000000000000000000000..9daf954b99dcf88cd60a8e3ea718e8f18495b7c6 --- /dev/null +++ b/Yunzai/renderers/puppeteer/lib/puppeteer.js @@ -0,0 +1,321 @@ +import Renderer from '../../../lib/renderer/Renderer.js' +import os from 'node:os' +import lodash from 'lodash' +import puppeteer from 'puppeteer' +// 暂时保留对原config的兼容 +import cfg from '../../../lib/config/config.js' +import { Data } from '#miao' + +const _path = process.cwd() +// mac地址 +let mac = '' +// 超时计时器 +let overtimeList = [] + +export default class Puppeteer extends Renderer { + constructor (config) { + super({ + id: 'puppeteer', + type: 'image', + render: 'screenshot' + }) + this.browser = false + this.lock = false + this.shoting = [] + /** 截图数达到时重启浏览器 避免生成速度越来越慢 */ + this.restartNum = 100 + /** 截图次数 */ + this.renderNum = 0 + this.config = { + headless: Data.def(config.headless, 'new'), + args: Data.def(config.args, [ + '--disable-gpu', + '--disable-setuid-sandbox', + '--no-sandbox', + '--no-zygote' + ]) + } + if (config.chromiumPath || cfg?.bot?.chromium_path) { + /** chromium其他路径 */ + this.config.executablePath = config.chromiumPath || cfg?.bot?.chromium_path + } + if (config.puppeteerWS || cfg?.bot?.puppeteer_ws) { + /** chromium其他路径 */ + this.config.wsEndpoint = config.puppeteerWS || cfg?.bot?.puppeteer_ws + } + /** puppeteer超时超时时间 */ + this.puppeteerTimeout = config.puppeteerTimeout || cfg?.bot?.puppeteer_timeout || 0 + } + + /** + * 初始化chromium + */ + async browserInit () { + if (this.browser) return this.browser + if (this.lock) return false + this.lock = true + + logger.info('puppeteer Chromium 启动中...') + + let connectFlag = false + try { + // 获取Mac地址 + if (!mac) { + mac = await this.getMac() + this.browserMacKey = `Yz:chromium:browserWSEndpoint:${mac}` + } + // 是否有browser实例 + const browserUrl = (await redis.get(this.browserMacKey)) || this.config.wsEndpoint + if (browserUrl) { + logger.info(`puppeteer Chromium from ${browserUrl}`) + const browserWSEndpoint = await puppeteer.connect({ browserWSEndpoint: browserUrl }).catch(() => { + logger.error('puppeteer Chromium 缓存的实例已关闭') + redis.del(this.browserMacKey) + }) + // 如果有实例,直接使用 + if (browserWSEndpoint) { + this.browser = browserWSEndpoint + if (this.browser) { + connectFlag = true + } + } + } + } catch (e) { + logger.info('puppeteer Chromium 不存在已有实例') + } + + if (!this.browser || !connectFlag) { + // 如果没有实例,初始化puppeteer + this.browser = await puppeteer.launch(this.config).catch((err, trace) => { + let errMsg = err.toString() + (trace ? trace.toString() : '') + if (typeof err == 'object') { + logger.error(JSON.stringify(err)) + } else { + logger.error(err.toString()) + if (errMsg.includes('Could not find Chromium')) { + logger.error('没有正确安装 Chromium,可以尝试执行安装命令:node node_modules/puppeteer/install.js') + } else if (errMsg.includes('cannot open shared object file')) { + logger.error('没有正确安装 Chromium 运行库') + } + } + logger.error(err, trace) + }) + } + + this.lock = false + + if (!this.browser) { + logger.error('puppeteer Chromium 启动失败') + return false + } + if (connectFlag) { + logger.info('puppeteer Chromium 已连接启动的实例') + } else { + logger.info(`[Chromium] ${this.browser.wsEndpoint()}`) + if (process.env.pm_id && this.browserMacKey) { + // 缓存一下实例30天 + const expireTime = 60 * 60 * 24 * 30 + await redis.set(this.browserMacKey, this.browser.wsEndpoint(), { EX: expireTime }) + } + logger.info('puppeteer Chromium 启动成功') + } + + /** 监听Chromium实例是否断开 */ + this.browser.on('disconnected', () => { + logger.error('Chromium 实例关闭或崩溃!') + this.browser = false + }) + + return this.browser + } + + // 获取Mac地址 + getMac () { + let mac = '00:00:00:00:00:00' + try { + const network = os.networkInterfaces() + let macFlag = false + for (const a in network) { + for (const i of network[a]) { + if (i.mac && i.mac !== mac) { + macFlag = true + mac = i.mac + break + } + } + if (macFlag) { + break + } + } + } catch (e) { + } + mac = mac.replace(/:/g, '') + return mac + } + + /** + * `chromium` 截图 + * @param name + * @param data 模板参数 + * @param data.tplFile 模板路径,必传 + * @param data.saveId 生成html名称,为空name代替 + * @param data.imgType screenshot参数,生成图片类型:jpeg,png + * @param data.quality screenshot参数,图片质量 0-100,jpeg是可传,默认90 + * @param data.omitBackground screenshot参数,隐藏默认的白色背景,背景透明。默认不透明 + * @param data.path screenshot参数,截图保存路径。截图图片类型将从文件扩展名推断出来。如果是相对路径,则从当前路径解析。如果没有指定路径,图片将不会保存到硬盘。 + * @param data.multiPage 是否分页截图,默认false + * @param data.multiPageHeight 分页状态下页面高度,默认4000 + * @param data.pageGotoParams 页面goto时的参数 + * @return img 不做segment包裹 + */ + async screenshot (name, data = {}) { + if (!await this.browserInit()) { + return false + } + const pageHeight = data.multiPageHeight || 4000 + + let savePath = this.dealTpl(name, data) + if (!savePath) { + return false + } + + let buff = '' + let start = Date.now() + + let ret = [] + this.shoting.push(name) + + const puppeteerTimeout = this.puppeteerTimeout + let overtime + let overtimeFlag = false + if (puppeteerTimeout > 0) { + // TODO 截图超时处理 + overtime = setTimeout(() => { + if (!overtimeFlag) { + logger.error(`[图片生成][${name}] 截图超时,当前等待队列:${this.shoting.join(',')}`) + this.restart(true) + this.shoting = [] + overtimeList.forEach(item => { + clearTimeout(item) + }) + } + }, puppeteerTimeout) + } + + try { + const page = await this.browser.newPage() + let pageGotoParams = lodash.extend({ timeout: 120000 }, data.pageGotoParams || {}) + await page.goto(`file://${_path}${lodash.trim(savePath, '.')}`, pageGotoParams) + let body = await page.$('#container') || await page.$('body') + + // 计算页面高度 + const boundingBox = await body.boundingBox() + // 分页数 + let num = 1 + + let randData = { + type: data.imgType || 'jpeg', + omitBackground: data.omitBackground || false, + quality: data.quality || 90, + path: data.path || '' + } + + if (data.multiPage) { + randData.type = 'jpeg' + num = Math.round(boundingBox.height / pageHeight) || 1 + } + + if (data.imgType === 'png') { + delete randData.quality + } + + if (!data.multiPage) { + buff = await body.screenshot(randData) + /** 计算图片大小 */ + const kb = (buff.length / 1024).toFixed(2) + 'KB' + logger.mark(`[图片生成][${name}][${this.renderNum}次] ${kb} ${logger.green(`${Date.now() - start}ms`)}`) + this.renderNum++ + ret.push(buff) + } else { + // 分片截图 + if (num > 1) { + await page.setViewport({ + width: boundingBox.width, + height: pageHeight + 100 + }) + } + for (let i = 1; i <= num; i++) { + if (i !== 1 && i === num) { + await page.setViewport({ + width: boundingBox.width, + height: parseInt(boundingBox.height) - pageHeight * (num - 1) + }) + } + if (i !== 1 && i <= num) { + await page.evaluate(pageHeight => window.scrollBy(0, pageHeight), pageHeight) + } + if (num === 1) { + buff = await body.screenshot(randData) + } else { + buff = await page.screenshot(randData) + } + if (num > 2) { + await Data.sleep(200) + } + this.renderNum++ + + /** 计算图片大小 */ + const kb = (buff.length / 1024).toFixed(2) + 'KB' + logger.mark(`[图片生成][${name}][${i}/${num}] ${kb}`) + ret.push(buff) + } + if (num > 1) { + logger.mark(`[图片生成][${name}] 处理完成`) + } + } + page.close().catch((err) => logger.error(err)) + } catch (error) { + logger.error(`[图片生成][${name}] 图片生成失败:${error}`) + /** 关闭浏览器 */ + if (this.browser) { + await this.browser.close().catch((err) => logger.error(err)) + } + this.browser = false + ret = [] + return false + } finally { + if (overtime) { + overtimeFlag = true + clearTimeout(overtime) + overtimeList = [] + } + } + + this.shoting.pop() + + if (ret.length === 0 || !ret[0]) { + logger.error(`[图片生成][${name}] 图片生成为空`) + return false + } + + this.restart(false) + + return data.multiPage ? ret : ret[0] + } + + /** 重启 */ + restart (force = false) { + /** 截图超过重启数时,自动关闭重启浏览器,避免生成速度越来越慢 */ + if (this.renderNum % this.restartNum === 0 || force) { + if (this.shoting.length <= 0 || force) { + setTimeout(async () => { + if (this.browser) { + await this.browser.close().catch((err) => logger.error(err)) + } + this.browser = false + logger.info(`puppeteer Chromium ${force ? '强制' : ''}关闭重启...`) + }, 100) + } + } + } +}