From 871ac9c4b6267fa78b5807647518178e8647d66c Mon Sep 17 00:00:00 2001 From: RegadPole <69202360+RegadPoleCN@users.noreply.github.com> Date: Sun, 12 May 2024 16:19:55 +0800 Subject: [PATCH 01/16] Update maven.yml Add dev branch to actions --- .github/workflows/maven.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index ad59d5c..1bffd20 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -11,9 +11,9 @@ name: Java CI with Maven on: push: - branches: [ "main" ] + branches: [ "main", "dev" ] pull_request: - branches: [ "main" ] + branches: [ "main", "dev" ] workflow_dispatch: jobs: @@ -42,4 +42,4 @@ jobs: uses: actions/upload-artifact@v3.1.2 with: name: "PlumBot-velocity.jar" - path: plumbot-velocity/target/plumbot-velocity*.jar \ No newline at end of file + path: plumbot-velocity/target/plumbot-velocity*.jar From 486f31bdc5dbf49a60eee5f21738e24b8517f91c Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Wed, 15 May 2024 17:10:04 +0800 Subject: [PATCH 02/16] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AF=B9BungeeCord?= =?UTF-8?q?=E7=9A=84=E6=94=AF=E6=8C=81\n=E6=9B=B4=E6=96=B01.3.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/maven-dev.yml | 51 ++ .github/workflows/maven.yml | 10 +- README.md | 1 + plumbot-bukkit/pom.xml | 2 +- .../java/me/regadpole/plumbot/PlumBot.java | 7 +- .../java/me/regadpole/plumbot/bot/Bot.java | 3 - .../me/regadpole/plumbot/bot/KookBot.java | 4 +- .../regadpole/plumbot/command/Commands.java | 27 +- .../plumbot/internal/Dependencies.java | 10 +- .../plumbot/internal/Environment.java | 38 + plumbot-bungee/pom.xml | 65 ++ .../java/me/regadpole/plumbot/PlumBot.java | 116 +++ .../java/me/regadpole/plumbot/bot/Bot.java | 9 + .../me/regadpole/plumbot/bot/KookBot.java | 148 ++++ .../java/me/regadpole/plumbot/bot/QQBot.java | 221 +++++ .../regadpole/plumbot/command/Commands.java | 99 +++ .../me/regadpole/plumbot/config/Args.java | 21 + .../me/regadpole/plumbot/config/Config.java | 151 ++++ .../me/regadpole/plumbot/config/DataBase.java | 23 + .../plumbot/event/kook/KookEvent.java | 254 ++++++ .../regadpole/plumbot/event/qq/QQEvent.java | 253 ++++++ .../plumbot/event/server/ServerEvent.java | 118 +++ .../plumbot/event/server/ServerManager.java | 26 + .../plumbot/internal/Dependencies.java | 77 ++ .../plumbot/internal/Environment.java | 10 + .../plumbot/internal/database/Database.java | 12 + .../internal/database/DatabaseManager.java | 288 +++++++ .../plumbot/internal/database/MySQL.java | 60 ++ .../plumbot/internal/database/SQLite.java | 56 ++ .../plumbot/internal/kook/KookClient.java | 62 ++ .../plumbot/internal/maven/LibraryLoader.java | 202 +++++ .../internal/maven/MavenLibraries.java | 42 + .../plumbot/internal/maven/MavenLibrary.java | 64 ++ .../internal/maven/URLClassLoaderAccess.java | 176 ++++ .../me/regadpole/plumbot/metrics/Metrics.java | 757 ++++++++++++++++++ .../me/regadpole/plumbot/tool/StringTool.java | 16 + .../src/main/java/sdk/anno/Param.java | 13 + .../src/main/java/sdk/client/Client.java | 280 +++++++ .../main/java/sdk/client/ClientFactory.java | 48 ++ .../java/sdk/client/impl/AdminClient.java | 155 ++++ .../main/java/sdk/client/impl/FileClient.java | 131 +++ .../sdk/client/impl/GroupAdminClient.java | 303 +++++++ .../java/sdk/client/impl/GroupClient.java | 150 ++++ .../java/sdk/client/impl/MessageClient.java | 159 ++++ .../main/java/sdk/client/impl/UserClient.java | 111 +++ .../main/java/sdk/client/response/CQFile.java | 43 + .../java/sdk/client/response/CQStatus.java | 162 ++++ .../sdk/client/response/CQVersionInfo.java | 153 ++++ .../java/sdk/client/response/EssenceMsg.java | 83 ++ .../sdk/client/response/ForwardMessage.java | 72 ++ .../java/sdk/client/response/ForwardNode.java | 93 +++ .../main/java/sdk/client/response/Friend.java | 43 + .../sdk/client/response/GroupAtAllRemain.java | 43 + .../client/response/GroupFileSystemInfo.java | 53 ++ .../java/sdk/client/response/GroupFiles.java | 214 +++++ .../sdk/client/response/GroupHonorInfo.java | 183 +++++ .../java/sdk/client/response/GroupInfo.java | 83 ++ .../sdk/client/response/GroupMemberInfo.java | 163 ++++ .../sdk/client/response/GroupSystemMsg.java | 205 +++++ .../java/sdk/client/response/LoginInfo.java | 34 + .../java/sdk/client/response/Message.java | 113 +++ .../java/sdk/client/response/OcrImage.java | 104 +++ .../sdk/client/response/OnlineClient.java | 43 + .../sdk/client/response/StrangerInfo.java | 64 ++ .../java/sdk/client/response/VipInfo.java | 83 ++ .../src/main/java/sdk/config/CQConfig.java | 52 ++ .../main/java/sdk/config/MessageConfig.java | 44 + .../main/java/sdk/connection/Connection.java | 13 + .../sdk/connection/ConnectionFactory.java | 49 ++ .../connection/impl/CQWebSocketClient.java | 71 ++ .../connection/impl/CQWebSocketServer.java | 65 ++ .../sdk/connection/impl/CustomHttpServer.java | 70 ++ .../main/java/sdk/event/EventDispatchers.java | 167 ++++ .../java/sdk/event/global/GroupNotice.java | 33 + .../main/java/sdk/event/global/Message.java | 45 ++ .../main/java/sdk/event/global/Notice.java | 24 + .../java/sdk/event/global/RecvMessage.java | 84 ++ .../main/java/sdk/event/global/Request.java | 24 + .../java/sdk/event/message/GroupMessage.java | 183 +++++ .../sdk/event/message/PrivateMessage.java | 84 ++ .../sdk/event/notice/ClientStatusNotice.java | 35 + .../java/sdk/event/notice/EssenceNotice.java | 55 ++ .../sdk/event/notice/FriendAddNotice.java | 25 + .../sdk/event/notice/FriendPokeNotice.java | 55 ++ .../sdk/event/notice/FriendRecallNotice.java | 35 + .../sdk/event/notice/GroupAdminNotice.java | 27 + .../java/sdk/event/notice/GroupBanNotice.java | 45 ++ .../sdk/event/notice/GroupCardNotice.java | 35 + .../sdk/event/notice/GroupDecreaseNotice.java | 37 + .../event/notice/GroupFileUploadNotice.java | 96 +++ .../sdk/event/notice/GroupHonorNotice.java | 35 + .../sdk/event/notice/GroupIncreaseNotice.java | 35 + .../event/notice/GroupLuckyKingNotice.java | 35 + .../sdk/event/notice/GroupPokeNotice.java | 36 + .../sdk/event/notice/GroupRecallNotice.java | 35 + .../sdk/event/notice/OfflineFileNotice.java | 74 ++ .../java/sdk/event/request/FriendRequest.java | 45 ++ .../java/sdk/event/request/GroupRequest.java | 65 ++ .../sdk/listener/DefaultHandlerListener.java | 41 + .../java/sdk/listener/EnableListener.java | 23 + .../src/main/java/sdk/listener/Listener.java | 17 + .../java/sdk/listener/SimpleListener.java | 4 + .../java/sdk/listener/VailderListener.java | 18 + .../java/sdk/listener/handler/Handler.java | 10 + .../listener/impl/GroupMessageListener.java | 22 + .../listener/impl/PrivateMessageListener.java | 20 + .../src/main/java/sdk/type/HonorType.java | 25 + .../src/main/java/sdk/type/SubType.java | 20 + .../main/java/sdk/utils/ListenerUtils.java | 57 ++ plumbot-bungee/src/main/resources/bot.yml | 27 + plumbot-bungee/src/main/resources/bungee.yml | 13 + plumbot-bungee/src/main/resources/config.yml | 55 ++ .../src/main/resources/kook/kbc.yml | 43 + plumbot-bungee/src/main/resources/returns.yml | 4 + plumbot-velocity/pom.xml | 2 +- .../java/me/regadpole/plumbot/PlumBot.java | 9 +- .../java/me/regadpole/plumbot/bot/Bot.java | 3 - .../me/regadpole/plumbot/bot/KookBot.java | 1 - .../regadpole/plumbot/command/Commands.java | 13 + .../plumbot/internal/Dependencies.java | 8 +- .../plumbot/internal/Environment.java | 22 + pom.xml | 11 +- 122 files changed, 9120 insertions(+), 24 deletions(-) create mode 100644 .github/workflows/maven-dev.yml create mode 100644 plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java create mode 100644 plumbot-bungee/pom.xml create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/PlumBot.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/Bot.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/KookBot.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/QQBot.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/command/Commands.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Args.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Config.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/config/DataBase.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerManager.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Dependencies.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Environment.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/Database.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/SQLite.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/kook/KookClient.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/LibraryLoader.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibraries.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibrary.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/URLClassLoaderAccess.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/metrics/Metrics.java create mode 100644 plumbot-bungee/src/main/java/me/regadpole/plumbot/tool/StringTool.java create mode 100644 plumbot-bungee/src/main/java/sdk/anno/Param.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/Client.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/ClientFactory.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/impl/AdminClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/impl/FileClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/impl/GroupAdminClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/impl/GroupClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/impl/MessageClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/impl/UserClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/CQFile.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/CQStatus.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/CQVersionInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/EssenceMsg.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/ForwardMessage.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/ForwardNode.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/Friend.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupAtAllRemain.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupFileSystemInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupFiles.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupHonorInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupMemberInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/GroupSystemMsg.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/LoginInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/Message.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/OcrImage.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/OnlineClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/StrangerInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/client/response/VipInfo.java create mode 100644 plumbot-bungee/src/main/java/sdk/config/CQConfig.java create mode 100644 plumbot-bungee/src/main/java/sdk/config/MessageConfig.java create mode 100644 plumbot-bungee/src/main/java/sdk/connection/Connection.java create mode 100644 plumbot-bungee/src/main/java/sdk/connection/ConnectionFactory.java create mode 100644 plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketClient.java create mode 100644 plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketServer.java create mode 100644 plumbot-bungee/src/main/java/sdk/connection/impl/CustomHttpServer.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/EventDispatchers.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/global/GroupNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/global/Message.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/global/Notice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/global/RecvMessage.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/global/Request.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/message/GroupMessage.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/message/PrivateMessage.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/ClientStatusNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/EssenceNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/FriendAddNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/FriendPokeNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/FriendRecallNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupAdminNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupBanNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupCardNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupDecreaseNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupFileUploadNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupHonorNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupIncreaseNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupLuckyKingNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupPokeNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/GroupRecallNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/notice/OfflineFileNotice.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/request/FriendRequest.java create mode 100644 plumbot-bungee/src/main/java/sdk/event/request/GroupRequest.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/DefaultHandlerListener.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/EnableListener.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/Listener.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/SimpleListener.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/VailderListener.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/handler/Handler.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/impl/GroupMessageListener.java create mode 100644 plumbot-bungee/src/main/java/sdk/listener/impl/PrivateMessageListener.java create mode 100644 plumbot-bungee/src/main/java/sdk/type/HonorType.java create mode 100644 plumbot-bungee/src/main/java/sdk/type/SubType.java create mode 100644 plumbot-bungee/src/main/java/sdk/utils/ListenerUtils.java create mode 100644 plumbot-bungee/src/main/resources/bot.yml create mode 100644 plumbot-bungee/src/main/resources/bungee.yml create mode 100644 plumbot-bungee/src/main/resources/config.yml create mode 100644 plumbot-bungee/src/main/resources/kook/kbc.yml create mode 100644 plumbot-bungee/src/main/resources/returns.yml create mode 100644 plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Environment.java diff --git a/.github/workflows/maven-dev.yml b/.github/workflows/maven-dev.yml new file mode 100644 index 0000000..11080fc --- /dev/null +++ b/.github/workflows/maven-dev.yml @@ -0,0 +1,51 @@ + +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Java CI dev + +on: + push: + branches: [ "dev" ] + pull_request: + branches: [ "dev" ] + workflow_dispatch: + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 18 + uses: actions/setup-java@v3 + with: + java-version: '18' + distribution: 'zulu' + cache: maven + - name: Build with Maven + run: mvn -B package --file pom.xml + + - name: Upload a Build Artifact - PlumBot-bukkit + uses: actions/upload-artifact@v3.1.2 + with: + name: "PlumBot-bukkit.jar" + path: plumbot-bukkit/target/plumbot-bukkit*.jar + + - name: Upload a Build Artifact - PlumBot-velocity + uses: actions/upload-artifact@v3.1.2 + with: + name: "PlumBot-velocity.jar" + path: plumbot-velocity/target/plumbot-velocity*.jar + + - name: Upload a Build Artifact - PlumBot-bungee + uses: actions/upload-artifact@v3.1.2 + with: + name: "PlumBot-bungee.jar" + path: plumbot-bungee/target/plumbot-bungee*.jar diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 1bffd20..c464d8f 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -11,9 +11,9 @@ name: Java CI with Maven on: push: - branches: [ "main", "dev" ] + branches: [ "main" ] pull_request: - branches: [ "main", "dev" ] + branches: [ "main" ] workflow_dispatch: jobs: @@ -43,3 +43,9 @@ jobs: with: name: "PlumBot-velocity.jar" path: plumbot-velocity/target/plumbot-velocity*.jar + + - name: Upload a Build Artifact - PlumBot-bungee + uses: actions/upload-artifact@v3.1.2 + with: + name: "PlumBot-bungee.jar" + path: plumbot-bungee/target/plumbot-bungee*.jar diff --git a/README.md b/README.md index af86881..93396f9 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ ![GitHub](https://img.shields.io/github/license/RegadPoleCN/PlumBot) [![Java CI with Maven](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven.yml/badge.svg)](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven.yml) +[![Java CI dev](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven-dev.yml/badge.svg)](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven-dev.yml) ![GitHub release (with filter)](https://img.shields.io/github/v/release/RegadPoleCN/PlumBot) 本插件适用于[go-cqhttp](https://github.com/Mrs4s/go-cqhttp)中的http通信模式 和 [kook](kookapp.cn)的websocket模式 diff --git a/plumbot-bukkit/pom.xml b/plumbot-bukkit/pom.xml index 8b700b6..702269a 100644 --- a/plumbot-bukkit/pom.xml +++ b/plumbot-bukkit/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.1 + 1.3.2 plumbot-bukkit diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/PlumBot.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/PlumBot.java index a7c9255..2fc7360 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/PlumBot.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/PlumBot.java @@ -14,6 +14,7 @@ import me.regadpole.plumbot.hook.QuickShopHook; import me.regadpole.plumbot.hook.ResidenceHook; import me.regadpole.plumbot.internal.Dependencies; +import me.regadpole.plumbot.internal.Environment; import me.regadpole.plumbot.internal.FoliaSupport; import me.regadpole.plumbot.internal.database.Database; import me.regadpole.plumbot.internal.database.DatabaseManager; @@ -38,6 +39,7 @@ public final class PlumBot extends JavaPlugin implements Listener { private static Database database; private static Bot bot; + private static Environment environment; @Override public void onLoad() { @@ -66,7 +68,7 @@ public void onEnable() { if (QuickShopHook.hasQs) Bukkit.getPluginManager().registerEvents(new QsChatEvent(),this); if (QuickShopHook.hasQsHikari) Bukkit.getPluginManager().registerEvents(new QsHikariChatEvent(),this); getLogger().info("服务器事件监听器注册完毕"); - Bukkit.getServer().getPluginCommand("plumbot").setExecutor(new Commands()); + Bukkit.getServer().getPluginCommand("plumbot").setExecutor(new Commands(this)); getLogger().info("命令注册完毕"); getScheduler().runTaskAsynchronously(() -> { @@ -94,6 +96,7 @@ public void onEnable() { int pluginId = 19427; // <-- Replace with the id of your plugin! Metrics metrics = new Metrics(this, pluginId); + environment = new Environment(); getLogger().info( "PlumBot已启动"); } @@ -138,7 +141,7 @@ public static Database getDatabase() { public void setDatabase(Database database) { PlumBot.database =database; } - + public Environment getEnvironment() {return environment;} } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/Bot.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/Bot.java index 85d5991..ce4f3a2 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/Bot.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/Bot.java @@ -1,12 +1,9 @@ package me.regadpole.plumbot.bot; -import snw.jkook.message.component.BaseComponent; - public interface Bot { void start(); void shutdown(); void sendMsg(boolean isGroup, String message, long id); - default void sendMsg(boolean isGroup, BaseComponent message, long id) {} String getGroupName(long groupId); boolean checkUserInGroup(long userId, long groupId); } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/KookBot.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/KookBot.java index 07cd279..3f8c9cf 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/KookBot.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/bot/KookBot.java @@ -29,7 +29,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.Set; import static me.regadpole.plumbot.PlumBot.INSTANCE; @@ -48,7 +47,7 @@ public void start() { File kookPlugins; KBCClient kook; kookcore = new CoreImpl(); - JKook.setCore(kookcore); + if (JKook.getCore() == null) JKook.setCore(kookcore); config = YamlConfiguration.loadConfiguration(new File(kookFolder, "kbc.yml")); kookPlugins = new File(kookFolder, "plugins"); kook = new KookClient(kookcore, config, kookPlugins, Config.getKookBotToken(), "websocket"); @@ -85,7 +84,6 @@ public void sendMsg(boolean isGroup, String message, long id) { }); } - @Override public void sendMsg(boolean isGroup, BaseComponent message, long id) { if (id == 0L) {return;} if (message.toString().isEmpty()) {return;} diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java index 6ebaa9a..82768b4 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -4,7 +4,9 @@ import me.regadpole.plumbot.bot.KookBot; import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; import me.regadpole.plumbot.internal.database.DatabaseManager; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; @@ -16,6 +18,12 @@ public class Commands implements CommandExecutor{ + private PlumBot plugin; + + public Commands(PlumBot plugin){ + this.plugin = plugin; + } + @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { @@ -25,6 +33,22 @@ public boolean onCommand(CommandSender sender, Command command, String label, St } switch (args[0]) { + case "info": + StringBuilder stringbuilder = new StringBuilder(); + stringbuilder.append("§1---PlumBot 信息---").append("\n"); + stringbuilder.append("§a作者: ").append("§f").append(plugin.getEnvironment().author).append("\n"); + stringbuilder.append("§a版本: ").append("§f").append(plugin.getEnvironment().version).append("\n"); + stringbuilder.append("§a机器人平台: ").append("§f").append(Config.getBotMode()).append("\n"); + stringbuilder.append("§a数据库模式: ").append("§f").append(DataBase.type()).append("\n"); + stringbuilder.append("§a服务端版本: ").append("§f").append(Bukkit.getVersion()).append("\n"); + stringbuilder.append("§a兼容插件: ").append("\n"); + stringbuilder.append("\t").append("§bAuthMe: ").append(plugin.getEnvironment().authme).append("\n"); + stringbuilder.append("\t").append("§bGriefDefender: ").append(plugin.getEnvironment().griefdefender).append("\n"); + stringbuilder.append("\t").append("§bResidence: ").append(plugin.getEnvironment().residence).append("\n"); + stringbuilder.append("\t").append("§bQuickShop: ").append(plugin.getEnvironment().quickshop).append("\n"); + stringbuilder.append("\t").append("§bQuickShopHikari: ").append(plugin.getEnvironment().quickshophikari).append("\n"); + sender.sendMessage(stringbuilder.toString()); + break; case "reload": if (args.length != 1) return true; DatabaseManager.close(); @@ -32,13 +56,14 @@ public boolean onCommand(CommandSender sender, Command command, String label, St Config.loadConfig(); DatabaseManager.start(); PlumBot.getBot().start(); - sender.sendMessage("PlumBot配置文件已重载"); + sender.sendMessage("PlumBot已重载"); break; case "help": if (args.length != 1) return true; sender.sendMessage("§6PlumBot 机器人帮助菜单"); sender.sendMessage("§6/pb reload :§f重载插件"); sender.sendMessage("§6/pb help :§f获取插件帮助"); + sender.sendMessage("§6/pb info :§f插件基本信息"); sender.sendMessage("§6/pb kook help :§f获取kook帮助"); sender.sendMessage("§6/pb kook plugins :§f获取kook插件列表"); break; diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java index 9925ba6..7922533 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java @@ -1,5 +1,6 @@ package me.regadpole.plumbot.internal; +import com.ghostchu.quickshop.util.config.UpdateScript; import me.regadpole.plumbot.internal.maven.MavenLibraries; import me.regadpole.plumbot.internal.maven.MavenLibrary; @@ -14,7 +15,8 @@ @MavenLibrary(groupId = lombok.groupId, artifactId = lombok.artifactId, version = lombok.version), @MavenLibrary(groupId = HikariCP.groupId, artifactId = HikariCP.artifactId, version = HikariCP.version), @MavenLibrary(groupId = MySQL.groupId, artifactId = MySQL.artifactId, version = MySQL.version), - @MavenLibrary(groupId = sqlite.groupId, artifactId = sqlite.artifactId, version = sqlite.version)}) + @MavenLibrary(groupId = sqlite.groupId, artifactId = sqlite.artifactId, version = sqlite.version), + @MavenLibrary(groupId = kookbc.groupId, artifactId = kookbc.artifactId, version = kookbc.version)}) public class Dependencies { public static class hutool{ public static final String groupId = "cn.hutool"; @@ -62,5 +64,9 @@ public static class sqlite{ public static final String artifactId = "sqlite-jdbc"; public static final String version = "3.42.0.0"; } - + public static class kookbc{ + public static final String groupId = "com.github.SNWCreations"; + public static final String artifactId = "KookBC"; + public static final String version = "0.27.4"; + } } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java new file mode 100644 index 0000000..5f652e8 --- /dev/null +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java @@ -0,0 +1,38 @@ +package me.regadpole.plumbot.internal; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.hook.AuthMeHook; +import me.regadpole.plumbot.hook.GriefDefenderHook; +import me.regadpole.plumbot.hook.QuickShopHook; +import me.regadpole.plumbot.hook.ResidenceHook; + +import java.util.Iterator; + +public final class Environment { + private final PlumBot plugin = PlumBot.INSTANCE; + public final String name = plugin.getDescription().getName(); + public final String version = plugin.getDescription().getVersion(); + public final String author = getAuthorString(); + public final String authme = getPluginHooked(AuthMeHook.hasAuthMe); + public final String griefdefender = getPluginHooked(GriefDefenderHook.hasGriefDefender); + public final String quickshop = getPluginHooked(QuickShopHook.hasQs); + public final String quickshophikari = getPluginHooked(QuickShopHook.hasQsHikari); + public final String residence = getPluginHooked(ResidenceHook.hasRes); + + private String getPluginHooked(boolean hooked){ + if (hooked){ + return "§2True"; + } else { + return "§cFalse"; + } + } + + private String getAuthorString() { + Iterator authors = plugin.getDescription().getAuthors().iterator(); + StringBuilder stringBuilder = new StringBuilder(); + while(authors.hasNext()){ + stringBuilder.append(authors.next()).append(", "); + } + return stringBuilder.substring(0, stringBuilder.lastIndexOf(",")-1); + } +} diff --git a/plumbot-bungee/pom.xml b/plumbot-bungee/pom.xml new file mode 100644 index 0000000..87d5ae9 --- /dev/null +++ b/plumbot-bungee/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + me.regadpole + plumbot + 1.3.2 + + + plumbot-bungee + + + 11 + 11 + UTF-8 + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.5.0 + + + package + + shade + + + + + + + + src/main/resources + true + + + + + + + bungeecord-repo + https://oss.sonatype.org/content/repositories/snapshots + + + + + + net.md-5 + bungeecord-api + 1.12-SNAPSHOT + provided + + + com.google.code.findbugs + jsr305 + 3.0.2 + provided + + + diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/PlumBot.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/PlumBot.java new file mode 100644 index 0000000..cf36e89 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/PlumBot.java @@ -0,0 +1,116 @@ +package me.regadpole.plumbot; + +import me.regadpole.plumbot.bot.Bot; +import me.regadpole.plumbot.bot.KookBot; +import me.regadpole.plumbot.bot.QQBot; +import me.regadpole.plumbot.command.Commands; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.event.server.ServerEvent; +import me.regadpole.plumbot.internal.Dependencies; +import me.regadpole.plumbot.internal.Environment; +import me.regadpole.plumbot.internal.database.Database; +import me.regadpole.plumbot.internal.database.DatabaseManager; +import me.regadpole.plumbot.internal.maven.LibraryLoader; +import me.regadpole.plumbot.metrics.Metrics; +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.plugin.Plugin; + +import java.io.IOException; + +public final class PlumBot extends Plugin { + + public static PlumBot INSTANCE; + + private static Database database; + private static Bot bot; + private static Environment environment; + + @Override + public void onLoad() { + INSTANCE = this; + + try { + Config.createConfig(); + } catch (IOException e) { + e.printStackTrace(); + } + + LibraryLoader.loadAll(Dependencies.class); + getLogger().info("PlumBot依赖已加载成功"); + } + + @Override + public void onEnable() { + + DatabaseManager.start(); + getProxy().getPluginManager().registerListener(this, new ServerEvent(this)); + getLogger().info("服务器事件监听器注册完毕"); + getProxy().getPluginManager().registerCommand(this, new Commands(this)); + getLogger().info("命令注册完毕"); + + getProxy().getScheduler().runAsync(this, () -> { + switch (Config.getBotMode()) { + case "go-cqhttp": + bot = new QQBot(this); + bot.start(); + getLogger().info("已启动go-cqhttp服务"); + break; + case "kook": + bot = new KookBot(); + bot.start(); + KookBot.setKookEnabled(true); + getLogger().info("已启动kook服务"); + break; + default: + getLogger().warning("无法启动服务,请检查配置文件,插件已关闭"); + getProxy().getPluginManager().getPlugin("PlumBot").onDisable(); + break; + } + }); + + // All you have to do is adding the following two lines in your onEnable method. + // You can find the plugin ids of your plugins on the page https://bstats.org/what-is-my-plugin-id + int pluginId = 21652; // <-- Replace with the id of your plugin! + Metrics metrics = new Metrics(this, pluginId); + + environment = new Environment(); + getLogger().info( "PlumBot已启动"); + + } + + @Override + public void onDisable() { + switch (Config.getBotMode()) { + case "go-cqhttp": + bot.shutdown(); + getLogger().info("已关闭go-cqhttp服务"); + break; + case "kook": + bot.shutdown(); + getLogger().info("已关闭kook服务"); + break; + default: + getLogger().warning("无法正常关闭服务,将在服务器关闭后强制关闭"); + getProxy().getPluginManager().getPlugin("PlumBot").onDisable(); + break; + } + DatabaseManager.close(); + getLogger().info("PlumBot已关闭"); + } + + public static void say(String s) { + CommandSender sender = INSTANCE.getProxy().getConsole(); + sender.sendMessage(s); + } + + public static Bot getBot() { + return bot; + } + public static Database getDatabase() { + return database; + } + public void setDatabase(Database database) { + PlumBot.database =database; + } + public Environment getEnvironment() {return environment;} +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/Bot.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/Bot.java new file mode 100644 index 0000000..ce4f3a2 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/Bot.java @@ -0,0 +1,9 @@ +package me.regadpole.plumbot.bot; + +public interface Bot { + void start(); + void shutdown(); + void sendMsg(boolean isGroup, String message, long id); + String getGroupName(long groupId); + boolean checkUserInGroup(long userId, long groupId); +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/KookBot.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/KookBot.java new file mode 100644 index 0000000..bfc93fc --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/KookBot.java @@ -0,0 +1,148 @@ +package me.regadpole.plumbot.bot; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.event.kook.KookEvent; +import me.regadpole.plumbot.internal.kook.KookClient; +import snw.jkook.JKook; +import snw.jkook.config.ConfigurationSection; +import snw.jkook.config.file.YamlConfiguration; +import snw.jkook.entity.User; +import snw.jkook.entity.channel.Channel; +import snw.jkook.entity.channel.TextChannel; +import snw.jkook.event.channel.ChannelMessageEvent; +import snw.jkook.event.pm.PrivateMessageReceivedEvent; +import snw.jkook.message.component.BaseComponent; +import snw.jkook.util.PageIterator; +import snw.kookbc.impl.CoreImpl; +import snw.kookbc.impl.KBCClient; + +import java.io.File; +import java.util.List; +import java.util.Set; + +import static me.regadpole.plumbot.PlumBot.INSTANCE; + +public class KookBot implements Bot { + + private static KBCClient kookClient; + private static KookBot kookBot; + private static boolean kookEnabled = false; + + @Override + public void start() { + CoreImpl kookcore; + File kookFolder = new File(INSTANCE.getDataFolder(), "kook"); + ConfigurationSection config; + File kookPlugins; + KBCClient kook; + kookcore = new CoreImpl(); + if (JKook.getCore() == null) JKook.setCore(kookcore); + config = YamlConfiguration.loadConfiguration(new File(kookFolder, "kbc.yml")); + kookPlugins = new File(kookFolder, "plugins"); + kook = new KookClient(kookcore, config, kookPlugins, Config.getKookBotToken(), "websocket"); + kook.start(); + kookClient = kook; + kookBot = new KookBot(); + kook.getCore().getEventManager().registerHandlers(kook.getInternalPlugin(), new KookEvent(this, INSTANCE)); + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + PlumBot.getBot().sendMsg(true, "PlumBot已启动", groupID); + } + } + + @Override + public void shutdown() { + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + sendChannelMessage("PlumBot已关闭", getChannel(groupID)); + } + kookClient.shutdown(); + } + + @Override + public void sendMsg(boolean isGroup, String message, long id) { + if (id == 0L) {return;} + if ("".equals(message)) {return;} + INSTANCE.getProxy().getScheduler().runAsync(INSTANCE, () -> { + if (isGroup) { + sendChannelMessage(message, getChannel(id)); + } + else { + sendPrivateMessage(message, getUser(id)); + } + }); + } + + public void sendMsg(boolean isGroup, BaseComponent message, long id) { + if (id == 0L) {return;} + if (message.toString().isEmpty()) {return;} + INSTANCE.getProxy().getScheduler().runAsync(INSTANCE, () -> { + if (isGroup) { + sendChannelMessage(message, getChannel(id)); + } + else { + sendPrivateMessage(message, getUser(id)); + } + }); + } + + public void sendChannelReply(ChannelMessageEvent e, String s) { + INSTANCE.getProxy().getScheduler().runAsync(INSTANCE, () -> { + e.getMessage().reply(s); + }); + } + + public void sendPrivateReply(PrivateMessageReceivedEvent e, String s) { + INSTANCE.getProxy().getScheduler().runAsync(INSTANCE, () -> { + e.getMessage().reply(s); + }); + } + + + private void sendChannelMessage(String s, TextChannel channel) { + channel.sendComponent(s); + } + + private void sendChannelMessage(BaseComponent s, TextChannel channel) { + channel.sendComponent(s); + } + + private void sendPrivateMessage(String s, User user) {user.sendPrivateMessage(s);} + private void sendPrivateMessage(BaseComponent s,User user) {user.sendPrivateMessage(s);} + + @Override + public String getGroupName(long groupId) { + Channel channel = getChannel(groupId); + return channel.getName(); + } + + public TextChannel getChannel(long groupId) { + return (TextChannel) kookClient.getCore().getHttpAPI().getChannel(String.valueOf(groupId)); + } + + @Override + public boolean checkUserInGroup(long userId, long groupId){ + PageIterator> iterator = getChannel(groupId).getGuild().getUsers(); + while(iterator.hasNext()){ + for (User user : iterator.next()) { + if (user.getId().equalsIgnoreCase(String.valueOf(userId))){ + return true; + } + } + } + return false; + } + + public User getUser(long id) { + return kookClient.getCore().getHttpAPI().getUser(String.valueOf(id)); + } + + public static KBCClient getKookClient() {return kookClient;} + + public static void setKookEnabled(boolean kook) {kookEnabled = kook;} + + public static boolean isKookEnabled() {return kookEnabled;} + + public static KookBot getKookBot() {return kookBot;} +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/QQBot.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/QQBot.java new file mode 100644 index 0000000..377f1e6 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/bot/QQBot.java @@ -0,0 +1,221 @@ +package me.regadpole.plumbot.bot; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.event.qq.QQEvent; +import sdk.client.ClientFactory; +import sdk.client.impl.GroupClient; +import sdk.client.impl.MessageClient; +import sdk.client.response.*; +import sdk.config.CQConfig; +import sdk.connection.Connection; +import sdk.connection.ConnectionFactory; +import sdk.event.EventDispatchers; +import sdk.event.message.GroupMessage; +import sdk.event.message.PrivateMessage; +import sdk.event.notice.GroupDecreaseNotice; +import sdk.listener.SimpleListener; + +import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; + +public class QQBot implements Bot { + + public QQBot(PlumBot plugin){ + this.plugin = plugin; + } + + private static CQConfig http_config; + private GroupClient client; + private MessageClient messageClient; + private static QQEvent qqEvent; + private Connection connection = null; + private PlumBot plugin; + + @Override + public void start() { + qqEvent = new QQEvent(plugin); + plugin.getLogger().info("QQ事件监听器注册完毕"); + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + http_config = new CQConfig(Config.getCqBotHttp(), Config.getCqBotToken(), Config.getCqBotIsAccessToken()); + client = new ClientFactory(http_config).createGroupClient(); + messageClient = new ClientFactory(http_config).createMessageClient(); + LinkedBlockingQueue blockingQueue = new LinkedBlockingQueue();//使用队列传输数据 + try { + connection = ConnectionFactory.createHttpServer(Config.getCqBotListenPort(),"/",blockingQueue); + } catch (Exception e) { + throw new RuntimeException(e); + } + connection.create(); + EventDispatchers dispatchers = new EventDispatchers(blockingQueue);//创建事件分发器 + dispatchers.addListener(new SimpleListener() {//私聊监听 + @Override + public void onMessage(PrivateMessage privateMessage) { + qqEvent.onFriendMessageReceive(privateMessage); + } + }); + dispatchers.addListener(new SimpleListener() {//群聊消息监听 + @Override + public void onMessage(GroupMessage groupMessage) { + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + if (groupID == groupMessage.getGroupId()) { + qqEvent.onGroupMessageReceive(groupMessage); + } + } + } + }); + dispatchers.addListener(new SimpleListener() {//群聊人数减少监听 + @Override + public void onMessage(GroupDecreaseNotice groupDecreaseNotice) { + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + if (groupID == groupDecreaseNotice.getGroupId()) { + qqEvent.onGroupDecreaseNotice(groupDecreaseNotice); + } + } + } + }); + dispatchers.start(10);//线程组处理任务 + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + PlumBot.getBot().sendMsg(true, "PlumBot已启动", groupID); + } + }); + } + + @Override + public void shutdown() { + QQBot bot = (QQBot) PlumBot.getBot(); + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + bot.sendGroupMsg( "PlumBot已关闭", groupID); + } + connection.stop(); + } + + @Override + public void sendMsg(boolean isGroup, String msg, long id) { + if (id == 0L) {return;} + if ("".equals(msg)) {return;} + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + if (isGroup) { + this.sendGroupMsg(msg, id); + } else { + this.sendPrivateMsg(msg, id); + } + }); + } + + public void sendCQMsg(boolean isGroup, String msg, long id) { + if (id == 0L) {return;} + if ("".equals(msg)) {return;} + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + if (isGroup) { + this.sendGroupCQMsg(msg, id); + } else { + this.sendPrivateCQMsg(msg, id); + } + }); + } + + /** + * 发送私聊消息 + */ + public void sendPrivateMsg(String msg, long userID){ + messageClient.sendPrivateMsg(userID, msg); + } + + /** + * 发送群聊消息 + */ + public void sendGroupMsg(String msg, long groupId) { + messageClient.sendGroupMsg(groupId, msg); + } + + /** + * 发送私聊消息 + */ + public void sendPrivateCQMsg(String msg, long userID){ + messageClient.sendPrivateMsg(userID, msg, false); + } + + /** + * 发送群聊消息 + */ + public void sendGroupCQMsg(String msg, long groupId) { + messageClient.sendGroupMsg(groupId, msg, false); + } + +// /** +// * 发送群聊消息 失败 +// */ +// public void sendGrouForwardMsg() { +// ForwardNode forwardNode = new ForwardNode(); +// ForwardNode.Data data = forwardNode.getData(); +// data.setName("slcower"); +// data.setContent("消息"); +// data.setSeq("消息"); +// data.setId(1720939235); +// data.setUin(1452683658L); +// ArrayList nodes = new ArrayList(); +// nodes.add(forwardNode); +// nodes.add(forwardNode); +// client.sendGroupForwardMsg(934145943L, nodes); +// } + + + /** + * 获取消息 + */ + public void getMsg(Integer msgId) { + Message msg = messageClient.getMsg(msgId); + System.out.println(msg); + } + + /** + * 获取转发消息 + */ + public void getForwardMsg(String msgId) { + List msg = messageClient.getForwardMsg(msgId); + System.out.println(msg); + } + + /** + * 获取图片缓存 + */ + public void getImage(String file) { + CQFile msg = messageClient.getImage(file); + System.out.println(msg); + } + + /** + * 撤回消息 + */ + public void deleteMsg(String msg, long groupId) { + messageClient.deleteMsg( messageClient.sendGroupMsg(groupId, msg)); + } + + /** + * 获取群信息 + */ + public GroupInfo getGroupInfo(long groupId) { + GroupInfo groupInfo = client.getGroupInfo(groupId); + return groupInfo; + } + + @Override + public String getGroupName(long groupId) { + return getGroupInfo(groupId).getGroupName(); + } + + @Override + public boolean checkUserInGroup(long userId, long groupId) { + for (GroupMemberInfo member : client.getGroupMemberList(groupId)){ + if(member.getUserId().equals(userId)){ + return true; + } + } + return false; + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/command/Commands.java new file mode 100644 index 0000000..0285377 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -0,0 +1,99 @@ +package me.regadpole.plumbot.command; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.bot.KookBot; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.internal.database.DatabaseManager; +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.plugin.Command; +import snw.jkook.command.ConsoleCommandSender; +import snw.jkook.plugin.Plugin; + +import java.io.IOException; +import java.util.Arrays; +import java.util.stream.Collectors; + +public class Commands extends Command { + + private PlumBot plugin; + + public Commands(PlumBot plugin){ + super("plumbot", "plumbot.command", "pb", "PlumBot"); + this.plugin = plugin; + } + + /** + * @param commandSender + * @param strings + */ + @Override + public void execute(CommandSender commandSender, String[] strings) { + if (strings.length == 0) { + commandSender.sendMessage("请使用/pb help查看命令使用方法"); + return; + } + + switch (strings[0]) { + case "info": + StringBuilder stringbuilder = new StringBuilder(); + stringbuilder.append("§1---PlumBot 信息---").append("\n"); + stringbuilder.append("§a作者: ").append("§f").append(plugin.getEnvironment().author).append("\n"); + stringbuilder.append("§a版本: ").append("§f").append(plugin.getEnvironment().version).append("\n"); + stringbuilder.append("§a机器人平台: ").append("§f").append(Config.getBotMode()).append("\n"); + stringbuilder.append("§a数据库模式: ").append("§f").append(DataBase.type()).append("\n"); + stringbuilder.append("§a服务端版本: ").append("§f").append(plugin.getProxy().getVersion()).append("\n"); + commandSender.sendMessage(stringbuilder.toString()); + break; + case "reload": + if (strings.length != 1) return; + DatabaseManager.close(); + PlumBot.getBot().shutdown(); + try { + Config.loadConfig(); + } catch (IOException e) { + e.printStackTrace(); + } + DatabaseManager.start(); + PlumBot.getBot().start(); + commandSender.sendMessage("PlumBot已重载"); + break; + case "help": + if (strings.length != 1) return; + commandSender.sendMessage("§6PlumBot 机器人帮助菜单"); + commandSender.sendMessage("§6/pb reload :§f重载插件"); + commandSender.sendMessage("§6/pb help :§f获取插件帮助"); + commandSender.sendMessage("§6/pb info :§f插件基本信息"); + commandSender.sendMessage("§6/pb kook help :§f获取kook帮助"); + commandSender.sendMessage("§6/pb kook plugins :§f获取kook插件列表"); + break; + case "kook": + if (strings.length == 1) { + commandSender.sendMessage("命令错误,格式:/plumbot kook "); + commandSender.sendMessage("value可选值:plugins,help"); + return; + } + if (strings.length > 2) return; + if (strings.length == 2) { + if (KookBot.isKookEnabled()) { + commandSender.sendMessage("kook客户端未启动"); + return; + } + switch (strings[1]) { + case "plugins": + Plugin[] plugins = KookBot.getKookClient().getCore().getPluginManager().getPlugins(); + String result = String.format("%s (%d): %s", commandSender instanceof ConsoleCommandSender ? "Installed and running plugins" : "已安装并正在运行的插件", plugins.length, String.join(", ", (Iterable) Arrays.stream(plugins).map((plugin) -> { + return plugin.getDescription().getName(); + }).collect(Collectors.toSet()))); + commandSender.sendMessage(result); + return; + } + } + break; + default: + if (strings.length != 1) return; + commandSender.sendMessage("错误的指令用法,请使用/pb help查看命令使用方法"); + break; + } + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Args.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Args.java new file mode 100644 index 0000000..f3ee0ba --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Args.java @@ -0,0 +1,21 @@ +package me.regadpole.plumbot.config; + +public class Args { + + public static int ForwardingMode(){ + return Config.getConfigYaml().getInt("Forwarding.mode"); + } + + public static String ForwardingPrefix(){ + return Config.getConfigYaml().getString("Forwarding.prefix"); + } + + public static String Prefix(){ + return Config.getConfigYaml().getString("Prefix"); + } + + public static String WhitelistKick() {return Config.getConfigYaml().getString("WhiteList.kickMsg");} + + public static String Maven() {return Config.getConfigYaml().getString("Maven");} + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Config.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Config.java new file mode 100644 index 0000000..45eee53 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/Config.java @@ -0,0 +1,151 @@ +package me.regadpole.plumbot.config; + +import me.regadpole.plumbot.PlumBot; +import net.md_5.bungee.config.Configuration; +import net.md_5.bungee.config.ConfigurationProvider; +import net.md_5.bungee.config.YamlConfiguration; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.List; + +public class Config { + private static final PlumBot INSTANCE = PlumBot.INSTANCE; + private static final File botFile = new File(INSTANCE.getDataFolder(), "bot.yml"); + private static final File configFile = new File(INSTANCE.getDataFolder(), "config.yml"); + private static final File returnsFile = new File(INSTANCE.getDataFolder(), "returns.yml"); + private static final File kook = new File(INSTANCE.getDataFolder(), "kook"); + private static final File kookConf = new File(kook, "kbc.yml"); + private static final File kookPlu = new File(kook, "plugins"); + private static Configuration bot; + private static Configuration config; + private static Configuration returns; + + public static void createConfig() throws IOException { + if (!INSTANCE.getDataFolder().exists()) { + INSTANCE.getDataFolder().mkdir(); + } + if (!kook.exists()) { + kook.mkdirs(); + } + if (!kookPlu.exists()) { + kookPlu.mkdirs(); + } + File[] allFile = {botFile,configFile,returnsFile}; + for (File file : allFile) { + if (!file.exists()) { + try (InputStream in = INSTANCE.getResourceAsStream(file.getName())) { + Files.copy(in, file.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + if (!kookConf.exists()) { +// try (InputStream in = INSTANCE.getResourceAsStream(kookConf.getParentFile().getName()+File.separator+kookConf.getName())) { + try (InputStream in = INSTANCE.getResourceAsStream(kookConf.getParentFile().getName()+"/"+kookConf.getName())) { + Files.copy(in, kookConf.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + } + loadConfig(); + if (!Config.getBotYamlVersion().equals("1.3.0")){ + try (InputStream in = INSTANCE.getResourceAsStream(botFile.getName())) { + Files.copy(in, kookConf.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (!Config.getConfigYamlVersion().equals("1.3.1")){ + try (InputStream in = INSTANCE.getResourceAsStream(configFile.getName())) { + Files.copy(in, kookConf.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (!Config.getReturnsYamlVersion().equals("1.2")){ + try (InputStream in = INSTANCE.getResourceAsStream(returnsFile.getName())) { + Files.copy(in, kookConf.toPath()); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static String getBotYamlVersion(){ + return getBotYaml().getString("Ver"); + } + + public static String getConfigYamlVersion(){ + return getConfigYaml().getString("Ver"); + } + + public static String getReturnsYamlVersion(){ + return getReturnsYaml().getString("Ver"); + } + + public static void loadConfig() throws IOException { + bot = ConfigurationProvider.getProvider(YamlConfiguration.class).load(botFile);; + config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); + returns = ConfigurationProvider.getProvider(YamlConfiguration.class).load(returnsFile); + } + + public static Configuration getBotYaml(){ + return bot; + } + + public static Configuration getConfigYaml() { + return config; + } + + public static Configuration getReturnsYaml() {return returns;} + + public static String getBotMode() { + return getBotYaml().getString("Bot.Mode").toLowerCase(); + } + public static String getCqBotHttp() { + return getBotYaml().getString("Bot.go-cqhttp.Http"); + } + public static String getCqBotToken() { + return getBotYaml().getString("Bot.go-cqhttp.Token"); + } + public static boolean getCqBotIsAccessToken() { + return getBotYaml().getBoolean("Bot.go-cqhttp.IsAccessToken"); + } + public static int getCqBotListenPort() { + return getBotYaml().getInt("Bot.go-cqhttp.ListenPort"); + } + public static String getKookBotToken() { + return getBotYaml().getString("Bot.Kook.Token"); + } + + public static List getGroupQQs(){ + return getBotYaml().getLongList("Groups"); + } + + public static List getAdmins() { + return getBotYaml().getLongList("Admins"); + } + + public static boolean Forwarding(){ + return getConfigYaml().getBoolean("Forwarding.enable"); + } + + public static boolean WhiteList(){ + return getConfigYaml().getBoolean("WhiteList.enable"); + } + + public static boolean JoinAndLeave(){ + return getConfigYaml().getBoolean("JoinAndLeave"); + } + + public static boolean Online(){ + return getConfigYaml().getBoolean("Online"); + } + + public static boolean SDR() {return getConfigYaml().getBoolean("SDR");} + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/DataBase.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/DataBase.java new file mode 100644 index 0000000..7ed48c2 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/config/DataBase.java @@ -0,0 +1,23 @@ +package me.regadpole.plumbot.config; + +import me.regadpole.plumbot.PlumBot; + +public class DataBase { + + public static String type() {return Config.getConfigYaml().getString("database.type");} + public static String sqlite_path() {return Config.getConfigYaml().getString("database.settings.sqlite.path").replace("%plugin_folder%", PlumBot.INSTANCE.getDataFolder().toPath().toString());} + public static String mysql_host() {return Config.getConfigYaml().getString("database.settings.mysql.host");} + public static String mysql_port() {return Config.getConfigYaml().getString("database.settings.mysql.port");} + public static String mysql_database() {return Config.getConfigYaml().getString("database.settings.mysql.database");} + public static String mysql_username() {return Config.getConfigYaml().getString("database.settings.mysql.username");} + public static String mysql_password() {return Config.getConfigYaml().getString("database.settings.mysql.password");} + public static String mysql_parameters() {return Config.getConfigYaml().getString("database.settings.mysql.parameters");} + public static long pool_connectionTimeout() {return Config.getConfigYaml().getLong("database.settings.pool.connectionTimeout");} + public static long pool_idleTimeout() {return Config.getConfigYaml().getLong("database.settings.pool.idleTimeout");} + public static long pool_maxLifetime() {return Config.getConfigYaml().getLong("database.settings.pool.maxLifetime");} + public static int pool_maximumPoolSize() {return Config.getConfigYaml().getInt("database.settings.pool.maximumPoolSize");} + public static long pool_keepaliveTime() {return Config.getConfigYaml().getLong("database.settings.pool.keepaliveTime");} + public static int pool_minimumIdle() {return Config.getConfigYaml().getInt("database.settings.pool.minimumIdle");} + public static String pool_connectionTestQuery() {return Config.getConfigYaml().getString("database.settings.pool.connectionTestQuery", "");} + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java new file mode 100644 index 0000000..bccb3df --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -0,0 +1,254 @@ +package me.regadpole.plumbot.event.kook; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.bot.KookBot; +import me.regadpole.plumbot.config.Args; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.event.server.ServerManager; +import me.regadpole.plumbot.internal.database.DatabaseManager; +import me.regadpole.plumbot.tool.StringTool; +import snw.jkook.event.EventHandler; +import snw.jkook.event.Listener; +import snw.jkook.event.channel.ChannelMessageEvent; +import snw.jkook.event.pm.PrivateMessageReceivedEvent; +import snw.jkook.event.user.UserLeaveGuildEvent; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class KookEvent implements Listener { + public KookEvent(KookBot kookBot, PlumBot plugin){ + kBot=kookBot; + this.plugin=plugin; + } + + KookBot kBot; + private PlumBot plugin; + String Prefix = Args.Prefix(); + + @EventHandler + public void onChannelMessageReceive(ChannelMessageEvent e) { + + for (long groupId:Config.getGroupQQs()) { + if (!e.getChannel().getId().equalsIgnoreCase(kBot.getChannel(groupId).getId())) return; + } + + Pattern pattern; + Matcher matcher; + + ArrayList groups = new ArrayList<>(); + for (long groupId:Config.getGroupQQs()) { + groups.add(kBot.getChannel(groupId).getId()); + } + + ArrayList admins = new ArrayList<>(); + for (long adminId:Config.getAdmins()) { + admins.add(kBot.getUser(adminId).getId()); + } + + String msg = e.getMessage().getComponent().toString(); + String groupID= e.getChannel().getId(); + String senderID = e.getMessage().getSender().getId(); + String senderName = e.getMessage().getSender().getNickName(e.getChannel().getGuild()); + String groupName = e.getChannel().getGuild().getName()+"/"+e.getChannel().getName(); + + pattern = Pattern.compile(" { + long nameForId = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (nameForId == 0L) { + e.getMessage().reply("尚未申请白名单"); + return; + } + DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单"); + }); + return; + } + + pattern = Pattern.compile(Prefix + "删除User白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String qq = matcher.group().replace(Prefix + "删除User白名单 ", ""); + if (qq.isEmpty()) { + e.getMessage().reply("QQ不能为空"); + return; + } + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + String idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName == null) { + e.getMessage().reply("尚未申请白名单"); + return; + } + DatabaseManager.removeBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单"); + }); + return; + } + + } + + if(msg.equals(Prefix+"帮助")) { + List messages = new LinkedList<>(); + StringBuilder stringBuilder = new StringBuilder(); + messages.add("成员命令:"); + messages.add(Prefix+"在线人数 查看服务器当前在线人数"); + messages.add(Prefix+"申请白名单 为自己申请白名单"); + messages.add(Prefix+"删除白名单 删除自己的白名单"); + messages.add("管理命令:"); + messages.add(Prefix+"删除白名单 删除指定游戏id的白名单"); + messages.add(Prefix+"删除User白名单 删除指定群成员的白名单"); + for (String message : messages) { + if (messages.get(messages.size() - 1).equalsIgnoreCase(message)) { + stringBuilder.append(message.replaceAll("§\\S", "")); + } else { + stringBuilder.append(message.replaceAll("§\\S", "")).append("\n"); + } + } + e.getMessage().reply(stringBuilder.toString()); + return; + } + + if(msg.equals(Prefix+"在线人数")) { + if(!Config.Online()){ + return; + } + e.getMessage().reply("当前在线:" + "("+plugin.getProxy().getPlayers().size()+"人)"+ServerManager.listOnlinePlayer()); + return; + } + + + pattern = Pattern.compile(Prefix + "申请白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); + if (PlayerName.isEmpty()) { + e.getMessage().reply("id不能为空"); + return; + } + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + if ((DatabaseManager.getBind(senderID, DataBase.type().toLowerCase(), PlumBot.getDatabase())!=null) || (DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()) != 0L)) { + e.getMessage().reply("绑定失败"); + return; + } + DatabaseManager.addBind(PlayerName, senderID, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功申请白名单"); + }); + return; + } + + pattern = Pattern.compile(Prefix + "删除白名单"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + String idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName == null || idForName.isEmpty()) { + e.getMessage().reply("您尚未申请白名单"); + return; + } + DatabaseManager.removeBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单"); + }); + return; + } + + if (Config.SDR()){ + String back = Config.getReturnsYaml().getString(msg); + if(back!=null){ + e.getMessage().reply(back); + return; + } + } + + if (!Config.Forwarding()){ + return; + } + + if (Args.ForwardingMode()==1 && groups.contains(groupID)){ + pattern = Pattern.compile(Args.ForwardingPrefix()+".*"); + matcher = pattern.matcher(msg); + if(!matcher.find()){ + return; + } + String fmsg = msg.replace(Args.ForwardingPrefix(), ""); + String name = StringTool.filterColor(senderName); + String smsg = StringTool.filterColor(fmsg); + plugin.getProxy().broadcast("§6" + "[" + groupName + "]" + "§a" + name + "§f" + ":" + smsg); + return; + } + + if(groups.contains(groupID)) { + String name = StringTool.filterColor(senderName); + String smsg = StringTool.filterColor(msg); + plugin.getProxy().broadcast("§6" + "[" + groupName + "]" + "§a" + name + "§f" + ":" + smsg); + } + + } + + @EventHandler + public void onPrivateMessageReceive(PrivateMessageReceivedEvent e) { + + ArrayList admins = new ArrayList<>(); + for (long adminId:Config.getAdmins()) { + admins.add(kBot.getUser(adminId).getId()); + } + + if(e.getMessage().toString().equals(Prefix+"在线人数")) { + if(!Config.Online()){ + return; + } + e.getMessage().reply("当前在线:" + "("+ plugin.getProxy().getPlayers().size()+"人)"+ ServerManager.listOnlinePlayer()); + return; + } + } + + @EventHandler + public void onGroupDecreaseNotice(UserLeaveGuildEvent e) { + String userId = e.getUser().getId(); + String groupId = e.getGuildId(); + String player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player == null) { + return; + } + DatabaseManager.removeBindid(player, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java new file mode 100644 index 0000000..1c942b5 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -0,0 +1,253 @@ +package me.regadpole.plumbot.event.qq; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.bot.QQBot; +import me.regadpole.plumbot.config.Args; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.event.server.ServerManager; +import me.regadpole.plumbot.internal.database.DatabaseManager; +import me.regadpole.plumbot.tool.StringTool; +import sdk.event.message.GroupMessage; +import sdk.event.message.PrivateMessage; +import sdk.event.notice.GroupDecreaseNotice; + +import java.util.LinkedList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class QQEvent { + + public QQEvent(PlumBot plugin){ + this.plugin=plugin; + } + + String Prefix = Args.Prefix(); + private PlumBot plugin; + + public void onFriendMessageReceive(PrivateMessage e){ + + QQBot bot = (QQBot) PlumBot.getBot(); + + if(e.getMessage().equals(Prefix+"在线人数")) { + if(!Config.Online()){ + return; + } + bot.sendMsg(false, "当前在线:" + "("+plugin.getProxy().getPlayers().size()+"人)"+ServerManager.listOnlinePlayer(), e.getUserId()); + } + } + + public void onGroupMessageReceive(GroupMessage e){ + + Pattern pattern; + Matcher matcher; + + QQBot bot = (QQBot) PlumBot.getBot(); + String msg = e.getMessage(); + long groupID= e.getGroupId(); + long senderID = e.getUserId(); + String senderName; + String groupName = bot.getGroupInfo(e.getGroupId()).getGroupName(); + + { + if (e.getSender().getCard().isEmpty()) { + senderName = e.getSender().getNickname(); + } else { + senderName = e.getSender().getCard(); + } + } + + pattern = Pattern.compile(" { + long nameForId = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (nameForId == 0L) { + bot.sendMsg(true, "尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单", groupID); + }); + return; + } + + pattern = Pattern.compile(Prefix + "删除User白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String qq = matcher.group().replace(Prefix + "删除User白名单 ", ""); + if (qq.isEmpty()) { + bot.sendMsg(true, "QQ不能为空", groupID); + return; + } + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + String idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName == null) { + bot.sendMsg(true, "尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单", groupID); + }); + return; + } + + } + + if(msg.equals(Prefix+"帮助")) { + List messages = new LinkedList<>(); + StringBuilder stringBuilder = new StringBuilder(); + messages.add("成员命令:"); + messages.add(Prefix+"在线人数 查看服务器当前在线人数"); + messages.add(Prefix+"申请白名单 为自己申请白名单"); + messages.add(Prefix+"删除白名单 删除自己的白名单"); + messages.add("管理命令:"); + messages.add(Prefix+"删除白名单 删除指定游戏id的白名单"); + messages.add(Prefix+"删除User白名单 删除指定群成员的白名单"); + for (String message : messages) { + if (messages.get(messages.size() - 1).equalsIgnoreCase(message)) { + stringBuilder.append(message.replaceAll("§\\S", "")); + } else { + stringBuilder.append(message.replaceAll("§\\S", "")).append("\n"); + } + } + bot.sendMsg(true, stringBuilder.toString(),groupID); + return; + } + + if(msg.equals(Prefix+"在线人数")) { + if(!Config.Online()){ + return; + } + bot.sendMsg(true, "当前在线:" + "("+plugin.getProxy().getPlayers().size()+"人)"+ServerManager.listOnlinePlayer(),groupID); + return; + } + + pattern = Pattern.compile(Prefix + "申请白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); + if (PlayerName.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); + return; + } + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + if ((DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()) != null) || (DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()) != 0L)) { + bot.sendMsg(true, "绑定失败", groupID); + return; + } + DatabaseManager.addBind(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单", groupID); + }); + return; + } + + pattern = Pattern.compile(Prefix + "删除白名单"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + String idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName == null || idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单", groupID); + }); + return; + } + + if (Config.SDR()){ + String back = Config.getReturnsYaml().getString(msg); + if(back!=null){ + bot.sendMsg(true, back,groupID); + return; + } + } + + if (!Config.Forwarding()){ + return; + } + + if (Args.ForwardingMode()==1 && Config.getGroupQQs().contains(groupID)){ + pattern = Pattern.compile(Args.ForwardingPrefix()+".*"); + matcher = pattern.matcher(msg); + if(!matcher.find()){ + return; + } + String fmsg = msg.replace(Args.ForwardingPrefix(), ""); + String name = StringTool.filterColor(senderName); + String smsg = StringTool.filterColor(fmsg); + pattern = Pattern.compile("\\[CQ:.*].*"); + matcher = pattern.matcher(smsg); + if (matcher.find()){ + String useMsg = smsg.replaceAll("\\[CQ:.*]", ""); + plugin.getProxy().broadcast("§6" + "[" + groupName + "]" + "§a" + name + "§f" + ":" + useMsg); + return; + } + plugin.getProxy().broadcast("§6" + "[" + groupName + "]" + "§a" + name + "§f" + ":" + smsg); + return; + } + + if(Config.getGroupQQs().contains(groupID)) { + String name = StringTool.filterColor(senderName); + String smsg = StringTool.filterColor(msg); + pattern = Pattern.compile("\\[CQ:.*].*"); + matcher = pattern.matcher(smsg); + if (matcher.find()){ + String useMsg = smsg.replaceAll("\\[CQ:.*]", ""); + plugin.getProxy().broadcast("§6" + "[" + groupName + "]" + "§a" + name + "§f" + ":" + useMsg); + return; + } + plugin.getProxy().broadcast("§6" + "[" + groupName + "]" + "§a" + name + "§f" + ":" + smsg); + } + + } + + public void onGroupDecreaseNotice(GroupDecreaseNotice e) { + long userId = e.getUserId(); + long groupId = e.getGroupId(); + String player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player == null) { + return; + } + DatabaseManager.removeBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + } + + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java new file mode 100644 index 0000000..9647105 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java @@ -0,0 +1,118 @@ +package me.regadpole.plumbot.event.server; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.Args; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.internal.database.DatabaseManager; +import me.regadpole.plumbot.tool.StringTool; +import net.md_5.bungee.api.connection.ProxiedPlayer; +import net.md_5.bungee.api.event.*; +import net.md_5.bungee.api.plugin.Listener; +import net.md_5.bungee.event.EventHandler; +import net.md_5.bungee.event.EventPriority; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ServerEvent implements Listener { + + private PlumBot plugin; + + public ServerEvent(PlumBot plugin){ + this.plugin=plugin; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onChat(ChatEvent event) { + + Pattern pattern; + Matcher matcher; + ProxiedPlayer player = ServerManager.getServerPlayer(event.getSender().getAddress()); + + if (!Config.Forwarding()){ + return; + } + String name = StringTool.filterColor(player.getDisplayName()); + String message = StringTool.filterColor(event.getMessage()); + if (Args.ForwardingMode() == 1) { + pattern = Pattern.compile(Args.ForwardingPrefix()+".*"); + matcher = pattern.matcher(message); + if(!matcher.find()){ + return; + } + String fmsg = matcher.group().replaceAll(Args.ForwardingPrefix(), ""); + List groups = Config.getGroupQQs(); + for (long groupID : groups){ + PlumBot.getBot().sendMsg(true, "[服务器]"+name+":"+fmsg,groupID); + } + return; + } + + List groups = Config.getGroupQQs(); + for (long groupID : groups){ + PlumBot.getBot().sendMsg(true, "[服务器]"+name+":"+message,groupID); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onPreLogin(ServerSwitchEvent event){ + ProxiedPlayer player = event.getPlayer(); + String name = player.getName(); + + if (Config.WhiteList()) { + plugin.getProxy().getScheduler().runAsync(plugin, () -> { + long qq; + qq = (DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase())); + if (qq == 0L) { + player.disconnect(Args.WhitelistKick()); + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", groupID); + } + return; + } + for (long groupID : Config.getGroupQQs()) { + if(!PlumBot.getBot().checkUserInGroup(qq, groupID)){ + player.disconnect(Args.WhitelistKick()); + List groups = Config.getGroupQQs(); + for (long group : groups) { + PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", group); + } + DatabaseManager.removeBind(String.valueOf(qq), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + return; + } + } + }); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onJoin(ServerConnectedEvent event){ + + String name = event.getPlayer().getName(); + + if (!Config.JoinAndLeave()){ + return; + } + List groups = Config.getGroupQQs(); + for (long groupID : groups){ + PlumBot.getBot().sendMsg(true, "玩家"+name+"加入游戏",groupID); + } + } + + @EventHandler + public void onQuit(PlayerDisconnectEvent event){ + + String name = StringTool.filterColor(event.getPlayer().getDisplayName()); + + if (!Config.JoinAndLeave()){ + return; + } + List groups = Config.getGroupQQs(); + for (long groupID : groups){ + PlumBot.getBot().sendMsg(true, "玩家"+name+"退出游戏",groupID); + } + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerManager.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerManager.java new file mode 100644 index 0000000..75765a2 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/event/server/ServerManager.java @@ -0,0 +1,26 @@ +package me.regadpole.plumbot.event.server; + +import me.regadpole.plumbot.PlumBot; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import java.net.InetSocketAddress; +import java.util.*; + +public class ServerManager { + + public static String listOnlinePlayer() { + List onlinePlayer = new LinkedList<>(); + for (ProxiedPlayer p : PlumBot.INSTANCE.getProxy().getPlayers()) { + onlinePlayer.add(p.getName()); + } + return Arrays.toString(onlinePlayer.toArray()).replace("\\[|\\]", ""); + } + + public static ProxiedPlayer getServerPlayer(InetSocketAddress address) { + LinkedHashMap playerConnectionMap = new LinkedHashMap<>(); + for (ProxiedPlayer p : PlumBot.INSTANCE.getProxy().getPlayers()) { + playerConnectionMap.put(p.getAddress(), p); + } + return playerConnectionMap.get(address); + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Dependencies.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Dependencies.java new file mode 100644 index 0000000..4b84928 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Dependencies.java @@ -0,0 +1,77 @@ +package me.regadpole.plumbot.internal; + +import me.regadpole.plumbot.internal.maven.MavenLibraries; +import me.regadpole.plumbot.internal.maven.MavenLibrary; + +import static me.regadpole.plumbot.internal.Dependencies.*; + +@MavenLibraries({ + @MavenLibrary(groupId = hutool.groupId, artifactId = hutool.artifactId, version = hutool.version), + @MavenLibrary(groupId = ws.groupId, artifactId = ws.artifactId, version = ws.version), + @MavenLibrary(groupId = juint.groupId, artifactId = juint.artifactId, version = juint.version), + @MavenLibrary(groupId = fastjson.groupId, artifactId = fastjson.artifactId, version = fastjson.version), + @MavenLibrary(groupId = common.groupId, artifactId = common.artifactId, version = common.version), + @MavenLibrary(groupId = lombok.groupId, artifactId = lombok.artifactId, version = lombok.version), + @MavenLibrary(groupId = HikariCP.groupId, artifactId = HikariCP.artifactId, version = HikariCP.version), + @MavenLibrary(groupId = MySQL.groupId, artifactId = MySQL.artifactId, version = MySQL.version), + @MavenLibrary(groupId = sqlite.groupId, artifactId = sqlite.artifactId, version = sqlite.version), + @MavenLibrary(groupId = kookbc.groupId, artifactId = kookbc.artifactId, version = kookbc.version), + @MavenLibrary(groupId = jsr305.groupId, artifactId = jsr305.artifactId, version = jsr305.version)}) +public class Dependencies { + public static class hutool{ + public static final String groupId = "cn.hutool"; + public static final String artifactId = "hutool-all"; + public static final String version = "5.8.21"; + + } + public static class ws{ + public static final String groupId = "org.java-websocket"; + public static final String artifactId = "Java-WebSocket"; + public static final String version = "1.5.3"; + } + public static class juint{ + public static final String groupId = "junit"; + public static final String artifactId = "junit"; + public static final String version = "4.13.2"; + } + public static class fastjson{ + public static final String groupId = "com.alibaba"; + public static final String artifactId = "fastjson"; + public static final String version = "2.0.32"; + } + public static class common{ + public static final String groupId = "org.apache.commons"; + public static final String artifactId = "commons-lang3"; + public static final String version = "3.12.0"; + } + public static class lombok{ + public static final String groupId = "org.projectlombok"; + public static final String artifactId = "lombok"; + public static final String version = "1.18.26"; + } + public static class HikariCP{ + public static final String groupId = "com.zaxxer"; + public static final String artifactId = "HikariCP"; + public static final String version = "4.0.3"; + } + public static class MySQL{ + public static final String groupId = "com.mysql"; + public static final String artifactId = "mysql-connector-j"; + public static final String version = "8.1.0"; + } + public static class sqlite{ + public static final String groupId = "org.xerial"; + public static final String artifactId = "sqlite-jdbc"; + public static final String version = "3.42.0.0"; + } + public static class kookbc{ + public static final String groupId = "com.github.SNWCreations"; + public static final String artifactId = "KookBC"; + public static final String version = "0.27.4"; + } + public static class jsr305{ + public static final String groupId = "com.google.code.findbugs"; + public static final String artifactId = "jsr305"; + public static final String version = "3.0.2"; + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Environment.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Environment.java new file mode 100644 index 0000000..37a0db3 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/Environment.java @@ -0,0 +1,10 @@ +package me.regadpole.plumbot.internal; + +import me.regadpole.plumbot.PlumBot; + +public final class Environment { + private final PlumBot plugin = PlumBot.INSTANCE; + public final String name = plugin.getDescription().getName(); + public final String version = plugin.getDescription().getVersion(); + public final String author = plugin.getDescription().getAuthor(); +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/Database.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/Database.java new file mode 100644 index 0000000..4529daa --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/Database.java @@ -0,0 +1,12 @@ +package me.regadpole.plumbot.internal.database; + +import java.sql.Connection; +import java.sql.SQLException; + +public interface Database { + void initialize() throws ClassNotFoundException; + + void close() throws SQLException; + + Connection getConnection() throws SQLException; +} \ No newline at end of file diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java new file mode 100644 index 0000000..a2c1870 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -0,0 +1,288 @@ +package me.regadpole.plumbot.internal.database; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.DataBase; + +import javax.annotation.Nullable; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +public class DatabaseManager { + + public static void start(){ + try { + switch (DataBase.type().toLowerCase()) { + case "sqlite": + default: { + PlumBot.INSTANCE.getLogger().info("Initializing SQLite database."); + PlumBot.INSTANCE.setDatabase(new SQLite()); + break; + } + case "mysql": { + PlumBot.INSTANCE.getLogger().info("Initializing MySQL database."); + PlumBot.INSTANCE.setDatabase(new MySQL()); + break; + } + } + PlumBot.getDatabase().initialize(); + } catch (ClassNotFoundException e) { + PlumBot.INSTANCE.getLogger().warning("Failed to initialize database, reason: " + e); + } + } + + public static void close(){ + PlumBot.INSTANCE.getLogger().info("Closing database."); + try { + PlumBot.getDatabase().close(); + } catch (SQLException e) { + PlumBot.INSTANCE.getLogger().warning("在关闭数据库时出现错误" + e); + } + + } + + public static void addBind(String id, String qq, String mode, Database db) { + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String selectid = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1"; + String selectqq = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1"; + String updateid = "UPDATE whitelist SET id='" + id + "' WHERE qq=" + qq + ";"; + String updateqq = "UPDATE whitelist SET qq=" + qq + " WHERE id='" + id + "';"; + String insert = "insert into whitelist values('" + id + "', " + qq + ");"; + + try { + Connection connection = db.getConnection(); + switch (mode) { + case "sqlite": + default: { + Statement statement = connection.createStatement(); + Statement statement1 = connection.createStatement(); + statement.executeUpdate(createTable); + + ResultSet resultSetid = statement.executeQuery(selectid); + ResultSet resultSetqq = statement1.executeQuery(selectqq); + + if (!resultSetid.isBeforeFirst() && resultSetqq.isBeforeFirst()) { + statement.executeUpdate(updateid); + } else if (resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { + statement.executeUpdate(updateqq); + } else if (!resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { + statement.executeUpdate(insert); + } + + resultSetid.close(); + resultSetqq.close(); + statement.close(); + statement1.close(); + connection.close(); + + break; + } + case "mysql": { + + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSetid = connection.prepareStatement(selectid).executeQuery(); + ResultSet resultSetqq = connection.prepareStatement(selectqq).executeQuery(); + + if (!resultSetid.isBeforeFirst() && resultSetqq.isBeforeFirst()) { + connection.prepareStatement(updateid).executeUpdate(); + } else if (resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { + connection.prepareStatement(updateqq).executeUpdate(); + } else if (!resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { + connection.prepareStatement(insert).executeUpdate(); + } + + resultSetid.close(); + resultSetqq.close(); + connection.close(); + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + + public static void removeBindid(String id,String mode, Database db) { + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String select = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1;"; + String delete = "DELETE FROM whitelist WHERE id='" + id + "';"; + + try { + Connection connection = db.getConnection(); + switch (mode) { + case "sqlite": + default: { + Statement statement = connection.createStatement(); + statement.executeUpdate(createTable); + + ResultSet resultSet = statement.executeQuery(select); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + statement.executeUpdate(delete); + } + resultSet.close(); + statement.close(); + connection.close(); + + break; + } + case "mysql": { + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSet = connection.prepareStatement(select).executeQuery(); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + connection.prepareStatement(delete).executeUpdate(); + } + resultSet.close(); + connection.close(); + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public static void removeBind(String qq,String mode, Database db) { + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; + String delete = "DELETE FROM whitelist WHERE qq=" + qq+";"; + + try { + Connection connection = db.getConnection(); + switch (mode){ + case "sqlite": + default: { + Statement statement = connection.createStatement(); + statement.executeUpdate(createTable); + + // 如果没有找到记录为false,找到就是true + ResultSet resultSet = statement.executeQuery(select); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + statement.executeUpdate(delete); + } + resultSet.close(); + statement.close(); + connection.close(); + + break; + } + case "mysql": { + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSet = connection.prepareStatement(select).executeQuery(); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + connection.prepareStatement(delete).executeUpdate(); + } + resultSet.close(); + connection.close(); + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public static long getBindId(String id,String mode, Database db) { + long qq = 0L; + + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String select = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1;"; + + try { + Connection connection = db.getConnection(); + switch (mode){ + case "mysql": { + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSet = connection.prepareStatement(select).executeQuery(); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + qq = resultSet.getLong("qq"); + resultSet.close(); + connection.close(); + break; + } + case "sqlite": + default: { + Statement statement = connection.createStatement(); + statement.executeUpdate(createTable); + + ResultSet resultSet = statement.executeQuery(select); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + qq = resultSet.getLong("qq"); + resultSet.close(); + statement.close(); + connection.close(); + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + return qq; + } + + @Nullable + public static String getBind(String qq,String mode, Database db) { + String id = null; + + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; + + try { + Connection connection = db.getConnection(); + switch (mode){ + case "mysql": { + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSet = connection.prepareStatement(select).executeQuery(); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + id = resultSet.getString("id"); + resultSet.close(); + connection.close(); + break; + } + case "sqlite": + default: { + Statement statement = connection.createStatement(); + statement.executeUpdate(createTable); + + ResultSet resultSet = statement.executeQuery(select); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + id = resultSet.getString("id"); + resultSet.close(); + statement.close(); + connection.close(); + + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + return id; + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java new file mode 100644 index 0000000..c71bcb8 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java @@ -0,0 +1,60 @@ +package me.regadpole.plumbot.internal.database; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.DataBase; + +import java.sql.Connection; +import java.sql.SQLException; + +public class MySQL implements Database{ + + private static HikariDataSource hds; // MySQL + @Override + public void initialize() { + String driver = null; + try{ + Class.forName("com.mysql.cj.jdbc.Driver"); + driver = "com.mysql.cj.jdbc.Driver"; + } catch (ClassNotFoundException ignored) { + try { + Class.forName("com.mysql.jdbc.Driver"); + driver = "com.mysql.jdbc.Driver"; + } catch (ClassNotFoundException ignored1) { + PlumBot.INSTANCE.getLogger().info("无法找到数据库驱动"); + } + } + + HikariConfig config = new HikariConfig(); + config.setDriverClassName(driver); + config.setPoolName("PlumBot-MySQL"); + config.setJdbcUrl("jdbc:mysql://" + DataBase.mysql_host() +":"+ DataBase.mysql_port() + "/" + DataBase.mysql_database() + DataBase.mysql_parameters()); + config.setUsername(DataBase.mysql_username()); + config.setPassword(DataBase.mysql_password()); + if (!DataBase.pool_connectionTestQuery().isEmpty()){ + config.setConnectionTestQuery(DataBase.pool_connectionTestQuery()); + } + config.setConnectionTimeout(DataBase.pool_connectionTimeout()); + config.setIdleTimeout(DataBase.pool_idleTimeout()); + config.setMaxLifetime(DataBase.pool_maxLifetime()); + config.setMaximumPoolSize(DataBase.pool_maximumPoolSize()); + config.setKeepaliveTime(DataBase.pool_keepaliveTime()); + config.setMinimumIdle(DataBase.pool_minimumIdle()); + config.addDataSourceProperty("cachePrepStmts", "true" ); + config.addDataSourceProperty("prepStmtCacheSize", "250" ); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048" ); + + hds = new HikariDataSource(config); + } + + @Override + public void close() { + hds.close(); + } + + @Override + public Connection getConnection() throws SQLException { + return hds.getConnection(); + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/SQLite.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/SQLite.java new file mode 100644 index 0000000..60dffb7 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/database/SQLite.java @@ -0,0 +1,56 @@ +package me.regadpole.plumbot.internal.database; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.DataBase; + +import java.io.File; +import java.sql.Connection; +import java.sql.SQLException; + +public class SQLite implements Database{ + + private static HikariDataSource hds; // MySQL + + @Override + public void initialize() { + + String driver = null; + try{ + Class.forName("org.sqlite.JDBC"); + driver = "org.sqlite.JDBC"; + } catch (ClassNotFoundException ignored) { + PlumBot.INSTANCE.getLogger().info("无法找到数据库驱动"); + } + + HikariConfig config = new HikariConfig(); + config.setDriverClassName(driver); + config.setPoolName("PlumBot-SQLite"); + config.setJdbcUrl("jdbc:sqlite:" + new File(DataBase.sqlite_path()).getPath()); + if (!DataBase.pool_connectionTestQuery().isEmpty()){ + config.setConnectionTestQuery(DataBase.pool_connectionTestQuery()); + } + config.setConnectionTimeout(DataBase.pool_connectionTimeout()); + config.setIdleTimeout(DataBase.pool_idleTimeout()); + config.setMaxLifetime(DataBase.pool_maxLifetime()); + config.setMaximumPoolSize(DataBase.pool_maximumPoolSize()); + config.setKeepaliveTime(DataBase.pool_keepaliveTime()); + config.setMinimumIdle(DataBase.pool_minimumIdle()); + config.addDataSourceProperty("cachePrepStmts", "true" ); + config.addDataSourceProperty("prepStmtCacheSize", "250" ); + config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048" ); + + hds = new HikariDataSource(config); + } + + @Override + public void close() { + hds.close(); + } + + @Override + public Connection getConnection() throws SQLException { + return hds.getConnection(); + } +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/kook/KookClient.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/kook/KookClient.java new file mode 100644 index 0000000..ab61756 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/kook/KookClient.java @@ -0,0 +1,62 @@ +package me.regadpole.plumbot.internal.kook; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import snw.jkook.command.CommandManager; +import snw.jkook.command.JKookCommand; +import snw.jkook.config.ConfigurationSection; +import snw.kookbc.SharedConstants; +import snw.kookbc.impl.CoreImpl; +import snw.kookbc.impl.KBCClient; +import snw.kookbc.impl.command.internal.PluginsCommand; +import snw.kookbc.impl.entity.builder.EntityBuilder; +import snw.kookbc.impl.entity.builder.MessageBuilder; +import snw.kookbc.impl.event.EventFactory; +import snw.kookbc.impl.network.NetworkClient; +import snw.kookbc.impl.storage.EntityStorage; +import snw.kookbc.interfaces.network.NetworkSystem; +import snw.kookbc.util.ReturnNotNullFunction; + +import java.io.File; + +public class KookClient extends KBCClient { + public KookClient(CoreImpl core, ConfigurationSection config, File pluginsFolder, String token) { + super(core, config, pluginsFolder, token); + } + + public KookClient(CoreImpl core, ConfigurationSection config, File pluginsFolder, String token, @NotNull String networkMode) { + super(core, config, pluginsFolder, token, networkMode); + } + + public KookClient(CoreImpl core, ConfigurationSection config, File pluginsFolder, String token, @Nullable ReturnNotNullFunction commandManager, @Nullable ReturnNotNullFunction networkClient, @Nullable ReturnNotNullFunction storage, @Nullable ReturnNotNullFunction entityBuilder, @Nullable ReturnNotNullFunction msgBuilder, @Nullable ReturnNotNullFunction eventFactory, @Nullable ReturnNotNullFunction networkSystem) { + super(core, config, pluginsFolder, token, commandManager, networkClient, storage, entityBuilder, msgBuilder, eventFactory, networkSystem); + } + + @Override + protected void registerInternal() { + ConfigurationSection commandConfig = this.getConfig().getConfigurationSection("internal-commands"); + if (commandConfig == null) { + commandConfig = this.getConfig().createSection("internal-commands"); + } + + if (commandConfig.getBoolean("plugins", true)) { + this.registerPluginsCommand(); + } + } + + @Override + protected void registerStopCommand() { + + } + + @Override + protected void registerPluginsCommand() { + (new JKookCommand("plugins")).setDescription("获取已安装到此 " + SharedConstants.IMPL_NAME + " 实例的插件列表。").setExecutor(new PluginsCommand(this)).register(this.getInternalPlugin()); + } + + @Override + protected void registerHelpCommand() { + } + + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/LibraryLoader.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/LibraryLoader.java new file mode 100644 index 0000000..b0efc09 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/LibraryLoader.java @@ -0,0 +1,202 @@ +/* + * This file is part of helper, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.regadpole.plumbot.internal.maven; + +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.Args; + +import java.io.File; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.util.Objects; + +/** + * Resolves {@link MavenLibrary} annotations for a class, and loads the dependency + * into the classloader. + */ +public final class LibraryLoader { + + private static PlumBot plugin = PlumBot.INSTANCE; + + @SuppressWarnings("Guava") + private static final Supplier URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) plugin.getClass().getClassLoader())); + + /** + * Resolves all {@link MavenLibrary} annotations on the given object. + * + * @param object the object to load libraries for. + */ + public static void loadAll(Object object) { + loadAll(object.getClass()); + } + + /** + * Resolves all {@link MavenLibrary} annotations on the given class. + * + * @param clazz the class to load libraries for. + */ + public static void loadAll(Class clazz) { + MavenLibrary[] libs = clazz.getDeclaredAnnotationsByType(MavenLibrary.class); + if (libs == null) { + return; + } + + for (MavenLibrary lib : libs) { + load(lib.groupId(), lib.artifactId(), lib.version()); + } + } + + public static void load(String groupId, String artifactId, String version) { + String repo = Args.Maven(); + if ("".equals(repo)) repo = "https://repo1.maven.org/maven2"; + load(groupId, artifactId, version, repo); + } + + public static void load(String groupId, String artifactId, String version, String repoUrl) { + load(new Dependency(groupId, artifactId, version, repoUrl)); + } + + public static void load(Dependency d) { + plugin.getLogger().info(String.format("Loading dependency %s:%s:%s from %s", d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getRepoUrl())); + String name = d.getArtifactId() + "-" + d.getVersion(); + + File saveLocation = new File(getLibFolder(), name + ".jar"); + if (!saveLocation.exists()) { + + try { + plugin.getLogger().info("Dependency '" + name + "' is not already in the libraries folder. Attempting to download..."); + URL url = d.getUrl(); + + try (InputStream is = url.openStream()) { + Files.copy(is, saveLocation.toPath()); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + plugin.getLogger().info("Dependency '" + name + "' successfully downloaded."); + } + + if (!saveLocation.exists()) { + throw new RuntimeException("Unable to download dependency: " + d.toString()); + } + + try { + URL_INJECTOR.get().addURL(saveLocation.toURI().toURL()); + } catch (Exception e) { + throw new RuntimeException("Unable to load dependency: " + saveLocation.toString(), e); + } + + plugin.getLogger().info("Loaded dependency '" + name + "' successfully."); + } + + private static File getLibFolder() { + File pluginDataFolder = plugin.getDataFolder(); + File libs = new File(pluginDataFolder, "libraries"); + libs.mkdirs(); + return libs; + } + + public static final class Dependency { + private final String groupId; + private final String artifactId; + private final String version; + private final String repoUrl; + + public Dependency(String groupId, String artifactId, String version, String repoUrl) { + this.groupId = Objects.requireNonNull(groupId, "groupId"); + this.artifactId = Objects.requireNonNull(artifactId, "artifactId"); + this.version = Objects.requireNonNull(version, "version"); + this.repoUrl = Objects.requireNonNull(repoUrl, "repoUrl"); + } + + public String getGroupId() { + return this.groupId; + } + + public String getArtifactId() { + return this.artifactId; + } + + public String getVersion() { + return this.version; + } + + public String getRepoUrl() { + return this.repoUrl; + } + + public URL getUrl() throws MalformedURLException { + String repo = this.repoUrl; + if (!repo.endsWith("/")) { + repo += "/"; + } + repo += "%s/%s/%s/%s-%s.jar"; + + String url = String.format(repo, this.groupId.replace(".", "/"), this.artifactId, this.version, this.artifactId, this.version); + return new URL(url); + } + + @Override + public boolean equals(Object o) { + if (o == this) return true; + if (!(o instanceof Dependency)) return false; + final Dependency other = (Dependency) o; + return this.getGroupId().equals(other.getGroupId()) && + this.getArtifactId().equals(other.getArtifactId()) && + this.getVersion().equals(other.getVersion()) && + this.getRepoUrl().equals(other.getRepoUrl()); + } + + @Override + public int hashCode() { + final int PRIME = 59; + int result = 1; + result = result * PRIME + this.getGroupId().hashCode(); + result = result * PRIME + this.getArtifactId().hashCode(); + result = result * PRIME + this.getVersion().hashCode(); + result = result * PRIME + this.getRepoUrl().hashCode(); + return result; + } + + @Override + public String toString() { + return "LibraryLoader.Dependency(" + + "groupId=" + this.getGroupId() + ", " + + "artifactId=" + this.getArtifactId() + ", " + + "version=" + this.getVersion() + ", " + + "repoUrl=" + this.getRepoUrl() + ")"; + } + } + + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibraries.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibraries.java new file mode 100644 index 0000000..b764d5f --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibraries.java @@ -0,0 +1,42 @@ +/* + * This file is part of helper, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.regadpole.plumbot.internal.maven; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * Annotation to indicate the required libraries for a class. + */ +@Documented +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface MavenLibraries { + + @Nonnull + MavenLibrary[] value(); + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibrary.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibrary.java new file mode 100644 index 0000000..ab8aa96 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/MavenLibrary.java @@ -0,0 +1,64 @@ +/* + * This file is part of helper, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.regadpole.plumbot.internal.maven; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * Annotation to indicate a required library for a class. + */ +@Documented +@Repeatable(MavenLibraries.class) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface MavenLibrary { + + /** + * The group id of the library + * + * @return the group id of the library + */ + @Nonnull + String groupId(); + + /** + * The artifact id of the library + * + * @return the artifact id of the library + */ + @Nonnull + String artifactId(); + + /** + * The version of the library + * + * @return the version of the library + */ + @Nonnull + String version(); + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/URLClassLoaderAccess.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/URLClassLoaderAccess.java new file mode 100644 index 0000000..2be02cb --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/internal/maven/URLClassLoaderAccess.java @@ -0,0 +1,176 @@ +/* + * This file is part of helper, licensed under the MIT License. + * + * Copyright (c) lucko (Luck) + * Copyright (c) contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.regadpole.plumbot.internal.maven; + +import javax.annotation.Nonnull; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Collection; + +/** + * Provides access to {@link URLClassLoader}#addURL. + */ +public abstract class URLClassLoaderAccess { + + /** + * Creates a {@link URLClassLoaderAccess} for the given class loader. + * + * @param classLoader the class loader + * @return the access object + */ + static URLClassLoaderAccess create(URLClassLoader classLoader) { + if (Reflection.isSupported()) { + return new Reflection(classLoader); + } else if (Unsafe.isSupported()) { + return new Unsafe(classLoader); + } else { + return Noop.INSTANCE; + } + } + + private final URLClassLoader classLoader; + + protected URLClassLoaderAccess(URLClassLoader classLoader) { + this.classLoader = classLoader; + } + + + /** + * Adds the given URL to the class loader. + * + * @param url the URL to add + */ + public abstract void addURL(@Nonnull URL url); + + /** + * Accesses using reflection, not supported on Java 9+. + */ + private static class Reflection extends URLClassLoaderAccess { + private static final Method ADD_URL_METHOD; + + static { + Method addUrlMethod; + try { + addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); + addUrlMethod.setAccessible(true); + } catch (Exception e) { + addUrlMethod = null; + } + ADD_URL_METHOD = addUrlMethod; + } + + private static boolean isSupported() { + return ADD_URL_METHOD != null; + } + + Reflection(URLClassLoader classLoader) { + super(classLoader); + } + + @Override + public void addURL(@Nonnull URL url) { + try { + ADD_URL_METHOD.invoke(super.classLoader, url); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } + } + + /** + * Accesses using sun.misc.Unsafe, supported on Java 9+. + * + * @author Vaishnav Anil (https://github.com/slimjar/slimjar) + */ + private static class Unsafe extends URLClassLoaderAccess { + private static final sun.misc.Unsafe UNSAFE; + + static { + sun.misc.Unsafe unsafe; + try { + Field unsafeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = (sun.misc.Unsafe) unsafeField.get(null); + } catch (Throwable t) { + unsafe = null; + } + UNSAFE = unsafe; + } + + private static boolean isSupported() { + return UNSAFE != null; + } + + private final Collection unopenedURLs; + private final Collection pathURLs; + + @SuppressWarnings("unchecked") + Unsafe(URLClassLoader classLoader) { + super(classLoader); + + Collection unopenedURLs; + Collection pathURLs; + try { + Object ucp = fetchField(URLClassLoader.class, classLoader, "ucp"); + unopenedURLs = (Collection) fetchField(ucp.getClass(), ucp, "unopenedUrls"); + pathURLs = (Collection) fetchField(ucp.getClass(), ucp, "path"); + } catch (Throwable e) { + unopenedURLs = null; + pathURLs = null; + } + this.unopenedURLs = unopenedURLs; + this.pathURLs = pathURLs; + } + + private static Object fetchField(final Class clazz, final Object object, final String name) throws NoSuchFieldException { + Field field = clazz.getDeclaredField(name); + long offset = UNSAFE.objectFieldOffset(field); + return UNSAFE.getObject(object, offset); + } + + @Override + public void addURL(@Nonnull URL url) { + this.unopenedURLs.add(url); + this.pathURLs.add(url); + } + } + + private static class Noop extends URLClassLoaderAccess { + private static final Noop INSTANCE = new Noop(); + + private Noop() { + super(null); + } + + @Override + public void addURL(@Nonnull URL url) { + throw new UnsupportedOperationException(); + } + } + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/metrics/Metrics.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/metrics/Metrics.java new file mode 100644 index 0000000..0fbeda4 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/metrics/Metrics.java @@ -0,0 +1,757 @@ +package me.regadpole.plumbot.metrics; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import net.md_5.bungee.api.plugin.Plugin; +import net.md_5.bungee.config.Configuration; +import net.md_5.bungee.config.ConfigurationProvider; +import net.md_5.bungee.config.YamlConfiguration; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

+ * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'n', 'g', 'e', 'e', 'c', 'o', 'r', 'd'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bungeecord"; + + // The plugin + private final Plugin plugin; + + // The plugin id + private final int pluginId; + + // Is bStats enabled on this server? + private boolean enabled; + + // The uuid of the server + private String serverUUID; + + // Should failed requests be logged? + private boolean logFailedRequests = false; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // A list with all known metrics class objects including this one + private static final List knownMetricsInstances = new ArrayList<>(); + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + * @param pluginId The id of the plugin. + * It can be found at What is my plugin id? + */ + public Metrics(Plugin plugin, int pluginId) { + this.plugin = plugin; + this.pluginId = pluginId; + + try { + loadConfig(); + } catch (IOException e) { + // Failed to load configuration + plugin.getLogger().log(Level.WARNING, "Failed to load bStats config!", e); + return; + } + + // We are not allowed to send data about this server :( + if (!enabled) { + return; + } + + Class usedMetricsClass = getFirstBStatsClass(); + if (usedMetricsClass == null) { + // Failed to get first metrics class + return; + } + if (usedMetricsClass == getClass()) { + // We are the first! :) + linkMetrics(this); + startSubmitting(); + } else { + // We aren't the first so we link to the first metrics class + try { + usedMetricsClass.getMethod("linkMetrics", Object.class).invoke(null, this); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Failed to link to first metrics class " + usedMetricsClass.getName() + "!", e); + } + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + plugin.getLogger().log(Level.WARNING, "Chart cannot be null"); + } + charts.add(chart); + } + + /** + * Links an other metrics class with this class. + * This method is called using Reflection. + * + * @param metrics An object of the metrics class to link. + */ + public static void linkMetrics(Object metrics) { + knownMetricsInstances.add(metrics); + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.addProperty("pluginName", pluginName); + data.addProperty("id", pluginId); + data.addProperty("pluginVersion", pluginVersion); + + JsonArray customCharts = new JsonArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JsonObject chart = customChart.getRequestJsonObject(plugin.getLogger(), logFailedRequests); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.add("customCharts", customCharts); + + return data; + } + + private void startSubmitting() { + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into the initial and second delay. + // WARNING: You must not modify and part of this Metrics class, including the submit delay or frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + plugin.getProxy().getScheduler().schedule(plugin, this::submitData, initialDelay, TimeUnit.MILLISECONDS); + plugin.getProxy().getScheduler().schedule( + plugin, this::submitData, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount = Math.min(plugin.getProxy().getOnlineCount(), 500); + int onlineMode = plugin.getProxy().getConfig().isOnlineMode() ? 1 : 0; + String bungeecordVersion = plugin.getProxy().getVersion(); + int managedServers = plugin.getProxy().getServers().size(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JsonObject data = new JsonObject(); + + data.addProperty("serverUUID", serverUUID); + + data.addProperty("playerAmount", playerAmount); + data.addProperty("managedServers", managedServers); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bungeecordVersion", bungeecordVersion); + + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); + + final JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Object metrics : knownMetricsInstances) { + try { + Object plugin = metrics.getClass().getMethod("getPluginData").invoke(metrics); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + + data.add("plugins", pluginData); + + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats!", e); + } + } + } + + /** + * Loads the bStats configuration. + * + * @throws IOException If something did not work :( + */ + private void loadConfig() throws IOException { + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + bStatsFolder.mkdirs(); + File configFile = new File(bStatsFolder, "config.yml"); + if (!configFile.exists()) { + writeFile(configFile, + "#bStats collects some data for plugin authors like how many servers are using their plugins.", + "#To honor their work, you should not disable it.", + "#This has nearly no effect on the server performance!", + "#Check out https://bStats.org/ to learn more :)", + "enabled: true", + "serverUuid: \"" + UUID.randomUUID() + "\"", + "logFailedRequests: false", + "logSentData: false", + "logResponseStatusText: false"); + } + + Configuration configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile); + + // Load configuration + enabled = configuration.getBoolean("enabled", true); + serverUUID = configuration.getString("serverUuid"); + logFailedRequests = configuration.getBoolean("logFailedRequests", false); + logSentData = configuration.getBoolean("logSentData", false); + logResponseStatusText = configuration.getBoolean("logResponseStatusText", false); + } + + /** + * Gets the first bStat Metrics class. + * + * @return The first bStats metrics class. + */ + private Class getFirstBStatsClass() { + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + bStatsFolder.mkdirs(); + File tempFile = new File(bStatsFolder, "temp.txt"); + + try { + String className = readFile(tempFile); + if (className != null) { + try { + // Let's check if a class with the given name exists. + return Class.forName(className); + } catch (ClassNotFoundException ignored) { } + } + writeFile(tempFile, getClass().getName()); + return getClass(); + } catch (IOException e) { + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Failed to get first bStats class!", e); + } + return null; + } + } + + /** + * Reads the first line of the file. + * + * @param file The file to read. Cannot be null. + * @return The first line of the file or {@code null} if the file does not exist or is empty. + * @throws IOException If something did not work :( + */ + private String readFile(File file) throws IOException { + if (!file.exists()) { + return null; + } + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + return bufferedReader.readLine(); + } + } + + /** + * Writes a String to a file. It also adds a note for the user, + * + * @param file The file to write to. Cannot be null. + * @param lines The lines to write. + * @throws IOException If something did not work :( + */ + private void writeFile(File file, String... lines) throws IOException { + try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) { + for (String line : lines) { + bufferedWriter.write(line); + bufferedWriter.newLine(); + } + } + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + + StringBuilder builder = new StringBuilder(); + + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + private final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) { + JsonObject chart = new JsonObject(); + chart.addProperty("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.add("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + logger.log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JsonObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObject value = new JsonObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.addProperty(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.add(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.addProperty("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.addProperty(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JsonArray categoryValues = new JsonArray(); + categoryValues.add(new JsonPrimitive(entry.getValue())); + values.add(entry.getKey(), categoryValues); + } + data.add("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObject data = new JsonObject(); + JsonObject values = new JsonObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JsonArray categoryValues = new JsonArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(new JsonPrimitive(categoryValue)); + } + values.add(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.add("values", values); + return data; + } + + } + +} diff --git a/plumbot-bungee/src/main/java/me/regadpole/plumbot/tool/StringTool.java b/plumbot-bungee/src/main/java/me/regadpole/plumbot/tool/StringTool.java new file mode 100644 index 0000000..1a78f94 --- /dev/null +++ b/plumbot-bungee/src/main/java/me/regadpole/plumbot/tool/StringTool.java @@ -0,0 +1,16 @@ +package me.regadpole.plumbot.tool; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class StringTool { + + public static String filterColor(String text){ + + String regEx = "§[0-9a-zA-Z]"; + Pattern p = Pattern.compile(regEx); + Matcher matcher = p.matcher(text); + return matcher.replaceAll("").trim(); + + } +} diff --git a/plumbot-bungee/src/main/java/sdk/anno/Param.java b/plumbot-bungee/src/main/java/sdk/anno/Param.java new file mode 100644 index 0000000..1a2d2c8 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/anno/Param.java @@ -0,0 +1,13 @@ +package sdk.anno; + +import java.lang.annotation.*; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +@Documented +/** + * 网络请求时需要用到,对应的value是参数名称 + */ +public @interface Param { + String value() default ""; +} diff --git a/plumbot-bungee/src/main/java/sdk/client/Client.java b/plumbot-bungee/src/main/java/sdk/client/Client.java new file mode 100644 index 0000000..e158d8f --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/Client.java @@ -0,0 +1,280 @@ +package sdk.client; + +import cn.hutool.http.HttpRequest; +import cn.hutool.json.JSONArray; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import me.regadpole.plumbot.PlumBot; +import sdk.anno.Param; +import sdk.config.CQConfig; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 客户端父类 集成公用方法 + */ +public class Client { + +// private static Log log = LogFactory.get(); + + protected CQConfig config; + + public Client(CQConfig config) { + this.config = config; + } + + /** + * 获取url + * + * @return + */ + protected String getUrl() { + StackTraceElement stacks = (new Throwable()).getStackTrace()[1]; + String methodName = stacks.getMethodName(); + return getUrl(this.upperCharToUnderLine(methodName)); + } + + + /** + * 获取url + * + * @return + */ + protected String getUrl(String uri) { + StringBuilder builder = new StringBuilder(); + builder.append(config.getUrl()); + builder.append("/"); + builder.append(uri); + if (config.getIsAccessToken()) { + //使用token鉴权 + builder.append("?access_token="); + builder.append(config.getToken()); + } + return builder.toString(); + } + + /** + * 创建基础的post请求 + * + * @param url + * @return + */ + public static HttpRequest createPostRequest(String url) { + return HttpRequest.post(url); + } + + /** + * 创建基础的get请求 + * + * @param url + * @return + */ + public static HttpRequest createGetRequest(String url) { + return HttpRequest.get(url); + } + + /** + * 根据调用方的@Param进行封装参数 并构建get请求 + * + * @param url + * @param params 需要写入实际类型,例如ArrayList不能写List(调用方) + * @return + */ + public static HttpRequest createGetRequest(String url, Object... params) { + try { + StackTraceElement traceElement = getCaller();//获取调用的类 + Map paramMap = createParamMap(traceElement, params); + + HttpRequest get = HttpRequest.get(url); + get.form(paramMap); + return get; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 根据调用方的@Param进行封装参数 并构建post请求 + * + * @param url + * @param params + * @return + */ + public static HttpRequest createPostRequest(String url, Object... params) { + try { + StackTraceElement traceElement = getCaller();//获取调用的类 + Map paramMap = createParamMap(traceElement, params); + + HttpRequest post = HttpRequest.post(url); + post.form(paramMap); + return post; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 构建请求参数 + * + * @param traceElement + * @param params + * @return + */ + private static Map createParamMap(StackTraceElement traceElement, Object... params) { + try { + Class aClass = Class.forName(traceElement.getClassName()); + Map paramMap = new HashMap<>(); + + Class[] classes = new Class[params.length]; + for (int i = 0; i < params.length; i++) { + classes[i] = params[i].getClass();//获取参数类型 + } + Method method = aClass.getMethod(traceElement.getMethodName(), classes);//获取对应方法 + Annotation[][] annotations = method.getParameterAnnotations(); + for (int i = 0; i < annotations.length; i++) { + paramMap.put(((Param) annotations[i][0]).value(), params[i]);//封装请求参数 + } + return paramMap; + } catch (Exception e) { +// log.error(e); + PlumBot.INSTANCE.getLogger().log(Level.WARNING, e.getMessage(), e); + } + return null; + } + + /** + * 将data反序列化为list类型的数据 + * + * @param body + * @param tClass + * @param + * @return + */ + public static List toListByData(String body, Class tClass) { + JSONObject obj = JSONUtil.parseObj(body); + JSONArray array = obj.getJSONArray("data"); + return toList(array, tClass); + } + + /** + * 将数据反序列化为list类型的数据 + * + * @param array + * @param tClass + * @param + * @return + */ + public static List toList(JSONArray array, Class tClass) { + if (array == null) { + return null; + } + return JSONUtil.toList(array, tClass); + } + + /** + * 将data反序列化为泛型对应类型的数据 + * + * @param body + * @param tClass + * @param + * @return + */ + public static T toBeanByData(String body, Class tClass) { + JSONObject obj = JSONUtil.parseObj(body); + JSONObject data = obj.getJSONObject("data"); + return toBean(data, tClass); + } + + /** + * 将数据反序列化为泛型对应类型的数据 + * + * @param object + * @param tClass + * @param + * @return + */ + public static T toBean(JSONObject object, Class tClass) { + if (object == null || "".equals(object)) { + return null; + } + return JSONUtil.toBean(object, tClass); + } + + /** + * 获取调用方 + * + * @return + */ + private static StackTraceElement getCaller() { + StackTraceElement stacks = (new Throwable()).getStackTrace()[2]; + return stacks; + } + + /** + * 获取data下面的某个值,并反序列化为对象 + * + * @param name + * @param json + * @param tClass + * @return + */ + public static T getDataValue(String name, String json, Class tClass) { + JSONObject object = JSONUtil.parseObj(json); + if (object == null || "".equals(object)) { + return null; + } + return (T) object.getJSONObject("data").get(name); + } + + /** + * 获取data下面的某个值,并反序列化为list + * + * @param name + * @param json + * @param tClass + * @return + */ + public static List getListValue(String name, String json, Class tClass) { + JSONObject object = JSONUtil.parseObj(json); + if (object == null || "".equals(object)) { + return null; + } + JSONArray jsonArray = object.getJSONObject("data").getJSONArray(name); + return JSONUtil.toList(jsonArray, tClass); + } + + /** + * 将大写字符串改为下划线+小写 + * + * @param param 例如: sendPrivateMessage + * @return 返回: send_private_message + */ + public static String upperCharToUnderLine(String param) { + Pattern p = Pattern.compile("[A-Z]"); + if (param == null || param.equals("")) { + return ""; + } + StringBuilder builder = new StringBuilder(param); + Matcher mc = p.matcher(param); + int i = 0; + while (mc.find()) { + builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase()); + i++; + } + + if ('_' == builder.charAt(0)) { + builder.deleteCharAt(0); + } + return builder.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/ClientFactory.java b/plumbot-bungee/src/main/java/sdk/client/ClientFactory.java new file mode 100644 index 0000000..2380e2e --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/ClientFactory.java @@ -0,0 +1,48 @@ +package sdk.client; + +import sdk.client.impl.*; +import sdk.config.CQConfig; + +/** + * 封装了客户端生成方法 + */ +public class ClientFactory { + private CQConfig config; + + public ClientFactory(CQConfig config) { + this.config = config; + } + + public AdminClient createAdminClient() { + return new AdminClient(config); + } + + public GroupClient createGroupClient() { + return new GroupClient(config); + } + + public MessageClient createMessageClient() { + return new MessageClient(config); + } + + public UserClient createUserClient() { + return new UserClient(config); + } + + public GroupAdminClient createGroupAdminClient() { + return new GroupAdminClient(config); + } + + public FileClient createGroupFileClient() { + return new FileClient(config); + } + + public void setConfig(CQConfig config) { + this.config = config; + } + + public CQConfig getConfig() { + return config; + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/client/impl/AdminClient.java b/plumbot-bungee/src/main/java/sdk/client/impl/AdminClient.java new file mode 100644 index 0000000..036db15 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/impl/AdminClient.java @@ -0,0 +1,155 @@ +package sdk.client.impl; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import sdk.anno.Param; +import sdk.client.Client; +import sdk.client.response.*; +import sdk.config.CQConfig; + +import java.util.List; + +/** + * CQHTTP管理相关的封装 + */ +public final class AdminClient extends Client { + public AdminClient(CQConfig config) { + super(config); + } + + /** + * 获取登录号信息 + * + * @return + */ + public LoginInfo getLoginInfo() { + HttpRequest request = this.createGetRequest(this.getUrl()); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), LoginInfo.class); + } + + /** + * 检查是否可以发送图片 + * + * @return + */ + public Boolean canSendImage() { + HttpRequest request = this.createGetRequest(this.getUrl()); + String body = request.execute().body(); + Boolean bool = JSONUtil.parseObj(body).getJSONObject("data").getBool("yes"); + return bool; + } + + /** + * 检查是否可以发送语音 + * + * @return + */ + public Boolean canSendRecord() { + HttpRequest request = this.createGetRequest(this.getUrl()); + String body = request.execute().body(); + Boolean bool = JSONUtil.parseObj(body).getJSONObject("data").getBool("yes"); + return bool; + } + + + /** + * 获取版本信息 + * + * @return + */ + public CQVersionInfo getVersionInfo() { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url); + String body = request.execute().body(); + return this.toBeanByData(body, CQVersionInfo.class); + } + + /** + * 重启cqhttp + * + * @param delay 延迟毫秒数 + */ + public void setRestart(@Param("delay") Long delay) { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url, delay); + request.execute(); + } + + /** + * 中文分词 + * + * @param content 内容 + * @return + */ + public List getWordSlices(@Param("content") String content) { + HttpRequest request = this.createPostRequest(this.getUrl(".get_word_slices"), content); + String body = request.execute().body(); + return this.getListValue("slices", body, String.class); + } + + /** + * 图片转文字 + * + * @param image + * @return + */ + public OcrImage ocrImage(@Param("image") String image) { + HttpRequest request = this.createPostRequest(this.getUrl(), image); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), OcrImage.class); + } + + /** + * 获取运行状态 + * + * @return + */ + public CQStatus getStatus() { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), CQStatus.class); + } + + /** + * 重载事件过滤器 + */ + public void reloadEventFilter() { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url); + request.execute(); + } + + /** + * 获取在线列表 + * + * @param noCache 是否使用缓存 + * @return + */ + public List getOnlineClients(@Param("no_cache") Boolean noCache) { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url, noCache); + String body = request.execute().body(); + JSONObject object = JSONUtil.parseObj(body); + if (object.getInt("retcode") == 0) { + return JSONUtil.toList(object.getJSONObject("data").getJSONArray("clients"), OnlineClient.class); + } + return null; + } + + /** + * 检查链接安全性 + * + * @param url 需要检查的链接 + * @return 安全等级, 1: 安全 2: 未知 3: 危险 + */ + public Integer checkUrlSafely(@Param("url") String url) { + HttpRequest request = this.createPostRequest(this.getUrl(), url); + HttpResponse response = request.execute(); + return this.getDataValue("level", response.body(), Integer.class); + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/client/impl/FileClient.java b/plumbot-bungee/src/main/java/sdk/client/impl/FileClient.java new file mode 100644 index 0000000..e0c46d1 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/impl/FileClient.java @@ -0,0 +1,131 @@ +package sdk.client.impl; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import sdk.anno.Param; +import sdk.client.Client; +import sdk.client.response.GroupFileSystemInfo; +import sdk.client.response.GroupFiles; +import sdk.config.CQConfig; + +/** + * 文件相关接口 + */ +public final class FileClient extends Client { + public FileClient(CQConfig config) { + super(config); + } + + /** + * 下载文件到缓存目录 + * + * @param url 资源地址 + * @return 绝对路径 + */ + public String downloadFile(@Param("url") String url) { + return this.downloadFile(url, 0, new String[]{}); + } + + /** + * 下载文件到缓存目录 + * + * @param url 资源地址 + * @param threadCount 下载线程数 + * @param headers 自定义请求头 + * @return 绝对路径 + */ + public String downloadFile(@Param("url") String url, + @Param("thread_count") Integer threadCount, + @Param("headers") String[] headers) { + HttpRequest request = this.createPostRequest(this.getUrl(), url, threadCount, headers); + String body = request.execute().body(); + JSONObject object = JSONUtil.parseObj(body); + if (object.getInt("retcode") == 0) { + return object.getJSONObject("data").getStr("file"); + } + return null; + } + + /** + * 上传图片 + * + * @param groupId 群号 + * @param file 文件路径 全路径 + * @param name 上传后的名称 + */ + public void uploadGroupFile(@Param("group_id") Long groupId, + @Param("file") String file, + @Param("name") String name) { + this.uploadGroupFile(groupId, file, name, ""); + } + + /** + * 上传图片 + * + * @param groupId 群号 + * @param file 文件路径 全路径 + * @param name 上传后的名称 + * @param folder 父目录id 不传上传到根目录 + */ + public void uploadGroupFile(@Param("group_id") Long groupId, + @Param("file") String file, + @Param("name") String name, + @Param("folder") String folder) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, file, name, folder); + request.execute(); + } + + /** + * 获取群文件系统信息 + * + * @param groupId + * @return + */ + public GroupFileSystemInfo getGroupFileSystemInfo(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupFileSystemInfo.class); + } + + /** + * 获取群根目录文件列表 + * + * @param groupId 群号 + * @return + */ + public GroupFiles getGroupRootFiles(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupFiles.class); + } + + /** + * 获取群目录文件列表 + * + * @param groupId 群号 + * @param folderId 文件夹id + * @return + */ + public GroupFiles getGroupFilesByFolder(@Param("group_id") Long groupId, @Param("folder_id") String folderId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, folderId); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupFiles.class); + } + + /** + * 获取群文件资源链接 + * + * @param groupId 群号 + * @param fileId 文件id + * @param busid 文件类型 + */ + public String getGroupFileUrl(@Param("group_id") Long groupId, + @Param("file_id") String fileId, + @Param("busid") Integer busid) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, fileId, busid); + HttpResponse response = request.execute(); + return this.getDataValue("url",response.body(),String.class); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/impl/GroupAdminClient.java b/plumbot-bungee/src/main/java/sdk/client/impl/GroupAdminClient.java new file mode 100644 index 0000000..b8d27ee --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/impl/GroupAdminClient.java @@ -0,0 +1,303 @@ +package sdk.client.impl; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import sdk.anno.Param; +import sdk.client.Client; +import sdk.client.response.EssenceMsg; +import sdk.client.response.GroupAtAllRemain; +import sdk.config.CQConfig; +import sdk.event.message.GroupMessage; + +import java.util.List; + +/** + * 群聊管理相关接口 + */ +public final class GroupAdminClient extends Client { + + public GroupAdminClient(CQConfig config) { + super(config); + } + + /** + * 将用户移出群聊 + * + * @param groupId 群号 + * @param userId 要移出的qq号 + */ + public void setGroupKick(Long groupId, Long userId) { + setGroupKick(groupId, userId, false); + } + + /** + * 将用户移出群聊 + * + * @param groupId 群号 + * @param userId 要移出的qq号 + * @param rejectAddRequest 是否接收该用户申请 + */ + public void setGroupKick(@Param("group_id") Long groupId, + @Param("user_id") Long userId, + @Param("reject_add_request") Boolean rejectAddRequest) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, userId, rejectAddRequest); + request.execute(); + } + + /** + * 群组单人禁言 + * + * @param groupId 群号 + * @param userId 要禁言的qq号 + * @param duration 禁言时长, 单位秒, 0 表示取消禁言 + */ + public HttpResponse setGroupBan(@Param("group_id") Long groupId, + @Param("user_id") Long userId, + @Param("duration") Long duration) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, userId, duration); + return request.execute(); + } + + /** + * 取消禁言 + * + * @param groupId 群号 + * @param userId 要取消禁言的qq号 + */ + public HttpResponse removeGroupBan(Long groupId, Long userId) { + return setGroupBan(groupId, userId, 0L); + } + + /** + * 群组匿名用户禁言 + * + * @param groupId 群号 + * @param flag 消息上报的flag + * @param duration 禁言时长, 单位秒, + */ + public void setGroupAnonymousBan(@Param("group_id") Long groupId, + @Param("anonymous_flag") String flag, + @Param("duration") Long duration) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, flag, duration); + request.execute(); + } + + /** + * 群组匿名用户禁言 + * + * @param groupId 群号 + * @param anonymous 消息上报的anonymous对象 + * @param duration 禁言时长, 单位秒, + */ + public void setGroupAnonymousBan(@Param("group_id") Long groupId, + @Param("anonymous") GroupMessage.Anonymous anonymous, + @Param("duration") Long duration) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, anonymous, duration); + request.execute(); + } + + /** + * 关闭全体禁言 + * + * @param groupId 群号 + */ + public void closeGroupWholeBan(Long groupId) { + setGroupWholeBan(groupId, false); + } + + /** + * 开启全体禁言 + * + * @param groupId 群号 + */ + public void startGroupWholeBan(Long groupId) { + setGroupWholeBan(groupId, true); + } + + /** + * 群聊全体禁言 + * + * @param groupId 群号 + * @param enable true开启 false关闭 + */ + public void setGroupWholeBan(@Param("group_id") Long groupId, @Param("enable") Boolean enable) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, enable); + request.execute(); + } + + /** + * 取消群管理员 + * + * @param groupId 群号 + * @param userId 要取消管理员的qq号 + */ + public void removeGroupAdmin(Long groupId, Long userId) { + setGroupAdmin(groupId, userId, false); + } + + /** + * 添加群管理员 + * + * @param groupId 群号 + * @param userId 要添加管理员的qq号 + */ + public void addGroupAdmin(Long groupId, Long userId) { + setGroupAdmin(groupId, userId, true); + } + + /** + * 设置群管理员 + * + * @param groupId 群号 + * @param userId 要设置管理员的qq号 + * @param enable true设置 false取消 + */ + public void setGroupAdmin(@Param("group_id") Long groupId, + @Param("user_id") Long userId, + @Param("enable") Boolean enable) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, userId, enable); + request.execute(); + } + + /** + * 删除群名片 ( 群备注 ) + * + * @param groupId 群号 + * @param userId QQ号 + */ + public void removeGroupCard(Long groupId, Long userId) { + setGroupCard(groupId, userId, ""); + } + + /** + * 设置群名片 ( 群备注 ) + * + * @param groupId 群号 + * @param userId QQ号 + * @param card 备注 不填时删除 + */ + public void setGroupCard(@Param("group_id") Long groupId, + @Param("user_id") Long userId, + @Param("card") String card) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, userId, card); + request.execute(); + } + + /** + * 设置群名 + * + * @param groupId 群号 + * @param groupName 群名 + */ + public void setGroupName(@Param("group_id") Long groupId, @Param("group_name") String groupName) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, groupName); + request.execute(); + } + + /** + * 解散群组 群主才能操作 + * + * @param groupId 群号 + */ + public void setGroupLeave(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl()); + request.form("group_id", groupId); + request.form("is_dismiss", true); + request.execute(); + } + + /** + * 删除专属头衔 + * + * @param groupId 群号 + * @param userId qq号 + */ + public void removeGroupSpecialTitle(Long groupId, Long userId) { + setGroupSpecialTitle(groupId, userId, ""); + } + + /** + * 设置专属头衔 + * + * @param groupId 群号 + * @param userId qq号 + * @param specialTitle 专属头衔, 不填或空字符串表示删除专属头衔 + */ + public void setGroupSpecialTitle(@Param("group_id") Long groupId, + @Param("user_id") Long userId, + @Param("special_title") String specialTitle) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, userId, specialTitle); + request.execute(); + } + + /** + * 设置群头像 + * + * @param groupId 群号 + * @param file 文件 绝对路径,网络路径,base64 + * @param cache 通过网络 URL 发送时有效, 1表示使用缓存, 0关闭关闭缓存, 默认 为1 + */ + public void setGroupPortrait(@Param("group_id") Long groupId, + @Param("file") String file, + @Param("cache") Integer cache) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, file, cache); + request.execute(); + } + + /** + * 获取群 @全体成员 剩余次数 + * + * @param groupId 群号 + * @return + */ + public GroupAtAllRemain getGroupAtAllRemain(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupAtAllRemain.class); + } + + /** + * 发送群公告 + * + * @param groupId 群号 + * @param content 公告内容 + */ + public void sendGroupNotice(@Param("group_id") Long groupId, @Param("content") String content) { + HttpRequest request = this.createPostRequest(this.getUrl("/_send_group_notice"), groupId, content); + request.execute(); + } + + /** + * 设置精华消息 + * 需要管理员权限 + * + * @param messageId 消息id + */ + public void setEssenceMsg(@Param("message_id") Integer messageId) { + HttpRequest request = this.createPostRequest(this.getUrl(), messageId); + request.execute(); + } + + /** + * 移除精华消息 + * + * @param messageId 消息id + */ + public void deleteEssenceMsg(@Param("message_id") Integer messageId) { + HttpRequest request = this.createPostRequest(this.getUrl(), messageId); + request.execute(); + } + + /** + * 获取精华消息列表 + * + * @param groupId + * @return + */ + public List getEssenceMsgList(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId); + String body = request.execute().body(); + return this.toListByData(body, EssenceMsg.class); + } +} + diff --git a/plumbot-bungee/src/main/java/sdk/client/impl/GroupClient.java b/plumbot-bungee/src/main/java/sdk/client/impl/GroupClient.java new file mode 100644 index 0000000..a741c2f --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/impl/GroupClient.java @@ -0,0 +1,150 @@ +package sdk.client.impl; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import sdk.anno.Param; +import sdk.client.Client; +import sdk.client.response.GroupHonorInfo; +import sdk.client.response.GroupInfo; +import sdk.client.response.GroupMemberInfo; +import sdk.client.response.GroupSystemMsg; +import sdk.config.CQConfig; +import sdk.event.message.GroupMessage; +import sdk.type.HonorType; + +import java.util.List; + +/** + * 群聊相关接口 + */ +public final class GroupClient extends Client { + public GroupClient(CQConfig config) { + super(config); + } + + /** + * 退出群 + * + * @param groupId 群号 + */ + public void setGroupLeave(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl()); + request.form("group_id", groupId); + request.execute(); + } + + /** + * 获取群信息 + * + * @param groupId + * @return + */ + public GroupInfo getGroupInfo(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId); + String body = request.execute().body(); + return this.toBeanByData(body, GroupInfo.class); + } + + /** + * 获取群列表 + * + * @return + */ + public List getGroupList() { + HttpRequest request = this.createPostRequest(this.getUrl()); + HttpResponse response = request.execute(); + return this.toListByData(response.body(), GroupInfo.class); + } + + + /** + * 获取群成员信息 + * + * @param groupId 群号 + * @param userId qq号 + * @param noCache 是否缓存 + * @return + */ + public GroupMemberInfo getGroupMemberInfo(@Param("group_id") Long groupId, + @Param("user_id") Long userId, + @Param("no_cache") Boolean noCache) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, userId, noCache); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupMemberInfo.class); + } + + /** + * 获取群成员列表 + * + * @param groupId 群号 + * @return + */ + public List getGroupMemberList(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId); + HttpResponse response = request.execute(); + return this.toListByData(response.body(), GroupMemberInfo.class); + } + + + /** + * 获取群荣誉 + * + * @param groupId 群号 + * @param honorType 获取类型 + * @return + */ + public GroupHonorInfo getGroupHonorInfo(@Param("group_id") Long groupId, @Param("honor_type") HonorType honorType) { + return getGroupHonorInfo(groupId, honorType.getValue()); + } + + /** + * 获取群荣誉 + * + * @param groupId 群号 + * @param type 获取类型 + * @return + */ + public GroupHonorInfo getGroupHonorInfo(@Param("group_id") Long groupId, @Param("type") String type) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, type); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupHonorInfo.class); + } + + /** + * 获取群系统消息 + * + * @return + */ + public GroupSystemMsg getGroupSystemMsg() { + HttpRequest request = this.createPostRequest(this.getUrl()); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), GroupSystemMsg.class); + } + + /** + * 获取群消息历史记录 + * + * @param groupId 群号 + * @return 最近19条消息 + */ + public List getGroupMsgHistory(@Param("group_id") Long groupId) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, 0L); + HttpResponse response = request.execute(); + return this.getListValue("messages", response.body(), GroupMessage.class); + } + + + /** + * 获取群消息历史记录 + * + * @param groupId 群号 + * @param messageSeq 消息序号 + * @return 最近19条消息 + */ + public List getGroupMsgHistory(@Param("group_id") Long groupId, @Param("message_seq") Long messageSeq) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, messageSeq); + HttpResponse response = request.execute(); + return this.getListValue("messages", response.body(), GroupMessage.class); + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/client/impl/MessageClient.java b/plumbot-bungee/src/main/java/sdk/client/impl/MessageClient.java new file mode 100644 index 0000000..5126a31 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/impl/MessageClient.java @@ -0,0 +1,159 @@ +package sdk.client.impl; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import sdk.anno.Param; +import sdk.client.Client; +import sdk.client.response.CQFile; +import sdk.client.response.ForwardMessage; +import sdk.client.response.ForwardNode; +import sdk.client.response.Message; +import sdk.config.CQConfig; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 消息相关接口 + */ +public final class MessageClient extends Client { + + public MessageClient(CQConfig config) { + super(config); + } + + /** + * 获取消息 + * + * @param messageId + * @return + */ + public Message getMsg(@Param("message_id") Integer messageId) { + HttpRequest request = this.createPostRequest(this.getUrl(), messageId); + HttpResponse response = request.execute(); + String body = response.body(); + return this.toBeanByData(body, Message.class); + } + + /** + * 获取合并转发内容 + * + * @param messageId + */ + public List getForwardMsg(@Param("message_id") String messageId) { + HttpRequest request = this.createPostRequest(this.getUrl(), messageId); + String body = request.execute().body(); + JSONObject parseObj = JSONUtil.parseObj(body); + return this.toList(parseObj.getJSONObject("data").getJSONArray("messages"), ForwardMessage.class); + } + + /** + * 发送合并消息 群 + * + * @param groupId + * @param messages + * @return + */ + public void sendGroupForwardMsg(@Param("group_id") Long groupId, @Param("messages") ArrayList messages) { + HttpRequest request = this.createPostRequest(this.getUrl()); + Map map = new HashMap<>(); + map.put("group_id",groupId); + map.put("messages",messages); + request.body(JSONUtil.toJsonStr(map)); + request.execute(); + } + + /** + * 撤回消息 + * + * @param messageId + */ + public void deleteMsg(@Param("message_id") Integer messageId) { + HttpRequest request = this.createPostRequest(this.getUrl(), messageId); + request.execute(); + } + + /** + * 发送私聊消息 + * + * @param groupId 群号 + * @param message 要发送的内容 + * @return 消息id + */ + public Integer sendGroupMsg(Long groupId, String message) { + return sendGroupMsg(groupId, message, true); + } + + /** + * 发送私聊消息 + * + * @param groupId 群号 + * @param message 要发送的内容 + * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 + * @return 消息id + */ + public Integer sendGroupMsg(@Param("group_id") Long groupId, @Param("message") String message, @Param("auto_escape") Boolean autoEscape) { + HttpRequest request = this.createPostRequest(this.getUrl(), groupId, message, autoEscape); + HttpResponse response = request.execute(); + + return this.getDataValue("message_id", response.body(), Integer.class); + } + + /** + * 发送私聊消息 + * + * @param userId 对方 QQ 号 + * @param message 要发送的内容 + * @return 消息id + */ + public Integer sendPrivateMsg(Long userId, String message) { + return sendPrivateMsg(userId, message, true); + } + + /** + * 发送私聊消息 + * + * @param userId 对方 QQ 号 + * @param message 要发送的内容 + * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 + * @return 消息id + */ + public Integer sendPrivateMsg(Long userId, String message, Boolean autoEscape) { + return sendPrivateMsg(userId, 0L, message, autoEscape); + } + + /** + * 发送私聊消息 + * + * @param userId 对方 QQ 号 + * @param groupId 主动发起临时会话群号(机器人本身必须是管理员/群主) + * @param message 要发送的内容 + * @param autoEscape 消息内容是否作为纯文本发送 ( 即不解析 CQ 码 ) , 只在 message 字段是字符串时有效 + * @return 消息id + */ + public Integer sendPrivateMsg(@Param("user_id") Long userId, + @Param("group_id") Long groupId, + @Param("message") String message, + @Param("auto_escape") Boolean autoEscape) { + HttpRequest request = this.createPostRequest(this.getUrl(), userId, groupId, message, autoEscape); + HttpResponse response = request.execute(); + return this.getDataValue("message_id", response.body(), Integer.class); + } + + /** + * 获取图片 + * + * @param file + * @return + */ + public CQFile getImage(@Param("file") String file) { + HttpRequest request = this.createPostRequest(this.getUrl(), file); + HttpResponse response = request.execute(); + String body = response.body(); + return this.toBeanByData(body, CQFile.class); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/impl/UserClient.java b/plumbot-bungee/src/main/java/sdk/client/impl/UserClient.java new file mode 100644 index 0000000..3e1abfd --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/impl/UserClient.java @@ -0,0 +1,111 @@ +package sdk.client.impl; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import sdk.anno.Param; +import sdk.client.Client; +import sdk.client.response.Friend; +import sdk.client.response.StrangerInfo; +import sdk.client.response.VipInfo; +import sdk.config.CQConfig; + +import java.util.List; + +/** + * 用户相关接口 + */ +public final class UserClient extends Client { + public UserClient(CQConfig config) { + super(config); + } + + /** + * 处理好友申请 + * + * @param flag 加好友请求的 flag(需从上报的数据中获得) + * @param approve true同意,false拒绝 + */ + public void setFriendAddRequest(String flag, Boolean approve) { + setFriendAddRequest(flag, approve, ""); + } + + /** + * 处理好友申请 + * + * @param flag 加好友请求的 flag(需从上报的数据中获得) + * @param approve true同意,false拒绝 + * @param reason 添加后的好友备注 + */ + public void setFriendAddRequest(@Param("flag") String flag, + @Param("approve") Boolean approve, + @Param("reason") String reason) { + HttpRequest request = this.createPostRequest(this.getUrl(), flag, approve, reason); + request.execute(); + } + + /** + * 处理申请/邀请群聊 + * + * @param flag 加群请求的 flag(需从上报的数据中获得) + * @param subType add 或 invite, 请求类型(需要和上报消息中的 sub_type 字段相符) + * @param approve true同意,false拒绝 + */ + public void setGroupAddRequest(String flag, String subType, Boolean approve) { + setGroupAddRequest(flag, subType, approve, ""); + } + + /** + * 处理申请/邀请群聊 + * + * @param flag 加群请求的 flag(需从上报的数据中获得) + * @param subType add 或 invite, 请求类型(需要和上报消息中的 sub_type 字段相符) + * @param approve true同意,false拒绝 + * @param reason 拒绝理由 + */ + public void setGroupAddRequest(@Param("flag") String flag, + @Param("sub_type") String subType, + @Param("approve") Boolean approve, + @Param("reason") String reason) { + HttpRequest request = this.createPostRequest(this.getUrl(), flag, subType, approve, reason); + request.execute(); + } + + + /** + * 获取陌生人信息 + * + * @param userId qq号 + * @return + */ + public StrangerInfo getStrangerInfo(@Param("user_id") Long userId) { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url, userId); + String body = request.execute().body(); + return this.toBeanByData(body, StrangerInfo.class); + } + + /** + * 获取好友列表 + * + * @return + */ + public List getFriendList() { + String url = this.getUrl(); + HttpRequest request = this.createPostRequest(url); + String body = request.execute().body(); + return this.toListByData(body, Friend.class); + } + + /** + * 获取vip信息 + * + * @param userId qq号 + * @return + */ + public VipInfo getVipInfo(@Param("user_id") Long userId) { + HttpRequest request = this.createPostRequest(this.getUrl("_get_vip_info"),userId); + HttpResponse response = request.execute(); + return this.toBeanByData(response.body(), VipInfo.class); + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/CQFile.java b/plumbot-bungee/src/main/java/sdk/client/response/CQFile.java new file mode 100644 index 0000000..4955edf --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/CQFile.java @@ -0,0 +1,43 @@ +package sdk.client.response; + +/** + * 文件 + */ +public class CQFile { + private Long size; + private String filename; + private String url; + + public Long getSize() { + return size; + } + + public void setSize(Long size) { + this.size = size; + } + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + return "CQFile{" + + "size=" + size + + ", filename='" + filename + '\'' + + ", url='" + url + '\'' + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/CQStatus.java b/plumbot-bungee/src/main/java/sdk/client/response/CQStatus.java new file mode 100644 index 0000000..7c47cae --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/CQStatus.java @@ -0,0 +1,162 @@ +package sdk.client.response; + +/** + * go-cqhttp状态 + */ +public class CQStatus { + private Boolean appInitialized;// true + private Boolean appEnabled;//原 CQHTTP 字段, 恒定为 true + private Boolean pluginsGood;//原 CQHTTP 字段, 恒定为 true + private Boolean appGood;//原 CQHTTP 字段, 恒定为 true + private Boolean online;//表示BOT是否在线 + private Boolean good;//online + private Statistics stat;//运行统计 + + public Boolean getAppInitialized() { + return appInitialized; + } + + public void setAppInitialized(Boolean appInitialized) { + this.appInitialized = appInitialized; + } + + public Boolean getAppEnabled() { + return appEnabled; + } + + public void setAppEnabled(Boolean appEnabled) { + this.appEnabled = appEnabled; + } + + public Boolean getPluginsGood() { + return pluginsGood; + } + + public void setPluginsGood(Boolean pluginsGood) { + this.pluginsGood = pluginsGood; + } + + public Boolean getAppGood() { + return appGood; + } + + public void setAppGood(Boolean appGood) { + this.appGood = appGood; + } + + public Boolean getOnline() { + return online; + } + + public void setOnline(Boolean online) { + this.online = online; + } + + public Boolean getGood() { + return good; + } + + public void setGood(Boolean good) { + this.good = good; + } + + public Statistics getStat() { + return stat; + } + + public void setStat(Statistics stat) { + this.stat = stat; + } + + @Override + public String toString() { + return "CQStatus{" + + "appInitialized=" + appInitialized + + ", appEnabled=" + appEnabled + + ", pluginsGood=" + pluginsGood + + ", appGood=" + appGood + + ", online=" + online + + ", good=" + good + + ", stat=" + stat + + '}'; + } + + public class Statistics { + private Long packetReceived;// 收到的数据包总数 + private Long packetSent;// 发送的数据包总数 + private Long packetLost;// 数据包丢失总数 + private Long messageReceived;// 接受信息总数 + private Long messageSent;// 发送信息总数 + private Long disconnectTimes;// TCP 链接断开次数 + private Long lostTimes;//账号掉线次数 + + public Long getPacketReceived() { + return packetReceived; + } + + public void setPacketReceived(Long packetReceived) { + this.packetReceived = packetReceived; + } + + public Long getPacketSent() { + return packetSent; + } + + public void setPacketSent(Long packetSent) { + this.packetSent = packetSent; + } + + public Long getPacketLost() { + return packetLost; + } + + public void setPacketLost(Long packetLost) { + this.packetLost = packetLost; + } + + public Long getMessageReceived() { + return messageReceived; + } + + public void setMessageReceived(Long messageReceived) { + this.messageReceived = messageReceived; + } + + public Long getMessageSent() { + return messageSent; + } + + public void setMessageSent(Long messageSent) { + this.messageSent = messageSent; + } + + public Long getDisconnectTimes() { + return disconnectTimes; + } + + public void setDisconnectTimes(Long disconnectTimes) { + this.disconnectTimes = disconnectTimes; + } + + public Long getLostTimes() { + return lostTimes; + } + + public void setLostTimes(Long lostTimes) { + this.lostTimes = lostTimes; + } + + @Override + public String toString() { + return "Statistics{" + + "packetReceived=" + packetReceived + + ", packetSent=" + packetSent + + ", packetLost=" + packetLost + + ", messageReceived=" + messageReceived + + ", messageSent=" + messageSent + + ", disconnectTimes=" + disconnectTimes + + ", lostTimes=" + lostTimes + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/CQVersionInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/CQVersionInfo.java new file mode 100644 index 0000000..4f1ac4c --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/CQVersionInfo.java @@ -0,0 +1,153 @@ +package sdk.client.response; + +/** + * go-cqhttp版本 + */ +public class CQVersionInfo { + private String appName;//应用标识, 如 go-cqhttp 固定值 + private String app_Version;//应用版本, 如 v0.9.40-fix4 + private String appFullName;//应用完整名称 + private String protocolVersion;//v11 OneBot 标准版本 固定值 + private String coolqEdition;//pro 原Coolq版本 固定值 + private String coolDirectory; + private Boolean goCqhttp;//是否为go-cqhttp 固定值 + private String pluginVersion;// 4.15.0 固定值 + private Integer pluginBuildNumber;//固定值 + private String pluginBuildConfiguration;//release 固定值 + private String runtimeVersion;// + private String runtimeOs;// + private String version;//应用版本, 如 v0.9.40-fix4 + private Integer protocol;// 0/1/2/3/-1 当前登陆使用协议类型 + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getApp_Version() { + return app_Version; + } + + public void setApp_Version(String app_Version) { + this.app_Version = app_Version; + } + + public String getAppFullName() { + return appFullName; + } + + public void setAppFullName(String appFullName) { + this.appFullName = appFullName; + } + + public String getProtocolVersion() { + return protocolVersion; + } + + public void setProtocolVersion(String protocolVersion) { + this.protocolVersion = protocolVersion; + } + + public String getCoolqEdition() { + return coolqEdition; + } + + public void setCoolqEdition(String coolqEdition) { + this.coolqEdition = coolqEdition; + } + + public String getCoolDirectory() { + return coolDirectory; + } + + public void setCoolDirectory(String coolDirectory) { + this.coolDirectory = coolDirectory; + } + + public Boolean getGoCqhttp() { + return goCqhttp; + } + + public void setGoCqhttp(Boolean goCqhttp) { + this.goCqhttp = goCqhttp; + } + + public String getPluginVersion() { + return pluginVersion; + } + + public void setPluginVersion(String pluginVersion) { + this.pluginVersion = pluginVersion; + } + + public Integer getPluginBuildNumber() { + return pluginBuildNumber; + } + + public void setPluginBuildNumber(Integer pluginBuildNumber) { + this.pluginBuildNumber = pluginBuildNumber; + } + + public String getPluginBuildConfiguration() { + return pluginBuildConfiguration; + } + + public void setPluginBuildConfiguration(String pluginBuildConfiguration) { + this.pluginBuildConfiguration = pluginBuildConfiguration; + } + + public String getRuntimeVersion() { + return runtimeVersion; + } + + public void setRuntimeVersion(String runtimeVersion) { + this.runtimeVersion = runtimeVersion; + } + + public String getRuntimeOs() { + return runtimeOs; + } + + public void setRuntimeOs(String runtimeOs) { + this.runtimeOs = runtimeOs; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Integer getProtocol() { + return protocol; + } + + public void setProtocol(Integer protocol) { + this.protocol = protocol; + } + + @Override + public String toString() { + return "CQVersionInfo{" + + "appName='" + appName + '\'' + + ", app_Version='" + app_Version + '\'' + + ", appFullName='" + appFullName + '\'' + + ", protocolVersion='" + protocolVersion + '\'' + + ", coolqEdition='" + coolqEdition + '\'' + + ", coolDirectory='" + coolDirectory + '\'' + + ", goCqhttp=" + goCqhttp + + ", pluginVersion='" + pluginVersion + '\'' + + ", pluginBuildNumber=" + pluginBuildNumber + + ", pluginBuildConfiguration='" + pluginBuildConfiguration + '\'' + + ", runtimeVersion='" + runtimeVersion + '\'' + + ", runtimeOs='" + runtimeOs + '\'' + + ", version='" + version + '\'' + + ", protocol=" + protocol + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/EssenceMsg.java b/plumbot-bungee/src/main/java/sdk/client/response/EssenceMsg.java new file mode 100644 index 0000000..c441f96 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/EssenceMsg.java @@ -0,0 +1,83 @@ +package sdk.client.response; + +/** + * 精华消息 + */ +public class EssenceMsg { + private Long senderId;// 发送者QQ 号 + private String senderNick;// 发送者昵称 + private Long senderTime;// 消息发送时间 + private Long operatorId;// 操作者QQ 号 + private String operatorNick;// 操作者昵称 + private Long operatorTime;// 精华设置时间 + private Integer messageId;// 消息ID + + public Long getSenderId() { + return senderId; + } + + public void setSenderId(Long senderId) { + this.senderId = senderId; + } + + public String getSenderNick() { + return senderNick; + } + + public void setSenderNick(String senderNick) { + this.senderNick = senderNick; + } + + public Long getSenderTime() { + return senderTime; + } + + public void setSenderTime(Long senderTime) { + this.senderTime = senderTime; + } + + public Long getOperatorId() { + return operatorId; + } + + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + + public String getOperatorNick() { + return operatorNick; + } + + public void setOperatorNick(String operatorNick) { + this.operatorNick = operatorNick; + } + + public Long getOperatorTime() { + return operatorTime; + } + + public void setOperatorTime(Long operatorTime) { + this.operatorTime = operatorTime; + } + + public Integer getMessageId() { + return messageId; + } + + public void setMessageId(Integer messageId) { + this.messageId = messageId; + } + + @Override + public String toString() { + return "EssenceMsg{" + + "senderId=" + senderId + + ", senderNick='" + senderNick + '\'' + + ", senderTime=" + senderTime + + ", operatorId=" + operatorId + + ", operatorNick='" + operatorNick + '\'' + + ", operatorTime=" + operatorTime + + ", messageId=" + messageId + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/ForwardMessage.java b/plumbot-bungee/src/main/java/sdk/client/response/ForwardMessage.java new file mode 100644 index 0000000..1d9cb76 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/ForwardMessage.java @@ -0,0 +1,72 @@ +package sdk.client.response; + +/** + * 获取合并转发信息 + */ +public class ForwardMessage { + private String content; + private Long time; + private Sender sender; + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public Long getTime() { + return time; + } + + public void setTime(Long time) { + this.time = time; + } + + public Sender getSender() { + return sender; + } + + public void setSender(Sender sender) { + this.sender = sender; + } + + @Override + public String toString() { + return "ForwardMessage{" + + "content='" + content + '\'' + + ", time=" + time + + ", sender=" + sender + + '}'; + } + + public class Sender { + private String nickname; + private Long userId; + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Override + public String toString() { + return "Sender{" + + "nickname='" + nickname + '\'' + + ", userId=" + userId + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/ForwardNode.java b/plumbot-bungee/src/main/java/sdk/client/response/ForwardNode.java new file mode 100644 index 0000000..1f128d8 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/ForwardNode.java @@ -0,0 +1,93 @@ +package sdk.client.response; + +/** + * 合并转发 + */ +public class ForwardNode { + + private String type = "node"; + private Data data = new Data(); + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Data getData() { + return data; + } + + public void setData(Data data) { + this.data = data; + } + + @Override + public String toString() { + return "ForwardNode{" + + "type='" + type + '\'' + + ", data=" + data + + '}'; + } + + public class Data{ + private String name; + private Integer id; + private Long uin; + private Object content; + private String seq; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Long getUin() { + return uin; + } + + public void setUin(Long uin) { + this.uin = uin; + } + + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + + public String getSeq() { + return seq; + } + + public void setSeq(String seq) { + this.seq = seq; + } + + @Override + public String toString() { + return "Data{" + + "name='" + name + '\'' + + ", id=" + id + + ", uin=" + uin + + ", content=" + content + + ", seq='" + seq + '\'' + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/Friend.java b/plumbot-bungee/src/main/java/sdk/client/response/Friend.java new file mode 100644 index 0000000..df68572 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/Friend.java @@ -0,0 +1,43 @@ +package sdk.client.response; + +/** + * 好友信息 + */ +public class Friend { + private Long userId;//QQ 号 + private String nickname;//昵称 + private String remark;//备注名 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + @Override + public String toString() { + return "Friend{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", remark='" + remark + '\'' + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupAtAllRemain.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupAtAllRemain.java new file mode 100644 index 0000000..2979cdc --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupAtAllRemain.java @@ -0,0 +1,43 @@ +package sdk.client.response; + +/** + * @全体 信息 + */ +public class GroupAtAllRemain { + private Boolean canAtAll;// 是否可以 @全体成员 + private Integer remainAtAllCountForGroup;// 群内所有管理当天剩余 @全体成员 次数 + private Integer remainAtAllCountForUin;// Bot 当天剩余 @全体成员 次数 + + public Boolean getCanAtAll() { + return canAtAll; + } + + public void setCanAtAll(Boolean canAtAll) { + this.canAtAll = canAtAll; + } + + public Integer getRemainAtAllCountForGroup() { + return remainAtAllCountForGroup; + } + + public void setRemainAtAllCountForGroup(Integer remainAtAllCountForGroup) { + this.remainAtAllCountForGroup = remainAtAllCountForGroup; + } + + public Integer getRemainAtAllCountForUin() { + return remainAtAllCountForUin; + } + + public void setRemainAtAllCountForUin(Integer remainAtAllCountForUin) { + this.remainAtAllCountForUin = remainAtAllCountForUin; + } + + @Override + public String toString() { + return "GroupAtAllRemain{" + + "canAtAll=" + canAtAll + + ", remainAtAllCountForGroup=" + remainAtAllCountForGroup + + ", remainAtAllCountForUin=" + remainAtAllCountForUin + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupFileSystemInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupFileSystemInfo.java new file mode 100644 index 0000000..0a0e86b --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupFileSystemInfo.java @@ -0,0 +1,53 @@ +package sdk.client.response; + +/** + * 群文件系统信息 + */ +public class GroupFileSystemInfo { + private Integer fileCount;//文件总数 + private Integer limitCount;//文件上限 + private Long usedSpace;//已使用空间 + private Long totalSpace;//空间上限 + + public Integer getFileCount() { + return fileCount; + } + + public void setFileCount(Integer fileCount) { + this.fileCount = fileCount; + } + + public Integer getLimitCount() { + return limitCount; + } + + public void setLimitCount(Integer limitCount) { + this.limitCount = limitCount; + } + + public Long getUsedSpace() { + return usedSpace; + } + + public void setUsedSpace(Long usedSpace) { + this.usedSpace = usedSpace; + } + + public Long getTotalSpace() { + return totalSpace; + } + + public void setTotalSpace(Long totalSpace) { + this.totalSpace = totalSpace; + } + + @Override + public String toString() { + return "GroupFileSystemInfo{" + + "fileCount=" + fileCount + + ", limitCount=" + limitCount + + ", usedSpace=" + usedSpace + + ", totalSpace=" + totalSpace + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupFiles.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupFiles.java new file mode 100644 index 0000000..010cc9d --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupFiles.java @@ -0,0 +1,214 @@ +package sdk.client.response; + +import java.util.List; + +/** + * 群文件信息 + */ +public class GroupFiles { + + private List files;// 文件列表 + private List folders;//文件夹列表 + + public List getFiles() { + return files; + } + + public void setFiles(List files) { + this.files = files; + } + + public List getFolders() { + return folders; + } + + public void setFolders(List folders) { + this.folders = folders; + } + + @Override + public String toString() { + return "GroupFiles{" + + "files=" + files + + ", folders=" + folders + + '}'; + } + + public class File { + private String fileId;//文件ID + private String fileName;//文件名 + private Integer busid;//文件类型 + private Long fileSize;//文件大小 + private Long uploadTime;// 上传时间 + private Long deadTime;//过期时间,永久文件恒为0 + private Long modifyTime;//最后修改时间 + private Integer downloadTimes;//下载次数 + private Long uploader;//上传者ID + private String uploaderName;//上传者名字 + + public String getFileId() { + return fileId; + } + + public void setFileId(String fileId) { + this.fileId = fileId; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public Integer getBusid() { + return busid; + } + + public void setBusid(Integer busid) { + this.busid = busid; + } + + public Long getFileSize() { + return fileSize; + } + + public void setFileSize(Long fileSize) { + this.fileSize = fileSize; + } + + public Long getUploadTime() { + return uploadTime; + } + + public void setUploadTime(Long uploadTime) { + this.uploadTime = uploadTime; + } + + public Long getDeadTime() { + return deadTime; + } + + public void setDeadTime(Long deadTime) { + this.deadTime = deadTime; + } + + public Long getModifyTime() { + return modifyTime; + } + + public void setModifyTime(Long modifyTime) { + this.modifyTime = modifyTime; + } + + public Integer getDownloadTimes() { + return downloadTimes; + } + + public void setDownloadTimes(Integer downloadTimes) { + this.downloadTimes = downloadTimes; + } + + public Long getUploader() { + return uploader; + } + + public void setUploader(Long uploader) { + this.uploader = uploader; + } + + public String getUploaderName() { + return uploaderName; + } + + public void setUploaderName(String uploaderName) { + this.uploaderName = uploaderName; + } + + @Override + public String toString() { + return "File{" + + "fileId='" + fileId + '\'' + + ", fileName='" + fileName + '\'' + + ", busid=" + busid + + ", fileSize=" + fileSize + + ", uploadTime=" + uploadTime + + ", deadTime=" + deadTime + + ", modifyTime=" + modifyTime + + ", downloadTimes=" + downloadTimes + + ", uploader=" + uploader + + ", uploaderName='" + uploaderName + '\'' + + '}'; + } + } + + public class Folder { + private String folderId;// 文件夹ID + private String folderName;// 文件名 + private Long createTime;// 创建时间 + private Long creator;// 创建者 + private String creatorName;// 创建者名字 + private Integer totalFileCount;// 子文件数量 + + public String getFolderId() { + return folderId; + } + + public void setFolderId(String folderId) { + this.folderId = folderId; + } + + public String getFolderName() { + return folderName; + } + + public void setFolderName(String folderName) { + this.folderName = folderName; + } + + public Long getCreateTime() { + return createTime; + } + + public void setCreateTime(Long createTime) { + this.createTime = createTime; + } + + public Long getCreator() { + return creator; + } + + public void setCreator(Long creator) { + this.creator = creator; + } + + public String getCreatorName() { + return creatorName; + } + + public void setCreatorName(String creatorName) { + this.creatorName = creatorName; + } + + public Integer getTotalFileCount() { + return totalFileCount; + } + + public void setTotalFileCount(Integer totalFileCount) { + this.totalFileCount = totalFileCount; + } + + @Override + public String toString() { + return "Folder{" + + "folderId='" + folderId + '\'' + + ", folderName='" + folderName + '\'' + + ", createTime=" + createTime + + ", creator=" + creator + + ", creatorName='" + creatorName + '\'' + + ", totalFileCount=" + totalFileCount + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupHonorInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupHonorInfo.java new file mode 100644 index 0000000..d412911 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupHonorInfo.java @@ -0,0 +1,183 @@ +package sdk.client.response; + +import java.util.List; + +/** + * 群荣誉信息 + */ +public class GroupHonorInfo { + private Long group_id;//群号 + private Talkative currentTalkative;//当前龙王, 仅 type 为 talkative 或 all 时有数据 + private List talkativeList;//历史龙王, 仅 type 为 talkative 或 all 时有数据 + private List performerList;//群聊之火, 仅 type 为 performer 或 all 时有数据 + private List legendList;//群聊炽焰, 仅 type 为 legend 或 all 时有数据 + private List strongNewbieList;//冒尖小春笋, 仅 type 为 strong_newbie 或 all 时有数据 + private List emotionList;//快乐之源, 仅 type 为 emotion 或 all 时有数据 + + public Long getGroup_id() { + return group_id; + } + + public void setGroup_id(Long group_id) { + this.group_id = group_id; + } + + public Talkative getCurrentTalkative() { + return currentTalkative; + } + + public void setCurrentTalkative(Talkative currentTalkative) { + this.currentTalkative = currentTalkative; + } + + public List getTalkativeList() { + return talkativeList; + } + + public void setTalkativeList(List talkativeList) { + this.talkativeList = talkativeList; + } + + public List getPerformerList() { + return performerList; + } + + public void setPerformerList(List performerList) { + this.performerList = performerList; + } + + public List getLegendList() { + return legendList; + } + + public void setLegendList(List legendList) { + this.legendList = legendList; + } + + public List getStrongNewbieList() { + return strongNewbieList; + } + + public void setStrongNewbieList(List strongNewbieList) { + this.strongNewbieList = strongNewbieList; + } + + public List getEmotionList() { + return emotionList; + } + + public void setEmotionList(List emotionList) { + this.emotionList = emotionList; + } + + @Override + public String toString() { + return "GroupHonorInfo{" + + "group_id=" + group_id + + ", currentTalkative=" + currentTalkative + + ", talkativeList=" + talkativeList + + ", performerList=" + performerList + + ", legendList=" + legendList + + ", strongNewbieList=" + strongNewbieList + + ", emotionList=" + emotionList + + '}'; + } + + public class Talkative { + private Long userId;//QQ 号 + private String nickname;//昵称 + private String avatar;//头像 URL + private Integer dayCount;//持续天数 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getAvatar() { + return avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar; + } + + public Integer getDayCount() { + return dayCount; + } + + public void setDayCount(Integer dayCount) { + this.dayCount = dayCount; + } + + @Override + public String toString() { + return "Talkative{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", avatar='" + avatar + '\'' + + ", dayCount=" + dayCount + + '}'; + } + } + + public class Member { + private Long userId;//QQ 号 + private String nickname;//昵称 + private String avatar;//头像 URL + private String description;//荣誉描述 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getAvatar() { + return avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "Member{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", avatar='" + avatar + '\'' + + ", description='" + description + '\'' + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupInfo.java new file mode 100644 index 0000000..df352c7 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupInfo.java @@ -0,0 +1,83 @@ +package sdk.client.response; + +/** + * 群信息 + */ +public class GroupInfo { + private Long groupId;//群号 + private String groupName;//群名称 + private String groupMemo;//群备注 + private String groupCreateTime;//群创建时间 + private Long groupLevel;//群等级 + private Integer memberCount;//成员数 + private Integer maxMemberCount;//最大成员数(群容量) + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public String getGroupMemo() { + return groupMemo; + } + + public void setGroupMemo(String groupMemo) { + this.groupMemo = groupMemo; + } + + public String getGroupCreateTime() { + return groupCreateTime; + } + + public void setGroupCreateTime(String groupCreateTime) { + this.groupCreateTime = groupCreateTime; + } + + public Long getGroupLevel() { + return groupLevel; + } + + public void setGroupLevel(Long groupLevel) { + this.groupLevel = groupLevel; + } + + public Integer getMemberCount() { + return memberCount; + } + + public void setMemberCount(Integer memberCount) { + this.memberCount = memberCount; + } + + public Integer getMaxMemberCount() { + return maxMemberCount; + } + + public void setMaxMemberCount(Integer maxMemberCount) { + this.maxMemberCount = maxMemberCount; + } + + @Override + public String toString() { + return "GroupInfo{" + + "groupId=" + groupId + + ", groupName='" + groupName + '\'' + + ", groupMemo='" + groupMemo + '\'' + + ", groupCreateTime='" + groupCreateTime + '\'' + + ", groupLevel=" + groupLevel + + ", memberCount=" + memberCount + + ", maxMemberCount=" + maxMemberCount + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupMemberInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupMemberInfo.java new file mode 100644 index 0000000..f448521 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupMemberInfo.java @@ -0,0 +1,163 @@ +package sdk.client.response; + +/** + * 群用户信息 + */ +public class GroupMemberInfo { + private Long groupId;// 群号 + private Long userId;// QQ 号 + private String nickname;// 昵称 + private String card;// 群名片/备注 + private String sex;// 性别, male 或 female 或 unknown + private Integer age;// 年龄 + private String area;// 地区 + private Integer joinTime;//加群时间戳 + private Integer lastSentTime;//最后发言时间戳 + private String level;//成员等级 + private String role;//owner 或 admin 或 member + private Boolean unfriendly;//是否不良记录成员 + private String title;//专属头衔 + private Long titleExpireTime;//专属头衔过期时间戳 + private Boolean cardChangeable;//是否允许修改群名 + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getCard() { + return card; + } + + public void setCard(String card) { + this.card = card; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getArea() { + return area; + } + + public void setArea(String area) { + this.area = area; + } + + public Integer getJoinTime() { + return joinTime; + } + + public void setJoinTime(Integer joinTime) { + this.joinTime = joinTime; + } + + public Integer getLastSentTime() { + return lastSentTime; + } + + public void setLastSentTime(Integer lastSentTime) { + this.lastSentTime = lastSentTime; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public Boolean getUnfriendly() { + return unfriendly; + } + + public void setUnfriendly(Boolean unfriendly) { + this.unfriendly = unfriendly; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Long getTitleExpireTime() { + return titleExpireTime; + } + + public void setTitleExpireTime(Long titleExpireTime) { + this.titleExpireTime = titleExpireTime; + } + + public Boolean getCardChangeable() { + return cardChangeable; + } + + public void setCardChangeable(Boolean cardChangeable) { + this.cardChangeable = cardChangeable; + } + + @Override + public String toString() { + return "GroupMemberInfo{" + + "groupId=" + groupId + + ", userId=" + userId + + ", nickname='" + nickname + '\'' + + ", card='" + card + '\'' + + ", sex='" + sex + '\'' + + ", age=" + age + + ", area='" + area + '\'' + + ", joinTime=" + joinTime + + ", lastSentTime=" + lastSentTime + + ", level='" + level + '\'' + + ", role='" + role + '\'' + + ", unfriendly=" + unfriendly + + ", title='" + title + '\'' + + ", titleExpireTime=" + titleExpireTime + + ", cardChangeable=" + cardChangeable + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/GroupSystemMsg.java b/plumbot-bungee/src/main/java/sdk/client/response/GroupSystemMsg.java new file mode 100644 index 0000000..44d3e54 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/GroupSystemMsg.java @@ -0,0 +1,205 @@ +package sdk.client.response; + + +import java.util.List; + +/** + * 群通知信息 + */ +public class GroupSystemMsg { + + private List invitedRequests;//邀请消息列表 + private List joinRequests;//进群消息列表 + + public List getInvitedRequests() { + return invitedRequests; + } + + public void setInvitedRequests(List invitedRequests) { + this.invitedRequests = invitedRequests; + } + + public List getJoinRequests() { + return joinRequests; + } + + public void setJoinRequests(List joinRequests) { + this.joinRequests = joinRequests; + } + + @Override + public String toString() { + return "GroupSystemMsg{" + + "invitedRequests=" + invitedRequests + + ", joinRequests=" + joinRequests + + '}'; + } + + public class InvitedRequest { + private Long requestId;//请求ID + private Long invitorUin;//邀请者 + private String invitorNick;//邀请者昵称 + private Long groupId;//群号 + private String groupName;//群名 + private Boolean checked;//是否已被处理 + private Long actor;//处理者, 未处理为0 + + public Long getRequestId() { + return requestId; + } + + public void setRequestId(Long requestId) { + this.requestId = requestId; + } + + public Long getInvitorUin() { + return invitorUin; + } + + public void setInvitorUin(Long invitorUin) { + this.invitorUin = invitorUin; + } + + public String getInvitorNick() { + return invitorNick; + } + + public void setInvitorNick(String invitorNick) { + this.invitorNick = invitorNick; + } + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public Boolean getChecked() { + return checked; + } + + public void setChecked(Boolean checked) { + this.checked = checked; + } + + public Long getActor() { + return actor; + } + + public void setActor(Long actor) { + this.actor = actor; + } + + @Override + public String toString() { + return "InvitedRequest{" + + "requestId=" + requestId + + ", invitorUin=" + invitorUin + + ", invitorNick='" + invitorNick + '\'' + + ", groupId=" + groupId + + ", groupName='" + groupName + '\'' + + ", checked=" + checked + + ", actor=" + actor + + '}'; + } + } + + public class JoinRequest { + private Long requestId;//请求ID + private Long requesterUin;//请求者ID + private String requesterNick;//请求者昵称 + private String message;//验证消息 + private Long groupId;//群号 + private String groupName;//群名 + private Boolean checked;//是否已被处理 + private Long actor;//处理者, 未处理为0 + + public Long getRequestId() { + return requestId; + } + + public void setRequestId(Long requestId) { + this.requestId = requestId; + } + + public Long getRequesterUin() { + return requesterUin; + } + + public void setRequesterUin(Long requesterUin) { + this.requesterUin = requesterUin; + } + + public String getRequesterNick() { + return requesterNick; + } + + public void setRequesterNick(String requesterNick) { + this.requesterNick = requesterNick; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public Boolean getChecked() { + return checked; + } + + public void setChecked(Boolean checked) { + this.checked = checked; + } + + public Long getActor() { + return actor; + } + + public void setActor(Long actor) { + this.actor = actor; + } + + @Override + public String toString() { + return "JoinRequest{" + + "requestId=" + requestId + + ", requesterUin=" + requesterUin + + ", requesterNick='" + requesterNick + '\'' + + ", message='" + message + '\'' + + ", groupId=" + groupId + + ", groupName='" + groupName + '\'' + + ", checked=" + checked + + ", actor=" + actor + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/LoginInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/LoginInfo.java new file mode 100644 index 0000000..b0b96fb --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/LoginInfo.java @@ -0,0 +1,34 @@ +package sdk.client.response; + + +/** + * 机器人信息 + */ +public class LoginInfo { + private Integer userId;//QQ号 + private String nickname;//QQ昵称 + + public Integer getUserId() { + return userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + @Override + public String toString() { + return "LoginInfo{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/Message.java b/plumbot-bungee/src/main/java/sdk/client/response/Message.java new file mode 100644 index 0000000..bcf00fb --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/Message.java @@ -0,0 +1,113 @@ +package sdk.client.response; + +/** + * 获取消息返回的信息 + */ +public class Message { + + private Integer messageId; + private Integer realId; + private Integer time; + private String message; + private String rawMessage; + + public Integer getMessageId() { + return messageId; + } + + public void setMessageId(Integer messageId) { + this.messageId = messageId; + } + + public Integer getRealId() { + return realId; + } + + public void setRealId(Integer realId) { + this.realId = realId; + } + + public Integer getTime() { + return time; + } + + public void setTime(Integer time) { + this.time = time; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getRawMessage() { + return rawMessage; + } + + public void setRawMessage(String rawMessage) { + this.rawMessage = rawMessage; + } + + @Override + public String toString() { + return "Message{" + + "messageId=" + messageId + + ", realId=" + realId + + ", time=" + time + + ", message='" + message + '\'' + + ", rawMessage='" + rawMessage + '\'' + + '}'; + } + + public class Sender{ + private Long userId;//QQ号 + private String nickname;//昵称/备注 + private String sex;//性别 + private Integer age;//年龄 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "Sender{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", sex='" + sex + '\'' + + ", age=" + age + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/OcrImage.java b/plumbot-bungee/src/main/java/sdk/client/response/OcrImage.java new file mode 100644 index 0000000..62efc6f --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/OcrImage.java @@ -0,0 +1,104 @@ +package sdk.client.response; + +import java.math.BigDecimal; +import java.util.List; + +/** + * ocr响应 + */ +public class OcrImage { + private List texts; + private String language; + + public List getTexts() { + return texts; + } + + public void setTexts(List texts) { + this.texts = texts; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + @Override + public String toString() { + return "OcrImage{" + + "texts=" + texts + + ", language='" + language + '\'' + + '}'; + } + + public class TextDetection { + private String text;// 文本 + private Integer confidence;// 置信度 + private List coordinates;// 坐标 + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Integer getConfidence() { + return confidence; + } + + public void setConfidence(Integer confidence) { + this.confidence = confidence; + } + + public List getCoordinates() { + return coordinates; + } + + public void setCoordinates(List coordinates) { + this.coordinates = coordinates; + } + + @Override + public String toString() { + return "TextDetection{" + + "text='" + text + '\'' + + ", confidence=" + confidence + + ", coordinates='" + coordinates + '\'' + + '}'; + } + } + + public class Vector2{ + private BigDecimal x; + private BigDecimal y; + + public BigDecimal getX() { + return x; + } + + public void setX(BigDecimal x) { + this.x = x; + } + + public BigDecimal getY() { + return y; + } + + public void setY(BigDecimal y) { + this.y = y; + } + + @Override + public String toString() { + return "Vector2{" + + "x=" + x + + ", y=" + y + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/OnlineClient.java b/plumbot-bungee/src/main/java/sdk/client/response/OnlineClient.java new file mode 100644 index 0000000..3d277d0 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/OnlineClient.java @@ -0,0 +1,43 @@ +package sdk.client.response; + +/** + * 客户端信息 + */ +public class OnlineClient { + private Long appId;// 客户端ID + private String deviceName;// 设备名称 + private String deviceKind;// 设备类型 + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public String getDeviceName() { + return deviceName; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public String getDeviceKind() { + return deviceKind; + } + + public void setDeviceKind(String deviceKind) { + this.deviceKind = deviceKind; + } + + @Override + public String toString() { + return "OnlineClient{" + + "appId=" + appId + + ", deviceName='" + deviceName + '\'' + + ", deviceKind='" + deviceKind + '\'' + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/StrangerInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/StrangerInfo.java new file mode 100644 index 0000000..5ff8552 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/StrangerInfo.java @@ -0,0 +1,64 @@ +package sdk.client.response; + + +/** + * 陌生人信息 + */ +public class StrangerInfo { + private Long userId;//QQ 号 + private String nickname;//昵称 + private String sex;//性别, male 或 female 或 unknown + private Integer age;//年龄 + private String qid;//qid ID身份卡 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getQid() { + return qid; + } + + public void setQid(String qid) { + this.qid = qid; + } + + @Override + public String toString() { + return "StrangerInfo{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", sex='" + sex + '\'' + + ", age=" + age + + ", qid='" + qid + '\'' + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/client/response/VipInfo.java b/plumbot-bungee/src/main/java/sdk/client/response/VipInfo.java new file mode 100644 index 0000000..bef4e30 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/client/response/VipInfo.java @@ -0,0 +1,83 @@ +package sdk.client.response; + +/** + * 会员信息 + */ +public class VipInfo { + private Long userId;// QQ 号 + private String nickname;// 用户昵称 + private Long level;// QQ 等级 + private Double leveSpeed;// 等级加速度 + private String vipLevel;// 会员等级 + private Long vipGrowthSpeed;// 会员成长速度 + private Long vipGrowthTotal;// 会员成长总值 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public Long getLevel() { + return level; + } + + public void setLevel(Long level) { + this.level = level; + } + + public Double getLeveSpeed() { + return leveSpeed; + } + + public void setLeveSpeed(Double leveSpeed) { + this.leveSpeed = leveSpeed; + } + + public String getVipLevel() { + return vipLevel; + } + + public void setVipLevel(String vipLevel) { + this.vipLevel = vipLevel; + } + + public Long getVipGrowthSpeed() { + return vipGrowthSpeed; + } + + public void setVipGrowthSpeed(Long vipGrowthSpeed) { + this.vipGrowthSpeed = vipGrowthSpeed; + } + + public Long getVipGrowthTotal() { + return vipGrowthTotal; + } + + public void setVipGrowthTotal(Long vipGrowthTotal) { + this.vipGrowthTotal = vipGrowthTotal; + } + + @Override + public String toString() { + return "VipInfo{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", level=" + level + + ", leveSpeed=" + leveSpeed + + ", vipLevel='" + vipLevel + '\'' + + ", vipGrowthSpeed=" + vipGrowthSpeed + + ", vipGrowthTotal=" + vipGrowthTotal + + '}'; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/config/CQConfig.java b/plumbot-bungee/src/main/java/sdk/config/CQConfig.java new file mode 100644 index 0000000..a8cf425 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/config/CQConfig.java @@ -0,0 +1,52 @@ +package sdk.config; + +/** + * go-cqhttp基本配置 + */ +public class CQConfig { + private String url;//websocket地址 + private String token;//token鉴权 + private Boolean isAccessToken;//是否开启鉴权 + + public CQConfig(String url) { + this(url, null); + } + + public CQConfig(String url, String token) { + this(url, token, false); + } + + + public CQConfig(String url, String token, Boolean isAccessToken) { + this.url = url; + this.token = token; + this.isAccessToken = isAccessToken; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public Boolean getIsAccessToken() { + return isAccessToken; + } + + public void setIsAccessToken(Boolean isAccessToken) { + this.isAccessToken = isAccessToken; + } + + public void addTask(String message) { + } +} diff --git a/plumbot-bungee/src/main/java/sdk/config/MessageConfig.java b/plumbot-bungee/src/main/java/sdk/config/MessageConfig.java new file mode 100644 index 0000000..9c15bb2 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/config/MessageConfig.java @@ -0,0 +1,44 @@ +package sdk.config; + +import sdk.event.global.Message; +import sdk.event.message.GroupMessage; +import sdk.event.message.PrivateMessage; +import sdk.event.notice.*; +import sdk.event.request.FriendRequest; +import sdk.event.request.GroupRequest; + +import java.util.HashMap; +import java.util.Map; + +/** + * 上报消息与其对应的实体类 + */ +public class MessageConfig { + public static Map> MessageMap = new HashMap<>(); + + static { + MessageMap.put("groupMessage", GroupMessage.class); + MessageMap.put("privateMessage", PrivateMessage.class); + + MessageMap.put("friend", FriendRequest.class); + MessageMap.put("group", GroupRequest.class); + + MessageMap.put("group_upload", GroupFileUploadNotice.class); + MessageMap.put("group_admin", GroupAdminNotice.class); + MessageMap.put("group_decrease", GroupDecreaseNotice.class); + MessageMap.put("group_increase", GroupIncreaseNotice.class); + MessageMap.put("group_ban", GroupBanNotice.class); + MessageMap.put("group_recall", GroupRecallNotice.class); + MessageMap.put("group_poke", GroupPokeNotice.class); + MessageMap.put("lucky_king", GroupLuckyKingNotice.class); + MessageMap.put("honor", GroupHonorNotice.class); + MessageMap.put("group_card", GroupCardNotice.class); + + MessageMap.put("friend_add", FriendAddNotice.class); + MessageMap.put("friend_recall", FriendRecallNotice.class); + MessageMap.put("friend_poke", FriendPokeNotice.class); + MessageMap.put("offline_file", OfflineFileNotice.class); + MessageMap.put("client_status", ClientStatusNotice.class); + MessageMap.put("essence", EssenceNotice.class); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/connection/Connection.java b/plumbot-bungee/src/main/java/sdk/connection/Connection.java new file mode 100644 index 0000000..84e9a98 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/connection/Connection.java @@ -0,0 +1,13 @@ +package sdk.connection; + +/** + * 封装启动方法 + * 实现类对各自不同的实现调用启动 + */ +public interface Connection { + /** + * 启动方法 + */ + void create(); + void stop(); +} diff --git a/plumbot-bungee/src/main/java/sdk/connection/ConnectionFactory.java b/plumbot-bungee/src/main/java/sdk/connection/ConnectionFactory.java new file mode 100644 index 0000000..66ba256 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/connection/ConnectionFactory.java @@ -0,0 +1,49 @@ +package sdk.connection; + +import sdk.config.CQConfig; +import sdk.connection.impl.CQWebSocketClient; +import sdk.connection.impl.CQWebSocketServer; +import sdk.connection.impl.CustomHttpServer; + +import java.net.URI; +import java.util.concurrent.BlockingQueue; + +/** + * 封装创建连接方法 + */ +public class ConnectionFactory { + /** + * 构建正向websocket服务 + * + * @return + */ + public static CQWebSocketClient createWebsocketClient(CQConfig config, BlockingQueue queue) throws Exception { + StringBuilder builder = new StringBuilder(); + builder.append(config.getUrl()); + if (config.getIsAccessToken()) { + builder.append("?access_token="); + builder.append(config.getToken()); + } + String url = builder.toString(); + URI uri = new URI(url); + return new CQWebSocketClient(uri, queue); + } + + /** + * 构建反向websocket服务 + * + * @return + */ + public static Connection createWebsocketServer(Integer port, BlockingQueue queue) throws Exception { + return new CQWebSocketServer(port, queue); + } + + /** + * 构建反向http服务 + * + * @return + */ + public static Connection createHttpServer(Integer port, String path, BlockingQueue queue) throws Exception { + return new CustomHttpServer(port, path, queue); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketClient.java b/plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketClient.java new file mode 100644 index 0000000..b289f89 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketClient.java @@ -0,0 +1,71 @@ +package sdk.connection.impl; + +import cn.hutool.log.Log; +import cn.hutool.log.LogFactory; +import org.java_websocket.client.WebSocketClient; +import org.java_websocket.handshake.ServerHandshake; +import sdk.connection.Connection; + +import java.net.URI; +import java.util.concurrent.BlockingQueue; + +/** + * 正向websocket + */ +public class CQWebSocketClient extends WebSocketClient implements Connection { + + private BlockingQueue queue; + + private static final Log log = LogFactory.get(); + + public CQWebSocketClient(URI serverUri, BlockingQueue queue) { + super(serverUri); + this.queue = queue; + } + + /** + * 建立连接 + * + * @param serverHandshake + */ + @Override + public void onOpen(ServerHandshake serverHandshake) { + log.info("已连接到服务器:{},开始监听事件", this.uri); + } + + /** + * 收到消息 + * + * @param message + */ + @Override + public void onMessage(String message) { + if (message != null && !message.contains("heartbeat") && !message.contains("lifecycle")) {//过滤心跳 + queue.add(message); + } + } + + @Override + public void onClose(int i, String s, boolean b) { + } + + /** + * 出现异常 + * + * @param e + */ + @Override + public void onError(Exception e) { + log.warn(e); + } + + @Override + public void create() { + super.connect(); + } + + @Override + public void stop() { + super.close(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketServer.java b/plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketServer.java new file mode 100644 index 0000000..061baec --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/connection/impl/CQWebSocketServer.java @@ -0,0 +1,65 @@ +package sdk.connection.impl; + +import cn.hutool.log.Log; +import cn.hutool.log.LogFactory; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import sdk.connection.Connection; + +import java.net.InetSocketAddress; +import java.util.concurrent.BlockingQueue; + +/** + * 反向websocket + */ +public class CQWebSocketServer extends WebSocketServer implements Connection { + + private BlockingQueue queue; + + private static final Log log = LogFactory.get(); + + public CQWebSocketServer(Integer port, BlockingQueue queue) { + super(new InetSocketAddress(port)); + this.queue = queue; + } + + @Override + public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) { + log.info("接收到来自客户端的连接"); + } + + @Override + public void onClose(WebSocket webSocket, int i, String s, boolean b) { + log.error("客户端下线"); + } + + @Override + public void onMessage(WebSocket webSocket, String s) { + queue.add(s); + } + + @Override + public void onError(WebSocket webSocket, Exception e) { + log.warn(e); + } + + @Override + public void onStart() { + log.info("WebSocket服务器启动,正在监听端口:{}", getPort()); + } + + @Override + public void create() { + super.start(); + } + + @Override + public void stop() { + try { + super.stop(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/connection/impl/CustomHttpServer.java b/plumbot-bungee/src/main/java/sdk/connection/impl/CustomHttpServer.java new file mode 100644 index 0000000..9d39e60 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/connection/impl/CustomHttpServer.java @@ -0,0 +1,70 @@ +package sdk.connection.impl; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import me.regadpole.plumbot.PlumBot; +import sdk.connection.Connection; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.concurrent.BlockingQueue; +import java.util.logging.Level; + +/** + * 基于内置http服务器实现自定义服务 + */ +public class CustomHttpServer implements Connection { + + private Integer port; + private String path; + private BlockingQueue queue; + +// private static Log log = LogFactory.get(); + + private HttpServer server; + + public CustomHttpServer(Integer port, String path, BlockingQueue queue) { + try { + this.port = port; + this.path = path; + server = HttpServer.create(new InetSocketAddress(port), 0); + server.createContext(path, new CustomHttpHandler()); + } catch (IOException e) { +// log.error(e); + PlumBot.INSTANCE.getLogger().log(Level.WARNING, e.getMessage(), e); + } + this.queue = queue; + } + + @Override + public void create() { + server.start(); +// log.info("HTTP服务器启动,正在监听端口:{}", port); + PlumBot.INSTANCE.getLogger().info("HTTP服务器启动,正在监听端口:"+port); + } + + class CustomHttpHandler implements HttpHandler { + @Override + public void handle(HttpExchange exchange) throws IOException { + BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); + StringBuffer stringBuffer = new StringBuffer(); + String oneLine = ""; + while ((oneLine = reader.readLine()) != null) { + stringBuffer.append(oneLine); + } + queue.add(stringBuffer.toString()); + exchange.sendResponseHeaders(204, -1); + exchange.close(); + } + } + + @Override + public void stop() { + server.stop(0); + PlumBot.INSTANCE.getLogger().info("HTTP服务器已关闭"); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/EventDispatchers.java b/plumbot-bungee/src/main/java/sdk/event/EventDispatchers.java new file mode 100644 index 0000000..30ff948 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/EventDispatchers.java @@ -0,0 +1,167 @@ +package sdk.event; + +import cn.hutool.json.JSONUtil; +import me.regadpole.plumbot.PlumBot; +import sdk.event.global.Message; +import sdk.listener.EnableListener; +import sdk.listener.Listener; +import sdk.utils.ListenerUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.logging.Level; + +/** + * 事件分发器 + */ +public class EventDispatchers implements Runnable { + +// private static Log log = LogFactory.get(); + + //存储监听器对象 + protected List listenerList = new ArrayList<>(); + + //缓存类型与监听器的关系 + protected Map, List> cache = new ConcurrentHashMap<>(); + + //线程池 用于并发执行队列中的任务 + protected ExecutorService service; + + protected BlockingQueue queue; + + private Listener messageListener; + + public EventDispatchers(BlockingQueue queue) { + this.queue = queue; + } + + public void addListener(Listener listener) { + listenerList.add(listener); + } + + public void start() { + start(1); + } + + public void start(Integer threadCount) { + if (threadCount <= 0) { + threadCount = 1; + } + service = Executors.newFixedThreadPool(threadCount); + for (int i = 0; i < threadCount; i++) { + service.submit(this); + + } + } + + @Override + public void run() { + while (true) { + try { + this.runTask(); + } catch (Exception e) { +// log.warn(e); +// PlumBot.INSTANCE.getSLF4JLogger().warn(Arrays.toString(e.getStackTrace())); + } + } + } + + /** + * 执行任务 + */ + protected void runTask() { + String message = this.getTask();//获取消息 + if (message == null) { + return; + } + Class messageType = ListenerUtils.getMessageType(message);//获取消息对应的实体类型 + if (messageType == null) { + return; + } + if (this.messageListener != null){ + this.messageListener.onMessage(message); + } +// log.debug("接收到上报消息:{}", messageType); + Message bean = JSONUtil.toBean(message, messageType);//将消息反序列化为对象 + List executeListener = (executeListener = cache.get(messageType)) == null ? + getMethod(messageType) : executeListener;//检查缓存 + + for (Listener listener : executeListener) { + if (listener.valider(bean)) { + listener.onMessage(bean);//调用监听方法 + } + } + if (executeListener != null) { + cache.put(messageType, executeListener); + } + } + + /** + * 从队列中获取任务 + * + * @return + */ + protected String getTask() { + try { + return this.queue.take(); + } catch (Exception e) { +// log.error(e); + PlumBot.INSTANCE.getLogger().log(Level.WARNING, e.getMessage(), e); + } + return null; + } + + /** + * 获取能处理消息类型的处理器 + * + * @param messageType + * @return + */ + protected List getMethod(Class messageType) { + List listeners = new ArrayList<>(); + for (Listener listener : listenerList) { + try { + try { + listener.getClass().getMethod("onMessage", messageType);//判断是否支持该类型 + } catch (NoSuchMethodException e) { + continue;//不支持则跳过 + } + if(listener instanceof EnableListener){ + EnableListener enableListener = (EnableListener)listener; + if (!enableListener.enable()) {//检测是否开启该插件 + continue; + } + } + listeners.add(listener);//开启后添加入当前类型的插件 + } catch (Exception e) { + e.printStackTrace(); + } + } + return listeners; + } + + public List getListenerList() { + return listenerList; + } + + /** + * 清除类型缓存 + */ + public void cleanCache() { + cache.clear(); + } + + public void setMessageListener(Listener messageListener) { + this.messageListener = messageListener; + } + + public Listener getMessageListener() { + return messageListener; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/global/GroupNotice.java b/plumbot-bungee/src/main/java/sdk/event/global/GroupNotice.java new file mode 100644 index 0000000..2575196 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/global/GroupNotice.java @@ -0,0 +1,33 @@ +package sdk.event.global; + +/** + * 抽取群通知 + */ +public class GroupNotice extends Notice { + private Long groupId;//群号 + private Long userId;//QQ号 + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Override + public String toString() { + return "GroupNotice{" + + "groupId=" + groupId + + ", userId=" + userId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/global/Message.java b/plumbot-bungee/src/main/java/sdk/event/global/Message.java new file mode 100644 index 0000000..e4b22de --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/global/Message.java @@ -0,0 +1,45 @@ +package sdk.event.global; + +/** + * 所有通知适用 + */ +public class Message { + private Long time;//事件发生的时间戳 + private Long selfId;//收到事件的机器人 QQ 号 + private String postType;//notice 上报类型 + + public Long getTime() { + return time; + } + + public void setTime(Long time) { + this.time = time; + } + + public Long getSelfId() { + return selfId; + } + + public void setSelfId(Long selfId) { + this.selfId = selfId; + } + + public String getPostType() { + return postType; + } + + public void setPostType(String postType) { + this.postType = postType; + } + + + @Override + public String toString() { + return "Message{" + + "time=" + time + + ", selfId=" + selfId + + ", postType='" + postType + '\'' + + '}'; + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/event/global/Notice.java b/plumbot-bungee/src/main/java/sdk/event/global/Notice.java new file mode 100644 index 0000000..7f228f4 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/global/Notice.java @@ -0,0 +1,24 @@ +package sdk.event.global; + + +/** + * 通知类型适用 + */ +public class Notice extends Message { + private String noticeType;//通知类型 + + public String getNoticeType() { + return noticeType; + } + + public void setNoticeType(String noticeType) { + this.noticeType = noticeType; + } + + @Override + public String toString() { + return "Notice{" + + "noticeType='" + noticeType + '\'' + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/global/RecvMessage.java b/plumbot-bungee/src/main/java/sdk/event/global/RecvMessage.java new file mode 100644 index 0000000..c5c3138 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/global/RecvMessage.java @@ -0,0 +1,84 @@ +package sdk.event.global; + + +/** + * 消息类型 + */ +public class RecvMessage extends Message { + private String messageType;//消息类型 + private String subType;//消息子类型 + private Integer messageId;//消息ID + private Long userId;//发送者QQ号 + private String message;//消息内容 + private String rawMessage;//原始消息内容 + private Integer font;//字体 + + public String getMessageType() { + return messageType; + } + + public void setMessageType(String messageType) { + this.messageType = messageType; + } + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Integer getMessageId() { + return messageId; + } + + public void setMessageId(Integer messageId) { + this.messageId = messageId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getRawMessage() { + return rawMessage; + } + + public void setRawMessage(String rawMessage) { + this.rawMessage = rawMessage; + } + + public Integer getFont() { + return font; + } + + public void setFont(Integer font) { + this.font = font; + } + + @Override + public String toString() { + return "RecvMessage{" + + "messageType='" + messageType + '\'' + + ", subType='" + subType + '\'' + + ", messageId=" + messageId + + ", userId=" + userId + + ", message='" + message + '\'' + + ", rawMessage='" + rawMessage + '\'' + + ", font=" + font + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/global/Request.java b/plumbot-bungee/src/main/java/sdk/event/global/Request.java new file mode 100644 index 0000000..30ba3eb --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/global/Request.java @@ -0,0 +1,24 @@ +package sdk.event.global; + + +/** + * 请求类型适用 + */ +public class Request extends Message { + private String requestType;//请求类型 + + public String getRequestType() { + return requestType; + } + + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + @Override + public String toString() { + return "Request{" + + "requestType='" + requestType + '\'' + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/message/GroupMessage.java b/plumbot-bungee/src/main/java/sdk/event/message/GroupMessage.java new file mode 100644 index 0000000..f190d78 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/message/GroupMessage.java @@ -0,0 +1,183 @@ +package sdk.event.message; + +import sdk.event.global.RecvMessage; + +/** + * 群聊消息 + */ +public class GroupMessage extends RecvMessage { + private Long groupId;//群号 + private Anonymous anonymous;//是否匿名 null为匿名 + private Sender sender; + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public Anonymous getAnonymous() { + return anonymous; + } + + public void setAnonymous(Anonymous anonymous) { + this.anonymous = anonymous; + } + + public Sender getSender() { + return sender; + } + + public void setSender(Sender sender) { + this.sender = sender; + } + + @Override + public String toString() { + return "GroupMessage{" + + "groupId=" + groupId + + ", anonymous=" + anonymous + + ", sender=" + sender + + "} " + super.toString(); + } + + public class Anonymous{ + private String flag; + private String name; + private Long id; + + public String getFlag() { + return flag; + } + + public void setFlag(String flag) { + this.flag = flag; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + @Override + public String toString() { + return "Anonymous{" + + "flag='" + flag + '\'' + + ", name='" + name + '\'' + + ", id=" + id + + '}'; + } + } + + public class Sender{ + private Long userId;//QQ号 + private String nickname;//昵称 + private String card;//群名/备注 + private String sex;//性别 + private Integer age;//年龄 + private String area;//地区 + private String level;//登记 + private String role;//角色 + private String title;//专属头衔 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getCard() { + return card; + } + + public void setCard(String card) { + this.card = card; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public String getArea() { + return area; + } + + public void setArea(String area) { + this.area = area; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() { + return "Sender{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", card='" + card + '\'' + + ", sex='" + sex + '\'' + + ", age=" + age + + ", area='" + area + '\'' + + ", level='" + level + '\'' + + ", role='" + role + '\'' + + ", title='" + title + '\'' + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/message/PrivateMessage.java b/plumbot-bungee/src/main/java/sdk/event/message/PrivateMessage.java new file mode 100644 index 0000000..8c2112a --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/message/PrivateMessage.java @@ -0,0 +1,84 @@ +package sdk.event.message; + +import sdk.event.global.RecvMessage; + +/** + * 私聊消息 + */ +public class PrivateMessage extends RecvMessage { + private Integer tempSource;//临时会话来源 + private Sender sender; + + public Integer getTempSource() { + return tempSource; + } + + public void setTempSource(Integer tempSource) { + this.tempSource = tempSource; + } + + public Sender getSender() { + return sender; + } + + public void setSender(Sender sender) { + this.sender = sender; + } + + @Override + public String toString() { + return "PrivateMessage{" + + "tempSource=" + tempSource + + ", sender=" + sender + + "} " + super.toString(); + } + + public class Sender{ + private Long userId;//QQ号 + private String nickname;//昵称/备注 + private String sex;//性别 + private Integer age;//年龄 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nickname) { + this.nickname = nickname; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + @Override + public String toString() { + return "Sender{" + + "userId=" + userId + + ", nickname='" + nickname + '\'' + + ", sex='" + sex + '\'' + + ", age=" + age + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/ClientStatusNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/ClientStatusNotice.java new file mode 100644 index 0000000..76e169d --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/ClientStatusNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 其他客户端在线状态变更 + */ +public class ClientStatusNotice extends Notice { + private String client;//Device类型 客户端信息 + private Boolean online;//当前是否在线 + + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + public Boolean getOnline() { + return online; + } + + public void setOnline(Boolean online) { + this.online = online; + } + + @Override + public String toString() { + return "ClientStatusNotice{" + + "client='" + client + '\'' + + ", online=" + online + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/EssenceNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/EssenceNotice.java new file mode 100644 index 0000000..c254194 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/EssenceNotice.java @@ -0,0 +1,55 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 精华消息 + */ +public class EssenceNotice extends Notice { + private String subType;//add,delete 添加为add,移出为delete + private Long senderId ;//消息发送者ID + private Long operatorId;//操作者ID + private Long messageId ;//消息ID + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getSenderId() { + return senderId; + } + + public void setSenderId(Long senderId) { + this.senderId = senderId; + } + + public Long getOperatorId() { + return operatorId; + } + + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + + public Long getMessageId() { + return messageId; + } + + public void setMessageId(Long messageId) { + this.messageId = messageId; + } + + @Override + public String toString() { + return "EssenceNotice{" + + "subType='" + subType + '\'' + + ", senderId=" + senderId + + ", operatorId=" + operatorId + + ", messageId=" + messageId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/FriendAddNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/FriendAddNotice.java new file mode 100644 index 0000000..d7181ea --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/FriendAddNotice.java @@ -0,0 +1,25 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 新增好友 + */ +public class FriendAddNotice extends Notice { + private Long userId;//新添加好友 QQ 号 + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Override + public String toString() { + return "FriendAddNotice{" + + "userId=" + userId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/FriendPokeNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/FriendPokeNotice.java new file mode 100644 index 0000000..4a8d308 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/FriendPokeNotice.java @@ -0,0 +1,55 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 好友戳一戳 + */ +public class FriendPokeNotice extends Notice { + private String subType;//poke 提示类型 + private Long senderId;//发送者 QQ 号 + private Long userId;//发送者 QQ 号 + private Long targetId;//被戳者 QQ 号 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getSenderId() { + return senderId; + } + + public void setSenderId(Long senderId) { + this.senderId = senderId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getTargetId() { + return targetId; + } + + public void setTargetId(Long targetId) { + this.targetId = targetId; + } + + @Override + public String toString() { + return "FriendPokeNotice{" + + "subType='" + subType + '\'' + + ", senderId=" + senderId + + ", userId=" + userId + + ", targetId=" + targetId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/FriendRecallNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/FriendRecallNotice.java new file mode 100644 index 0000000..f21f741 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/FriendRecallNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 好友消息撤回 + */ +public class FriendRecallNotice extends Notice { + private Long userId;//好友 QQ 号 + private Long messageId;//被撤回的消息 ID + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getMessageId() { + return messageId; + } + + public void setMessageId(Long messageId) { + this.messageId = messageId; + } + + @Override + public String toString() { + return "FriendRecallNotice{" + + "userId=" + userId + + ", messageId=" + messageId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupAdminNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupAdminNotice.java new file mode 100644 index 0000000..8a191ee --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupAdminNotice.java @@ -0,0 +1,27 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群管理员变动 + */ +public class GroupAdminNotice extends GroupNotice { + private String subType;//set、unset 事件子类型, 分别表示设置和取消管理员 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + @Override + public String toString() { + return "GroupAdminNotice{" + + "subType='" + subType + '\'' + + "} " + super.toString(); + } +} + + diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupBanNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupBanNotice.java new file mode 100644 index 0000000..e58976b --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupBanNotice.java @@ -0,0 +1,45 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群禁言 + */ +public class GroupBanNotice extends GroupNotice { + private String subType;//approve管理员同意 invite管理员邀请 + private Long operatorId;//操作者 QQ 号 + private Long duration;//禁言时长, 单位秒 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getOperatorId() { + return operatorId; + } + + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + + public Long getDuration() { + return duration; + } + + public void setDuration(Long duration) { + this.duration = duration; + } + + @Override + public String toString() { + return "GroupBanNotice{" + + "subType='" + subType + '\'' + + ", operatorId=" + operatorId + + ", duration=" + duration + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupCardNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupCardNotice.java new file mode 100644 index 0000000..84ec584 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupCardNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群成员名片更新 + */ +public class GroupCardNotice extends GroupNotice { + private Long cardNew;//新名片 + private Long cardOld;//旧名片 + + public Long getCardNew() { + return cardNew; + } + + public void setCardNew(Long cardNew) { + this.cardNew = cardNew; + } + + public Long getCardOld() { + return cardOld; + } + + public void setCardOld(Long cardOld) { + this.cardOld = cardOld; + } + + @Override + public String toString() { + return "GroupCardNotice{" + + "cardNew=" + cardNew + + ", cardOld=" + cardOld + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupDecreaseNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupDecreaseNotice.java new file mode 100644 index 0000000..c9598b1 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupDecreaseNotice.java @@ -0,0 +1,37 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群成员减少 + */ +public class GroupDecreaseNotice extends GroupNotice { + private String subType;//leave主动退群、kick成员被踢、kick_me登录号被踢 + private Long operatorId;//操作者 QQ 号 如果是主动退群, 则和 user_id 相同 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getOperatorId() { + return operatorId; + } + + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + + @Override + public String toString() { + return "GroupDecreaseNotice{" + + "subType='" + subType + '\'' + + ", operatorId=" + operatorId + + "} " + super.toString(); + } +} + + diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupFileUploadNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupFileUploadNotice.java new file mode 100644 index 0000000..c0b9538 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupFileUploadNotice.java @@ -0,0 +1,96 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 文件上传 + */ +public class GroupFileUploadNotice extends Notice { + private Long groupId;//群号 + private Long userId;//发送者 QQ 号 + private File file; + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + @Override + public String toString() { + return "GroupFileUploadNotice{" + + "groupId=" + groupId + + ", userId=" + userId + + ", file=" + file + + "} " + super.toString(); + } + + public class File { + private String id;//文件 ID + private String name;//文件名 + private Long size;//文件大小 + private Long busid; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getSize() { + return size; + } + + public void setSize(Long size) { + this.size = size; + } + + public Long getBusid() { + return busid; + } + + public void setBusid(Long busid) { + this.busid = busid; + } + + @Override + public String toString() { + return "File{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + ", size=" + size + + ", busid=" + busid + + '}'; + } + } +} + + diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupHonorNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupHonorNotice.java new file mode 100644 index 0000000..be018e4 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupHonorNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群成员荣誉变更提示 + */ +public class GroupHonorNotice extends GroupNotice { + private String subType;//提示类型 honor + private String honorType;//talkative:龙王 performer:群聊之火 emotion:快乐源泉 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public String getHonorType() { + return honorType; + } + + public void setHonorType(String honorType) { + this.honorType = honorType; + } + + @Override + public String toString() { + return "GroupHonorNotice{" + + "subType='" + subType + '\'' + + ", honorType='" + honorType + '\'' + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupIncreaseNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupIncreaseNotice.java new file mode 100644 index 0000000..589fb01 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupIncreaseNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群成员增加 + */ +public class GroupIncreaseNotice extends GroupNotice { + private String subType;//approve管理员同意 invite管理员邀请 + private Long operatorId;//操作者 QQ 号 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getOperatorId() { + return operatorId; + } + + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + + @Override + public String toString() { + return "GroupIncreaseNotice{" + + "subType='" + subType + '\'' + + ", operatorId=" + operatorId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupLuckyKingNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupLuckyKingNotice.java new file mode 100644 index 0000000..df5c5a9 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupLuckyKingNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群红包运气王提示 + */ +public class GroupLuckyKingNotice extends GroupNotice { + private String subType;//lucky_king 提示类型 + private Long targetId;//运气王id + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getTargetId() { + return targetId; + } + + public void setTargetId(Long targetId) { + this.targetId = targetId; + } + + @Override + public String toString() { + return "GroupLuckyKingNotice{" + + "subType='" + subType + '\'' + + ", targetId=" + targetId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupPokeNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupPokeNotice.java new file mode 100644 index 0000000..f776ff2 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupPokeNotice.java @@ -0,0 +1,36 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群内戳一戳 + */ +public class GroupPokeNotice extends GroupNotice { + private String subType;//poke 提示类型 + private Long targetId;//被戳者 QQ 号 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getTargetId() { + return targetId; + } + + public void setTargetId(Long targetId) { + this.targetId = targetId; + } + + @Override + public String toString() { + return "GroupPokeNotice{" + + "subType='" + subType + '\'' + + ", targetId=" + targetId + + "} " + super.toString(); + } +} + diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/GroupRecallNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/GroupRecallNotice.java new file mode 100644 index 0000000..a27cfdb --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/GroupRecallNotice.java @@ -0,0 +1,35 @@ +package sdk.event.notice; + +import sdk.event.global.GroupNotice; + +/** + * 群消息撤回 + */ +public class GroupRecallNotice extends GroupNotice { + private Long operatorId;//操作者 QQ 号 + private Long messageId;//被撤回的消息 ID + + public Long getOperatorId() { + return operatorId; + } + + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + + public Long getMessageId() { + return messageId; + } + + public void setMessageId(Long messageId) { + this.messageId = messageId; + } + + @Override + public String toString() { + return "GroupRecallNotice{" + + "operatorId=" + operatorId + + ", messageId=" + messageId + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/notice/OfflineFileNotice.java b/plumbot-bungee/src/main/java/sdk/event/notice/OfflineFileNotice.java new file mode 100644 index 0000000..274d5e4 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/notice/OfflineFileNotice.java @@ -0,0 +1,74 @@ +package sdk.event.notice; + +import sdk.event.global.Notice; + +/** + * 接收到离线文件 + */ +public class OfflineFileNotice extends Notice { + private String userId;//发送者id + private File file;//文件数据 + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + @Override + public String toString() { + return "OfflineFileNotice{" + + "userId='" + userId + '\'' + + ", file=" + file + + "} " + super.toString(); + } + + public class File { + private String name;//文件名 + private Long size;//文件大小 + private String url;//下载链接 + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getSize() { + return size; + } + + public void setSize(Long size) { + this.size = size; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + return "File{" + + "name='" + name + '\'' + + ", size=" + size + + ", url='" + url + '\'' + + '}'; + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/request/FriendRequest.java b/plumbot-bungee/src/main/java/sdk/event/request/FriendRequest.java new file mode 100644 index 0000000..f6c0cd5 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/request/FriendRequest.java @@ -0,0 +1,45 @@ +package sdk.event.request; + +import sdk.event.global.Request; + +/** + * 添加好友请求 + */ +public class FriendRequest extends Request { + private String flag; + private Long userId; + private String comment; + + public String getFlag() { + return flag; + } + + public void setFlag(String flag) { + this.flag = flag; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + @Override + public String toString() { + return "FriendRequest{" + + "flag='" + flag + '\'' + + ", userId=" + userId + + ", comment='" + comment + '\'' + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/event/request/GroupRequest.java b/plumbot-bungee/src/main/java/sdk/event/request/GroupRequest.java new file mode 100644 index 0000000..a8448d2 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/event/request/GroupRequest.java @@ -0,0 +1,65 @@ +package sdk.event.request; + +import sdk.event.global.Request; + +/** + * 加群请求 + */ +public class GroupRequest extends Request { + private String subType;//邀请还是申请 + private Long groupId;//群号 + private Long userId;//发送请求的 QQ 号 + private String comment;//验证信息 + private String flag;//请求 flag, 在调用处理请求的 API 时需要传入 + + public String getSubType() { + return subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public Long getGroupId() { + return groupId; + } + + public void setGroupId(Long groupId) { + this.groupId = groupId; + } + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getFlag() { + return flag; + } + + public void setFlag(String flag) { + this.flag = flag; + } + + @Override + public String toString() { + return "GroupRequest{" + + "subType='" + subType + '\'' + + ", groupId=" + groupId + + ", userId=" + userId + + ", comment='" + comment + '\'' + + ", flag='" + flag + '\'' + + "} " + super.toString(); + } +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/DefaultHandlerListener.java b/plumbot-bungee/src/main/java/sdk/listener/DefaultHandlerListener.java new file mode 100644 index 0000000..566ab1c --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/DefaultHandlerListener.java @@ -0,0 +1,41 @@ +package sdk.listener; + +import sdk.listener.handler.Handler; + +import java.util.HashMap; +import java.util.Map; + +/** + * 增加处理器分发功能 + * 一般给私聊或者群聊消息使用 + * + * @param + */ +public abstract class DefaultHandlerListener extends SimpleListener { + protected Map> handlerMap = new HashMap<>(); + + public Map> getHandlerMap() { + return handlerMap; + } + + public void setHandlerMap(Map> handlerMap) { + this.handlerMap = handlerMap; + } + + public void addHandler(String key, Handler handler) { + handlerMap.put(key, handler); + } + + public void removeHandler(String key) { + handlerMap.remove(key); + } + + public Handler getHandler(String key) { + return handlerMap.get(key); + } + + public Boolean contains(String key) { + return handlerMap.containsKey(key); + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/EnableListener.java b/plumbot-bungee/src/main/java/sdk/listener/EnableListener.java new file mode 100644 index 0000000..dabd411 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/EnableListener.java @@ -0,0 +1,23 @@ +package sdk.listener; + +/** + * 提供是否开启插件 + * @param + */ +public abstract class EnableListener implements Listener { + + private Boolean enable = true;//默认开启 + + public void setEnable(Boolean enable) { + this.enable = enable; + } + + public Boolean getEnable() { + return enable; + } + + public Boolean enable() { + return enable; + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/Listener.java b/plumbot-bungee/src/main/java/sdk/listener/Listener.java new file mode 100644 index 0000000..68edcd7 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/Listener.java @@ -0,0 +1,17 @@ +package sdk.listener; + +/** + * 监听器 + * + * @param + */ +public interface Listener extends VailderListener { + + /** + * 监听到消息 + * + * @param t 消息实体 + */ + void onMessage(T t); + +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/SimpleListener.java b/plumbot-bungee/src/main/java/sdk/listener/SimpleListener.java new file mode 100644 index 0000000..278c7e4 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/SimpleListener.java @@ -0,0 +1,4 @@ +package sdk.listener; + +public abstract class SimpleListener extends EnableListener { +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/VailderListener.java b/plumbot-bungee/src/main/java/sdk/listener/VailderListener.java new file mode 100644 index 0000000..3599bfb --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/VailderListener.java @@ -0,0 +1,18 @@ +package sdk.listener; + +/** + * 提供是否预先校验 + * @param + */ +public interface VailderListener { + + /** + * 验证方法 在onMessage前调用,返回false时不调用onMessage + * + * @param t 消息实体 + * @return 返回true时调用onMessage 否则跳过 + */ + default Boolean valider(T t) { + return true; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/handler/Handler.java b/plumbot-bungee/src/main/java/sdk/listener/handler/Handler.java new file mode 100644 index 0000000..ff10437 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/handler/Handler.java @@ -0,0 +1,10 @@ +package sdk.listener.handler; + +/** + * 处理器 + * + * @param + */ +public interface Handler { + void handle(T t); +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/impl/GroupMessageListener.java b/plumbot-bungee/src/main/java/sdk/listener/impl/GroupMessageListener.java new file mode 100644 index 0000000..2a2039f --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/impl/GroupMessageListener.java @@ -0,0 +1,22 @@ +package sdk.listener.impl; + +import sdk.event.message.GroupMessage; +import sdk.listener.DefaultHandlerListener; +import sdk.listener.handler.Handler; + +public class GroupMessageListener extends DefaultHandlerListener { + + @Override + public void onMessage(GroupMessage groupMessage) { + //处理逻辑 + String message = groupMessage.getMessage(); + long id = groupMessage.getGroupId(); + String[] split = message.split(" "); + String key = split[0]; + Handler handler = getHandler(key); + if (handler != null && id == 4130625468L) { + handler.handle(groupMessage); + } + } + +} diff --git a/plumbot-bungee/src/main/java/sdk/listener/impl/PrivateMessageListener.java b/plumbot-bungee/src/main/java/sdk/listener/impl/PrivateMessageListener.java new file mode 100644 index 0000000..9bd3287 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/listener/impl/PrivateMessageListener.java @@ -0,0 +1,20 @@ +package sdk.listener.impl; + +import sdk.event.message.PrivateMessage; +import sdk.listener.DefaultHandlerListener; +import sdk.listener.handler.Handler; + +public class PrivateMessageListener extends DefaultHandlerListener { + + @Override + public void onMessage(PrivateMessage privateMessage) { + //处理逻辑 + String message = privateMessage.getMessage(); + String[] split = message.split(" "); + String key = split[0]; + Handler handler = getHandler(key); + if (handler != null) { + handler.handle(privateMessage); + } + } +} diff --git a/plumbot-bungee/src/main/java/sdk/type/HonorType.java b/plumbot-bungee/src/main/java/sdk/type/HonorType.java new file mode 100644 index 0000000..e8700ad --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/type/HonorType.java @@ -0,0 +1,25 @@ +package sdk.type; + +/** + * 群聊荣誉 + */ +public enum HonorType { + + TALKATIVE("talkative"),//龙王 + PERFORMER("performer"),//群聊之火 + LEGENF("legend"),//群聊炽焰 + STRONG_NEWBIE("strong_newbie"),//冒尖小春笋 + EMOTION("emotion"),//快乐之源 + ALL("all"),//所有 + ; + + private String value; + + HonorType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/type/SubType.java b/plumbot-bungee/src/main/java/sdk/type/SubType.java new file mode 100644 index 0000000..061a0b7 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/type/SubType.java @@ -0,0 +1,20 @@ +package sdk.type; + +/** + * 提交类型,可能自定义会更好 + */ +public enum SubType { + + POKE("poke"),//戳一戳 + ; + + private String value; + + SubType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } +} diff --git a/plumbot-bungee/src/main/java/sdk/utils/ListenerUtils.java b/plumbot-bungee/src/main/java/sdk/utils/ListenerUtils.java new file mode 100644 index 0000000..4a24295 --- /dev/null +++ b/plumbot-bungee/src/main/java/sdk/utils/ListenerUtils.java @@ -0,0 +1,57 @@ +package sdk.utils; + + +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import sdk.config.MessageConfig; +import sdk.event.global.Message; +import sdk.type.SubType; + +public class ListenerUtils { + + + public static Class getMessageType(String message) { + return getMessageType(JSONUtil.parseObj(message)); + } + + /** + * 获取消息对应的实体类型 + * + * @param object + * @return + */ + public static Class getMessageType(JSONObject object) { + String type = null; + String postType = object.getStr("post_type"); + if ("message".equals(postType)) { + //消息类型 + String messageType = object.getStr("message_type"); + if ("group".equals(messageType)) { + //群聊消息类型 + type = "groupMessage"; + } else if ("private".equals(messageType)) { + //私聊消息类型 + type = "privateMessage"; + } + } else if ("request".equals(postType)) { + //请求类型 + String requestType = object.getStr("request_type"); + type = requestType; + } else if ("notice".equals(postType)) { + //通知类型 + String noticeType = object.getStr("notice_type"); + if ("notify".equals(noticeType) && SubType.POKE.getValue().equals(object.getStr("sub_type"))) { + //戳一戳单独处理 + Long groupId = object.getLong("group_id"); + if (!(groupId == null) && groupId > 0) { + type = "group_poke";//群聊戳一戳 + } else { + type = "friend_poke";//私聊戳一戳 + } + } else { + type = noticeType; + } + } + return MessageConfig.MessageMap.get(type); + } +} diff --git a/plumbot-bungee/src/main/resources/bot.yml b/plumbot-bungee/src/main/resources/bot.yml new file mode 100644 index 0000000..815ad9b --- /dev/null +++ b/plumbot-bungee/src/main/resources/bot.yml @@ -0,0 +1,27 @@ +#Bot配置 +Ver: '1.3.0' + +Bot: + Mode: "kook" + #机器人模式,可选go-cqhttp、kook + go-cqhttp: + Http: "http://127.0.0.1:5700" + #go-cqhttp的config文件中的adapters下http的address字符串 + Token: "" + #go-cqhttp是否开启了access-token模式,如是,请填写,如否,则该项无效 + IsAccessToken: false + #go-cqhttp是否开启了access-token模式 + ListenPort: 5701 + #插件监听的端口号,请在go-cqhttp的config文件中的adapters下http的post里面仿照示例添加且仅添加url为插件所在服务器ip:端口 + Kook: + #kook机器人,只支持websocket + Token: "" + #kook机器人Token + +Groups: + - 111 + #启用消息转发功能的群聊qq,也是一个长整形 + +Admins: + - 111 + #管理员的qq,还是一个长整形 diff --git a/plumbot-bungee/src/main/resources/bungee.yml b/plumbot-bungee/src/main/resources/bungee.yml new file mode 100644 index 0000000..65d2fc7 --- /dev/null +++ b/plumbot-bungee/src/main/resources/bungee.yml @@ -0,0 +1,13 @@ +name: PlumBot +version: '${project.version}' +main: me.regadpole.plumbot.PlumBot +author: RegadPole +api-version: 1.13 +prefix: PlumBot +commands: + plumbot: + aliases: [pb,PlumBot] + description: PlumBot基本命令. + usage: / + permission: plumbot.command + permission-message: 你不能执行它. diff --git a/plumbot-bungee/src/main/resources/config.yml b/plumbot-bungee/src/main/resources/config.yml new file mode 100644 index 0000000..2f74e91 --- /dev/null +++ b/plumbot-bungee/src/main/resources/config.yml @@ -0,0 +1,55 @@ +#机器人功能设置 +Ver: "1.3.1" + +#QQ群聊命令前缀 +Prefix: "/" + +#消息转发 +Forwarding: + enable: true + mode: 0 #mode设为0即无条件转发消息,设为1则消息前有前缀才会转发消息 + prefix: "#" + +#白名单 +WhiteList: + enable: false + kickMsg: "请加入qq群:xxx申请白名单" + +#进出提示 +JoinAndLeave: true + +#在线玩家查询 +Online: true + +#自定义回复 +SDR: true + +#maven仓库地址,默认为官方仓库,如速度慢或下载失败可更换为镜像仓库 +#此值为空时默认使用官方仓库 +Maven: "https://repo1.maven.org/maven2" + +database: + type: sqlite + settings: + sqlite: + path: "%plugin_folder%/database.db" + mysql: + host: localhost + port: 3306 + database: plumbot + user: plumbot + password: plumbot + parameters: "?useSSL=false" + pool: + connectionTimeout: 30000 + idleTimeout: 600000 + maxLifetime: 1800000 + maximumPoolSize: 15 + keepaliveTime: 0 + minimumIdle: 5 + #当服务端出现类似 + #“Receiver class org.sqlite.Conn does not define or + # inherit an implementation of the resolved method 'abstract boolean isValid(int)' + # of interface java.sql.Connection.” + #报错时,将下面配置取消注释 + #connectionTestQuery: "SELECT 1" \ No newline at end of file diff --git a/plumbot-bungee/src/main/resources/kook/kbc.yml b/plumbot-bungee/src/main/resources/kook/kbc.yml new file mode 100644 index 0000000..e3edacd --- /dev/null +++ b/plumbot-bungee/src/main/resources/kook/kbc.yml @@ -0,0 +1,43 @@ +# This is the configuration file of KookBC. +# You can configure many options here. + +### ------ BOT CONFIGURATION ------ ### +# Tips: The values of the items in this section will be used instead of the values from command line. +# The values from the command line will be used only if the appropriate value is not provided here. + +# The UUID of your Bot in the BotMarket. (see https://www.botmarket.cn) +# If you provided non-null value and it is a valid value, KookBC will schedule a task for pinging BotMarket. +botmarket-uuid: "" + +# If true, the data from Websocket server will be compressed. +# If you want to save the Internet flow, turn it to true. +# Tips: this item can't affect the Webhook mode. +compress: true + +# If true, when the internal commands that can't be used for users got call from user events, +# the executor will simply return. +# If false, a message will be sent to the user that sent the request. +ignore-remote-call-invisible-internal-command: true + +# If true, when the console executed a command, the content of command line +# and execute time will be stored in the ".console_history" file in KookBC folder. +save-console-history: true + +# UNSAFE! Are you sure? Are you really need this? +# If true, the event handler will ignore the order of events (SN). +# But we will do our best to ensure that what has been dealt with will not be dealt with again. +ignore-sn-order: false + +# Turn this option to true to enable the update checker! +check-update: false + +# If true, we will add two lines about KookBC's introduction and the repository link to command help. +# Please don't set it to false, it won't impact the performance! +allow-help-ad: true + +# Whether to register internal commands. +internal-commands: + plugins: true + +# Allow command exception feedback to the sender +allow-error-feedback: true \ No newline at end of file diff --git a/plumbot-bungee/src/main/resources/returns.yml b/plumbot-bungee/src/main/resources/returns.yml new file mode 100644 index 0000000..10ae1ee --- /dev/null +++ b/plumbot-bungee/src/main/resources/returns.yml @@ -0,0 +1,4 @@ +#自定义回复配置 +Ver: '1.2' + +自定义回复的关键词: 自定义回复的内容 diff --git a/plumbot-velocity/pom.xml b/plumbot-velocity/pom.xml index 8e29a41..d90cc81 100644 --- a/plumbot-velocity/pom.xml +++ b/plumbot-velocity/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.1 + 1.3.2 plumbot-velocity diff --git a/plumbot-velocity/src/main/java/me/regadpole/plumbot/PlumBot.java b/plumbot-velocity/src/main/java/me/regadpole/plumbot/PlumBot.java index 93c22ce..85ccf54 100644 --- a/plumbot-velocity/src/main/java/me/regadpole/plumbot/PlumBot.java +++ b/plumbot-velocity/src/main/java/me/regadpole/plumbot/PlumBot.java @@ -21,6 +21,7 @@ import me.regadpole.plumbot.internal.Config; import me.regadpole.plumbot.internal.DbConfig; import me.regadpole.plumbot.internal.Dependencies; +import me.regadpole.plumbot.internal.Environment; import me.regadpole.plumbot.internal.database.Database; import me.regadpole.plumbot.internal.database.DatabaseManager; import me.regadpole.plumbot.internal.database.MySQL; @@ -37,8 +38,8 @@ import java.util.Map; import java.util.Objects; -@Plugin(id = "plumbot", name = "PlumBot", version = "1.3.0-beta1", - url = "https://github.com/RegadPoleCN/PlumBot", description = "A plugin for Minecraft!", authors = {"Linear,RegadPole"}) +@Plugin(id = "plumbot", name = "PlumBot", version = "1.3.2", + url = "https://github.com/RegadPoleCN/PlumBot", description = "A bot plugin for QQ or Kook.", authors = {"Linear,RegadPole"}) public class PlumBot { private final ProxyServer server; @@ -48,6 +49,7 @@ public class PlumBot { private final Metrics.Factory metricsFactory; public VelocityConfig vconf; private static Bot bot; + private static Environment environment; public static PlumBot INSTANCE; private static Database database; @@ -129,6 +131,8 @@ public void onProxyInitialization(ProxyInitializeEvent event) { int pluginId = 19428; Metrics metrics = metricsFactory.make(this, pluginId); metrics.addCustomChart(new Metrics.SimplePie("chart_id", () -> "value")); + + environment = new Environment(); logger.info("PlumBot 已启动"); @@ -179,4 +183,5 @@ public static Database getDatabase() { public void setDatabase(Database database) { PlumBot.database = database; } + public Environment getEnvironment() {return environment;} } \ No newline at end of file diff --git a/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/Bot.java b/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/Bot.java index 85d5991..ce4f3a2 100644 --- a/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/Bot.java +++ b/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/Bot.java @@ -1,12 +1,9 @@ package me.regadpole.plumbot.bot; -import snw.jkook.message.component.BaseComponent; - public interface Bot { void start(); void shutdown(); void sendMsg(boolean isGroup, String message, long id); - default void sendMsg(boolean isGroup, BaseComponent message, long id) {} String getGroupName(long groupId); boolean checkUserInGroup(long userId, long groupId); } diff --git a/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/KookBot.java b/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/KookBot.java index d9125f4..f50548c 100644 --- a/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/KookBot.java +++ b/plumbot-velocity/src/main/java/me/regadpole/plumbot/bot/KookBot.java @@ -84,7 +84,6 @@ public void sendMsg(boolean isGroup, String message, long id) { }).schedule(); } - @Override public void sendMsg(boolean isGroup, BaseComponent message, long id) { if (id == 0L) {return;} if (message.toString().isEmpty()) {return;} diff --git a/plumbot-velocity/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-velocity/src/main/java/me/regadpole/plumbot/command/Commands.java index 8432d98..6d04503 100644 --- a/plumbot-velocity/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-velocity/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -4,6 +4,8 @@ import com.velocitypowered.api.command.SimpleCommand; import me.regadpole.plumbot.PlumBot; import me.regadpole.plumbot.bot.KookBot; +import me.regadpole.plumbot.internal.Config; +import me.regadpole.plumbot.internal.DbConfig; import me.regadpole.plumbot.internal.database.DatabaseManager; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; @@ -34,6 +36,16 @@ public void execute(Invocation invocation) { return; } switch (args[0].toLowerCase()) { + case "info": + StringBuilder stringbuilder = new StringBuilder(); + stringbuilder.append("§1---PlumBot 信息---").append("\n"); + stringbuilder.append("§a作者: ").append("§f").append(plugin.getEnvironment().author).append("\n"); + stringbuilder.append("§a版本: ").append("§f").append(plugin.getEnvironment().version).append("\n"); + stringbuilder.append("§a机器人平台: ").append("§f").append(Config.bot.Bot.Mode).append("\n"); + stringbuilder.append("§a数据库模式: ").append("§f").append(DbConfig.type).append("\n"); + stringbuilder.append("§a服务端版本: ").append("§f").append(plugin.getServer().getVersion().toString()).append("\n"); + source.sendMessage(Component.text(stringbuilder.toString())); + break; case "reload": { if (source.hasPermission("plumbot.command")) { try { @@ -54,6 +66,7 @@ public void execute(Invocation invocation) { case "help": { source.sendMessage(Component.text("§6PlumBot 机器人帮助菜单")); source.sendMessage(Component.text("§6/pb reload :§f重载插件")); + source.sendMessage(Component.text("§6/pb info :§f插件基本信息")); source.sendMessage(Component.text("§6/pb help :§f获取插件帮助")); break; } diff --git a/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Dependencies.java b/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Dependencies.java index 4ae8d07..69621af 100644 --- a/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Dependencies.java +++ b/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Dependencies.java @@ -15,7 +15,8 @@ @MavenLibrary(groupId = snakeyaml.groupId, artifactId = snakeyaml.artifactId, version = snakeyaml.version), @MavenLibrary(groupId = HikariCP.groupId, artifactId = HikariCP.artifactId, version = HikariCP.version), @MavenLibrary(groupId = MySQL.groupId, artifactId = MySQL.artifactId, version = MySQL.version), - @MavenLibrary(groupId = sqlite.groupId, artifactId = sqlite.artifactId, version = sqlite.version)}) + @MavenLibrary(groupId = sqlite.groupId, artifactId = sqlite.artifactId, version = sqlite.version), + @MavenLibrary(groupId = kookbc.groupId, artifactId = kookbc.artifactId, version = kookbc.version)}) public class Dependencies { public static class hutool{ public static final String groupId = "cn.hutool"; @@ -68,4 +69,9 @@ public static class sqlite{ public static final String artifactId = "sqlite-jdbc"; public static final String version = "3.42.0.0"; } + public static class kookbc{ + public static final String groupId = "com.github.SNWCreations"; + public static final String artifactId = "KookBC"; + public static final String version = "0.27.4"; + } } diff --git a/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Environment.java b/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Environment.java new file mode 100644 index 0000000..d1c6414 --- /dev/null +++ b/plumbot-velocity/src/main/java/me/regadpole/plumbot/internal/Environment.java @@ -0,0 +1,22 @@ +package me.regadpole.plumbot.internal; + +import me.regadpole.plumbot.PlumBot; + +import java.util.Iterator; + +public final class Environment { + private final PlumBot plugin = PlumBot.INSTANCE; + public final String name = plugin.getPluginContainer().getDescription().getName().get(); + public final String version = plugin.getPluginContainer().getDescription().getVersion().get(); + public final String author = getAuthorString(); + + + private String getAuthorString() { + Iterator authors = plugin.getPluginContainer().getDescription().getAuthors().iterator(); + StringBuilder stringBuilder = new StringBuilder(); + while(authors.hasNext()){ + stringBuilder.append(authors.next()).append(", "); + } + return stringBuilder.substring(0, stringBuilder.lastIndexOf(",")-1); + } +} diff --git a/pom.xml b/pom.xml index c62a4f3..c1f2320 100644 --- a/pom.xml +++ b/pom.xml @@ -6,13 +6,14 @@ me.regadpole plumbot - 1.3.1 + 1.3.2 pom PlumBot plumbot-velocity plumbot-bukkit + plumbot-bungee @@ -96,7 +97,7 @@ com.github.SNWCreations KookBC 0.27.4 - compile + provided net.kyori @@ -159,6 +160,12 @@ 3.42.0.0 provided + + com.mikuac + shiro + 2.2.2 + provided + From 293a5c3f7fa1f27a7a62a7ef02a83dc3446b5325 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Thu, 23 May 2024 17:24:43 +0800 Subject: [PATCH 03/16] fix --- .../java/me/regadpole/plumbot/internal/Dependencies.java | 1 - pom.xml | 8 +------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java index 7922533..57f2bd4 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java @@ -1,6 +1,5 @@ package me.regadpole.plumbot.internal; -import com.ghostchu.quickshop.util.config.UpdateScript; import me.regadpole.plumbot.internal.maven.MavenLibraries; import me.regadpole.plumbot.internal.maven.MavenLibrary; diff --git a/pom.xml b/pom.xml index c1f2320..8e544af 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ com.github.SNWCreations KookBC 0.27.4 - provided + compile net.kyori @@ -160,12 +160,6 @@ 3.42.0.0 provided - - com.mikuac - shiro - 2.2.2 - provided - From 6a7a966965738bd1f1d2036a74d859e8f0e486e4 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Thu, 23 May 2024 17:47:12 +0800 Subject: [PATCH 04/16] fix --- .../java/me/regadpole/plumbot/internal/Dependencies.java | 1 - pom.xml | 8 +------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java index 7922533..57f2bd4 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Dependencies.java @@ -1,6 +1,5 @@ package me.regadpole.plumbot.internal; -import com.ghostchu.quickshop.util.config.UpdateScript; import me.regadpole.plumbot.internal.maven.MavenLibraries; import me.regadpole.plumbot.internal.maven.MavenLibrary; diff --git a/pom.xml b/pom.xml index c1f2320..8e544af 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ com.github.SNWCreations KookBC 0.27.4 - provided + compile net.kyori @@ -160,12 +160,6 @@ 3.42.0.0 provided - - com.mikuac - shiro - 2.2.2 - provided - From b8208418dc34f6823982c61cddafcc5c1348e76b Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Thu, 20 Jun 2024 17:31:46 +0800 Subject: [PATCH 05/16] =?UTF-8?q?1.=E7=AE=A1=E7=90=86=E5=91=98=E7=99=BD?= =?UTF-8?q?=E5=90=8D=E5=8D=95limitless=202.=E7=AE=A1=E7=90=86=E4=B8=A5?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E7=94=A8=E6=88=B7=E7=99=BD=E5=90=8D=E5=8D=95?= =?UTF-8?q?remake=20git=20commit=20-m?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plumbot-bukkit/pom.xml | 2 +- .../regadpole/plumbot/command/Commands.java | 65 ++++++ .../me/regadpole/plumbot/config/Config.java | 6 +- .../plumbot/event/kook/KookEvent.java | 14 +- .../regadpole/plumbot/event/qq/QQEvent.java | 203 +++++++++++++----- .../plumbot/internal/WhitelistHelper.java | 28 +++ .../internal/database/DatabaseManager.java | 110 +++++++--- plumbot-bukkit/src/main/resources/config.yml | 3 +- plumbot-bungee/pom.xml | 2 +- plumbot-velocity/pom.xml | 2 +- pom.xml | 4 +- 11 files changed, 347 insertions(+), 92 deletions(-) create mode 100644 plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java diff --git a/plumbot-bukkit/pom.xml b/plumbot-bukkit/pom.xml index 702269a..8f0146f 100644 --- a/plumbot-bukkit/pom.xml +++ b/plumbot-bukkit/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 plumbot-bukkit diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java index 7e53519..ece2e0a 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -4,6 +4,7 @@ import me.regadpole.plumbot.bot.KookBot; import me.regadpole.plumbot.config.Config; import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.internal.WhitelistHelper; import me.regadpole.plumbot.internal.database.DatabaseManager; import org.bukkit.Bukkit; import org.bukkit.command.Command; @@ -13,6 +14,7 @@ import snw.jkook.plugin.Plugin; import java.util.Arrays; +import java.util.List; import java.util.stream.Collectors; public class Commands implements CommandExecutor{ @@ -65,6 +67,69 @@ public boolean onCommand(CommandSender sender, Command command, String label, St sender.sendMessage("§6/pb info :§f插件基本信息"); sender.sendMessage("§6/pb kook help :§f获取kook帮助"); sender.sendMessage("§6/pb kook plugins :§f获取kook插件列表"); + sender.sendMessage("§6/pb queryBind :§f查询id或qq绑定数据"); + sender.sendMessage("§6/pb addBind :§f为qq添加ID白名单"); + break; + case "queryBind": + if (args.length == 1) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length > 2) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length == 2) { + if (args[1].startsWith("id:")) { + String name = args[1].substring(3); + if (name.isEmpty()) { + sender.sendMessage("id不能为空"); + return true; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (qq==0L) { + sender.sendMessage("ID尚未申请白名单"); + return; + } + sender.sendMessage(name+"的申请用户为"+qq); + }); + return true; + } else if (args[1].startsWith("qq:")) { + String qq = args[1].substring(3); + if (qq.isEmpty()) { + sender.sendMessage("QQ不能为空"); + return true; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + sender.sendMessage(qq+"尚未申请白名单"); + return; + } + sender.sendMessage(qq+"拥有白名单ID:"+id); + }); + return true; + } + break; + } + case "addBind": + if (args.length == 1) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length > 2) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length == 2) { + if (!WhitelistHelper.checkIDNotExist(args[1])) { + sender.sendMessage("绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return true; + } + List id = WhitelistHelper.addAndGet(args[1], args[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + sender.sendMessage("成功申请白名单," + args[0] + "目前的白名单为" + id); + } break; case "kook": if (args.length == 1) { diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java index 01a162a..5233767 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java @@ -41,7 +41,7 @@ public static void createConfig(){ if (!Config.getBotYamlVersion().equals("1.3.0")){ INSTANCE.saveResource(botFile.getName(), true); } - if (!Config.getConfigYamlVersion().equals("1.3.1")){ + if (!Config.getConfigYamlVersion().equals("1.3.2")){ INSTANCE.saveResource(configFile.getName(), true); } if (!Config.getCommandsYamlVersion().equals("1.2.2")){ @@ -126,6 +126,10 @@ public static boolean WhiteList(){ return getConfigYaml().getBoolean("WhiteList.enable"); } + public static int WhiteListMaxCount(){ + return getConfigYaml().getInt("WhiteList.maxCount"); + } + public static boolean JoinAndLeave(){ return getConfigYaml().getBoolean("JoinAndLeave"); } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index bc2feb3..758bafc 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -126,8 +126,8 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null) { + List idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { e.getMessage().reply("尚未申请白名单"); return; } @@ -225,8 +225,8 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null || idForName.isEmpty()) { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { e.getMessage().reply("您尚未申请白名单"); return; } @@ -348,10 +348,10 @@ public void onPrivateMessageReceive(PrivateMessageReceivedEvent e) { public void onGroupDecreaseNotice(UserLeaveGuildEvent e) { String userId = e.getUser().getId(); String groupId = e.getGuildId(); - String player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (player == null) { + List player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player.isEmpty()) { return; } - DatabaseManager.removeBindid(player, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + DatabaseManager.removeBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); } } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index ed2e1d0..ad31f6e 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -8,6 +8,7 @@ import me.regadpole.plumbot.event.server.ServerManager; import me.regadpole.plumbot.event.server.ServerTps; import me.regadpole.plumbot.internal.FoliaSupport; +import me.regadpole.plumbot.internal.WhitelistHelper; import me.regadpole.plumbot.internal.database.DatabaseManager; import me.regadpole.plumbot.tool.StringTool; import org.bukkit.Bukkit; @@ -124,43 +125,54 @@ public void onGroupMessageReceive(GroupMessage e){ if (!Config.WhiteList()) { return; } - String name = matcher.group().replace(Prefix + "删除白名单 ", ""); - if (name.isEmpty()) { - bot.sendMsg(true, "id不能为空", groupID); + String para = matcher.group().replace(Prefix + "删除白名单 ", ""); + if (para.isEmpty()) { + bot.sendMsg(true, "参数不能为空", groupID); return; } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - long nameForId = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (nameForId == 0L) { - bot.sendMsg(true, "尚未申请白名单", groupID); + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); return; } - DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单", groupID); - }); - return; - } - - pattern = Pattern.compile(Prefix + "删除User白名单 .*"); - matcher = pattern.matcher(msg); - if (matcher.find()) { - if (!Config.WhiteList()) { - return; - } - String qq = matcher.group().replace(Prefix + "删除User白名单 ", ""); - if (qq.isEmpty()) { - bot.sendMsg(true, "QQ不能为空", groupID); - return; - } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null) { - bot.sendMsg(true, "尚未申请白名单", groupID); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + if (WhitelistHelper.checkIDNotExist(name)) { + bot.sendMsg(true, "ID尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单", groupID); + }); + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + bot.sendMsg(true, "QQ不能为空", groupID); return; } - DatabaseManager.removeBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单", groupID); - }); + String[] p = qq.split(" "); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(p[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, p[0]+"尚未申请白名单", groupID); + return; + } + int num = Integer.parseInt(p[1]); + DatabaseManager.removeBind(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,"+p[0]+"目前拥有的白名单为"+DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + }); + } else { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBind(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + }); + } return; } @@ -190,12 +202,14 @@ public void onGroupMessageReceive(GroupMessage e){ messages.add(Prefix+"在线人数 查看服务器当前在线人数"); messages.add(Prefix+"tps 查看服务器当前tps"); messages.add(Prefix+"申请白名单 为自己申请白名单"); - messages.add(Prefix+"删除白名单 删除自己的白名单"); + messages.add(Prefix+"删除白名单 <序号> 删除自己的白名单"); + messages.add(Prefix+"查询白名单 查询自己的白名单"); messages.add("管理命令:"); messages.add(Prefix+"cmd 向服务器发送命令"); - messages.add(Prefix+"删除白名单 删除指定游戏id的白名单"); - messages.add(Prefix+"删除User白名单 删除指定群成员的白名单"); - for (String message : messages) { + messages.add(Prefix+"申请白名单 为指定用户申请白名单"); + messages.add(Prefix+"删除白名单 删除指定游戏id或qq的白名单"); + messages.add(Prefix+"查询白名单 查询指定游戏id或qq的白名单"); + for (String message : messages) { if (messages.get(messages.size() - 1).equalsIgnoreCase(message)) { stringBuilder.append(message.replaceAll("§\\S", "")); } else { @@ -223,42 +237,129 @@ public void onGroupMessageReceive(GroupMessage e){ return; } - pattern = Pattern.compile(Prefix + "申请白名单 .*"); + pattern = Pattern.compile(Prefix + "查询白名单 .*"); matcher = pattern.matcher(msg); if (matcher.find()) { if (!Config.WhiteList()) { return; } - String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); - if (PlayerName.isEmpty()) { - bot.sendMsg(true, "id不能为空", groupID); - return; + if(Config.getAdmins().contains(senderID)) { + String para = matcher.group().replace(Prefix + "查询白名单 ", ""); + if (para.isEmpty()) { + bot.sendMsg(true, "参数不能为空", groupID); + return; + } + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (qq==0L) { + bot.sendMsg(true, "ID尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, name+"的申请用户为"+qq, groupID); + }); + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + bot.sendMsg(true, "QQ不能为空", groupID); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + bot.sendMsg(true, qq+"尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, qq+"拥有白名单ID:"+id, groupID); + }); + } else { + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, senderID+"拥有白名单ID:"+id, groupID); + }); + } } PlumBot.getScheduler().runTaskAsynchronously(() -> { - if ((DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()) != null) || (DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()) != 0L)) { - bot.sendMsg(true, "绑定失败", groupID); + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - DatabaseManager.addBind(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功申请白名单", groupID); + bot.sendMsg(true, senderID +"拥有白名单ID:"+idForName, groupID); }); return; } - pattern = Pattern.compile(Prefix + "删除白名单"); + pattern = Pattern.compile(Prefix + "申请白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); + String[] para = PlayerName.split(" "); + if (para.length==1){ + if (PlayerName.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); + return; + } + if(Config.getAdmins().contains(senderID)) { + if (!WhitelistHelper.checkIDNotExist(PlayerName)) { + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + if (WhitelistHelper.checkCount(String.valueOf(senderID))) { + bot.sendMsg(true, "绑定失败,该用户已绑定:"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + if (!WhitelistHelper.checkIDNotExist(PlayerName)){ + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + }); + } else if (para.length==2) { + if(Config.getAdmins().contains(senderID)) { + if (!WhitelistHelper.checkIDNotExist(para[1])) { + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,"+para[0]+"目前的白名单为"+id, groupID); + } + } + return; + } + + pattern = Pattern.compile(Prefix + "删除白名单 .*"); matcher = pattern.matcher(msg); if (matcher.find()) { if (!Config.WhiteList()) { return; } + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null || idForName.isEmpty()) { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - DatabaseManager.removeBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单", groupID); + DatabaseManager.removeBind(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前的白名单为"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); }); return; } @@ -354,8 +455,8 @@ public void onGroupMessageReceive(GroupMessage e){ public void onGroupDecreaseNotice(GroupDecreaseNotice e) { long userId = e.getUserId(); long groupId = e.getGroupId(); - String player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (player == null) { + List player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player.isEmpty()) { return; } DatabaseManager.removeBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java new file mode 100644 index 0000000..4a6d5dd --- /dev/null +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java @@ -0,0 +1,28 @@ +package me.regadpole.plumbot.internal; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.internal.database.Database; +import me.regadpole.plumbot.internal.database.DatabaseManager; + +import java.util.List; + +public class WhitelistHelper { + + public static boolean checkCount(String qq){ + List idList = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + int maxCount = Config.WhiteListMaxCount(); + if (idList == null) return true; + return idList.size() < maxCount; + } + + public static boolean checkIDNotExist(String id){ + return DatabaseManager.getBindId(id, DataBase.type().toLowerCase(), PlumBot.getDatabase()) == 0L; + } + + public static List addAndGet(String id, String qq, String mode, Database db){ + DatabaseManager.addBind(id, qq, mode, db); + return DatabaseManager.getBind(qq, mode, db); + } +} diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java index a2c1870..45f487a 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -8,6 +8,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; public class DatabaseManager { @@ -62,13 +64,7 @@ public static void addBind(String id, String qq, String mode, Database db) { ResultSet resultSetid = statement.executeQuery(selectid); ResultSet resultSetqq = statement1.executeQuery(selectqq); - if (!resultSetid.isBeforeFirst() && resultSetqq.isBeforeFirst()) { - statement.executeUpdate(updateid); - } else if (resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - statement.executeUpdate(updateqq); - } else if (!resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - statement.executeUpdate(insert); - } + statement.executeUpdate(insert); resultSetid.close(); resultSetqq.close(); @@ -85,13 +81,7 @@ public static void addBind(String id, String qq, String mode, Database db) { ResultSet resultSetid = connection.prepareStatement(selectid).executeQuery(); ResultSet resultSetqq = connection.prepareStatement(selectqq).executeQuery(); - if (!resultSetid.isBeforeFirst() && resultSetqq.isBeforeFirst()) { - connection.prepareStatement(updateid).executeUpdate(); - } else if (resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - connection.prepareStatement(updateqq).executeUpdate(); - } else if (!resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - connection.prepareStatement(insert).executeUpdate(); - } + connection.prepareStatement(insert).executeUpdate(); resultSetid.close(); resultSetqq.close(); @@ -107,7 +97,7 @@ public static void addBind(String id, String qq, String mode, Database db) { public static void removeBindid(String id,String mode, Database db) { String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE id='" + id + "';"; String delete = "DELETE FROM whitelist WHERE id='" + id + "';"; try { @@ -149,9 +139,69 @@ public static void removeBindid(String id,String mode, Database db) { } } - public static void removeBind(String qq,String mode, Database db) { + public static void removeBind(String qq, int num, String mode, Database db) { String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + ";"; + + try { + Connection connection = db.getConnection(); + switch (mode){ + case "sqlite": + default: { + Statement statement = connection.createStatement(); + statement.executeUpdate(createTable); + + // 如果没有找到记录为false,找到就是true + ResultSet resultSet = statement.executeQuery(select); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + for (int i = 1; i < num; i++) { + resultSet.next(); + } + if (resultSet.isAfterLast()){ + return; + } + String id = resultSet.getString("id"); + String delete = "DELETE FROM whitelist WHERE qq=" + qq+" AND id='" + id + "';"; + statement.executeUpdate(delete); + resultSet.close(); + statement.close(); + connection.close(); + + break; + } + case "mysql": { + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSet = connection.prepareStatement(select).executeQuery(); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + for (int i = 1; i < num; i++) { + resultSet.next(); + } + if (resultSet.isAfterLast()){ + return; + } + String id = resultSet.getString("id"); + String delete = "DELETE FROM whitelist WHERE qq=" + qq+" AND id='" + id + "';"; + connection.prepareStatement(delete).executeUpdate(); + resultSet.close(); + connection.close(); + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public static void removeBind(String qq, String mode, Database db) { + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + ";"; String delete = "DELETE FROM whitelist WHERE qq=" + qq+";"; try { @@ -167,8 +217,8 @@ public static void removeBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); - statement.executeUpdate(delete); } + statement.executeUpdate(delete); resultSet.close(); statement.close(); connection.close(); @@ -182,8 +232,8 @@ public static void removeBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); - connection.prepareStatement(delete).executeUpdate(); } + connection.prepareStatement(delete).executeUpdate(); resultSet.close(); connection.close(); break; @@ -194,11 +244,11 @@ public static void removeBind(String qq,String mode, Database db) { } } - public static long getBindId(String id,String mode, Database db) { + public static long getBindId(String id, String mode, Database db) { long qq = 0L; String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE id='" + id + "' ;"; try { Connection connection = db.getConnection(); @@ -238,10 +288,9 @@ public static long getBindId(String id,String mode, Database db) { } return qq; } - - @Nullable - public static String getBind(String qq,String mode, Database db) { - String id = null; + + public static List getBind(String qq,String mode, Database db) { + List id = new ArrayList<>(); String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; @@ -257,7 +306,10 @@ public static String getBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); } - id = resultSet.getString("id"); + do { + id.add(resultSet.getString("id")); + resultSet.next(); + }while(!resultSet.isAfterLast()); resultSet.close(); connection.close(); break; @@ -272,7 +324,10 @@ public static String getBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); } - id = resultSet.getString("id"); + do { + id.add(resultSet.getString("id")); + resultSet.next(); + }while(!resultSet.isAfterLast()); resultSet.close(); statement.close(); connection.close(); @@ -285,4 +340,5 @@ public static String getBind(String qq,String mode, Database db) { } return id; } + } diff --git a/plumbot-bukkit/src/main/resources/config.yml b/plumbot-bukkit/src/main/resources/config.yml index 1da7596..8d1b245 100644 --- a/plumbot-bukkit/src/main/resources/config.yml +++ b/plumbot-bukkit/src/main/resources/config.yml @@ -1,5 +1,5 @@ #机器人功能设置 -Ver: "1.3.1" +Ver: "1.3.2" #QQ群聊命令前缀 Prefix: "/" @@ -17,6 +17,7 @@ DieReport: false WhiteList: enable: false kickMsg: "请加入qq群:xxx申请白名单" + maxCount: 1 #执行命令功能 CMD: true diff --git a/plumbot-bungee/pom.xml b/plumbot-bungee/pom.xml index 87d5ae9..24b3a68 100644 --- a/plumbot-bungee/pom.xml +++ b/plumbot-bungee/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 plumbot-bungee diff --git a/plumbot-velocity/pom.xml b/plumbot-velocity/pom.xml index d90cc81..2d1b455 100644 --- a/plumbot-velocity/pom.xml +++ b/plumbot-velocity/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 plumbot-velocity diff --git a/pom.xml b/pom.xml index 8e544af..d506f33 100644 --- a/pom.xml +++ b/pom.xml @@ -6,14 +6,14 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 pom PlumBot - plumbot-velocity plumbot-bukkit plumbot-bungee + plumbot-velocity From 83ed51959f797ccc6e74af6cbc26b38434824f13 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Thu, 20 Jun 2024 18:07:34 +0800 Subject: [PATCH 06/16] =?UTF-8?q?=20=20=20=201.=E7=AE=A1=E7=90=86=E5=91=98?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95limitless=20=20=20=20=202.=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=91=98=E5=88=A0=E9=99=A4=E7=99=BD=E5=90=8D=E5=8D=95?= =?UTF-8?q?remake=20=20=20=20=203.=E6=96=B0=E5=A2=9E=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E5=8A=9F=E8=83=BD=20=20=20=20=204.?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E6=95=B0=E9=87=8F=E5=8F=AF=E6=8E=A7?= =?UTF-8?q?=20=20=20=20=205.more....=20=20=20=20=20=E5=88=87=E8=AE=B0?= =?UTF-8?q?=E5=A4=87=E4=BB=BD=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E5=A4=B9?= =?UTF-8?q?=20=20=20=20=20=E8=AF=B7=E5=9C=A8=E4=BD=9C=E8=80=85=E6=8C=87?= =?UTF-8?q?=E5=AF=BC=E4=B8=8B=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plumbot-bukkit/pom.xml | 2 +- .../regadpole/plumbot/command/Commands.java | 65 ++++++ .../me/regadpole/plumbot/config/Config.java | 6 +- .../plumbot/event/kook/KookEvent.java | 14 +- .../regadpole/plumbot/event/qq/QQEvent.java | 203 +++++++++++++----- .../plumbot/internal/WhitelistHelper.java | 28 +++ .../internal/database/DatabaseManager.java | 110 +++++++--- plumbot-bukkit/src/main/resources/config.yml | 3 +- plumbot-bungee/pom.xml | 2 +- plumbot-velocity/pom.xml | 2 +- pom.xml | 4 +- 11 files changed, 347 insertions(+), 92 deletions(-) create mode 100644 plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java diff --git a/plumbot-bukkit/pom.xml b/plumbot-bukkit/pom.xml index 702269a..8f0146f 100644 --- a/plumbot-bukkit/pom.xml +++ b/plumbot-bukkit/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 plumbot-bukkit diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java index 7e53519..ece2e0a 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -4,6 +4,7 @@ import me.regadpole.plumbot.bot.KookBot; import me.regadpole.plumbot.config.Config; import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.internal.WhitelistHelper; import me.regadpole.plumbot.internal.database.DatabaseManager; import org.bukkit.Bukkit; import org.bukkit.command.Command; @@ -13,6 +14,7 @@ import snw.jkook.plugin.Plugin; import java.util.Arrays; +import java.util.List; import java.util.stream.Collectors; public class Commands implements CommandExecutor{ @@ -65,6 +67,69 @@ public boolean onCommand(CommandSender sender, Command command, String label, St sender.sendMessage("§6/pb info :§f插件基本信息"); sender.sendMessage("§6/pb kook help :§f获取kook帮助"); sender.sendMessage("§6/pb kook plugins :§f获取kook插件列表"); + sender.sendMessage("§6/pb queryBind :§f查询id或qq绑定数据"); + sender.sendMessage("§6/pb addBind :§f为qq添加ID白名单"); + break; + case "queryBind": + if (args.length == 1) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length > 2) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length == 2) { + if (args[1].startsWith("id:")) { + String name = args[1].substring(3); + if (name.isEmpty()) { + sender.sendMessage("id不能为空"); + return true; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (qq==0L) { + sender.sendMessage("ID尚未申请白名单"); + return; + } + sender.sendMessage(name+"的申请用户为"+qq); + }); + return true; + } else if (args[1].startsWith("qq:")) { + String qq = args[1].substring(3); + if (qq.isEmpty()) { + sender.sendMessage("QQ不能为空"); + return true; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + sender.sendMessage(qq+"尚未申请白名单"); + return; + } + sender.sendMessage(qq+"拥有白名单ID:"+id); + }); + return true; + } + break; + } + case "addBind": + if (args.length == 1) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length > 2) { + sender.sendMessage("命令错误,格式:/plumbot queryBind "); + return true; + } + if (args.length == 2) { + if (!WhitelistHelper.checkIDNotExist(args[1])) { + sender.sendMessage("绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return true; + } + List id = WhitelistHelper.addAndGet(args[1], args[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + sender.sendMessage("成功申请白名单," + args[0] + "目前的白名单为" + id); + } break; case "kook": if (args.length == 1) { diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java index 01a162a..5233767 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java @@ -41,7 +41,7 @@ public static void createConfig(){ if (!Config.getBotYamlVersion().equals("1.3.0")){ INSTANCE.saveResource(botFile.getName(), true); } - if (!Config.getConfigYamlVersion().equals("1.3.1")){ + if (!Config.getConfigYamlVersion().equals("1.3.2")){ INSTANCE.saveResource(configFile.getName(), true); } if (!Config.getCommandsYamlVersion().equals("1.2.2")){ @@ -126,6 +126,10 @@ public static boolean WhiteList(){ return getConfigYaml().getBoolean("WhiteList.enable"); } + public static int WhiteListMaxCount(){ + return getConfigYaml().getInt("WhiteList.maxCount"); + } + public static boolean JoinAndLeave(){ return getConfigYaml().getBoolean("JoinAndLeave"); } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index bc2feb3..758bafc 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -126,8 +126,8 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null) { + List idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { e.getMessage().reply("尚未申请白名单"); return; } @@ -225,8 +225,8 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null || idForName.isEmpty()) { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { e.getMessage().reply("您尚未申请白名单"); return; } @@ -348,10 +348,10 @@ public void onPrivateMessageReceive(PrivateMessageReceivedEvent e) { public void onGroupDecreaseNotice(UserLeaveGuildEvent e) { String userId = e.getUser().getId(); String groupId = e.getGuildId(); - String player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (player == null) { + List player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player.isEmpty()) { return; } - DatabaseManager.removeBindid(player, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + DatabaseManager.removeBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); } } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index ed2e1d0..ad31f6e 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -8,6 +8,7 @@ import me.regadpole.plumbot.event.server.ServerManager; import me.regadpole.plumbot.event.server.ServerTps; import me.regadpole.plumbot.internal.FoliaSupport; +import me.regadpole.plumbot.internal.WhitelistHelper; import me.regadpole.plumbot.internal.database.DatabaseManager; import me.regadpole.plumbot.tool.StringTool; import org.bukkit.Bukkit; @@ -124,43 +125,54 @@ public void onGroupMessageReceive(GroupMessage e){ if (!Config.WhiteList()) { return; } - String name = matcher.group().replace(Prefix + "删除白名单 ", ""); - if (name.isEmpty()) { - bot.sendMsg(true, "id不能为空", groupID); + String para = matcher.group().replace(Prefix + "删除白名单 ", ""); + if (para.isEmpty()) { + bot.sendMsg(true, "参数不能为空", groupID); return; } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - long nameForId = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (nameForId == 0L) { - bot.sendMsg(true, "尚未申请白名单", groupID); + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); return; } - DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单", groupID); - }); - return; - } - - pattern = Pattern.compile(Prefix + "删除User白名单 .*"); - matcher = pattern.matcher(msg); - if (matcher.find()) { - if (!Config.WhiteList()) { - return; - } - String qq = matcher.group().replace(Prefix + "删除User白名单 ", ""); - if (qq.isEmpty()) { - bot.sendMsg(true, "QQ不能为空", groupID); - return; - } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null) { - bot.sendMsg(true, "尚未申请白名单", groupID); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + if (WhitelistHelper.checkIDNotExist(name)) { + bot.sendMsg(true, "ID尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单", groupID); + }); + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + bot.sendMsg(true, "QQ不能为空", groupID); return; } - DatabaseManager.removeBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单", groupID); - }); + String[] p = qq.split(" "); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(p[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, p[0]+"尚未申请白名单", groupID); + return; + } + int num = Integer.parseInt(p[1]); + DatabaseManager.removeBind(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,"+p[0]+"目前拥有的白名单为"+DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + }); + } else { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + DatabaseManager.removeBind(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + }); + } return; } @@ -190,12 +202,14 @@ public void onGroupMessageReceive(GroupMessage e){ messages.add(Prefix+"在线人数 查看服务器当前在线人数"); messages.add(Prefix+"tps 查看服务器当前tps"); messages.add(Prefix+"申请白名单 为自己申请白名单"); - messages.add(Prefix+"删除白名单 删除自己的白名单"); + messages.add(Prefix+"删除白名单 <序号> 删除自己的白名单"); + messages.add(Prefix+"查询白名单 查询自己的白名单"); messages.add("管理命令:"); messages.add(Prefix+"cmd 向服务器发送命令"); - messages.add(Prefix+"删除白名单 删除指定游戏id的白名单"); - messages.add(Prefix+"删除User白名单 删除指定群成员的白名单"); - for (String message : messages) { + messages.add(Prefix+"申请白名单 为指定用户申请白名单"); + messages.add(Prefix+"删除白名单 删除指定游戏id或qq的白名单"); + messages.add(Prefix+"查询白名单 查询指定游戏id或qq的白名单"); + for (String message : messages) { if (messages.get(messages.size() - 1).equalsIgnoreCase(message)) { stringBuilder.append(message.replaceAll("§\\S", "")); } else { @@ -223,42 +237,129 @@ public void onGroupMessageReceive(GroupMessage e){ return; } - pattern = Pattern.compile(Prefix + "申请白名单 .*"); + pattern = Pattern.compile(Prefix + "查询白名单 .*"); matcher = pattern.matcher(msg); if (matcher.find()) { if (!Config.WhiteList()) { return; } - String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); - if (PlayerName.isEmpty()) { - bot.sendMsg(true, "id不能为空", groupID); - return; + if(Config.getAdmins().contains(senderID)) { + String para = matcher.group().replace(Prefix + "查询白名单 ", ""); + if (para.isEmpty()) { + bot.sendMsg(true, "参数不能为空", groupID); + return; + } + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (qq==0L) { + bot.sendMsg(true, "ID尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, name+"的申请用户为"+qq, groupID); + }); + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + bot.sendMsg(true, "QQ不能为空", groupID); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + bot.sendMsg(true, qq+"尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, qq+"拥有白名单ID:"+id, groupID); + }); + } else { + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, senderID+"拥有白名单ID:"+id, groupID); + }); + } } PlumBot.getScheduler().runTaskAsynchronously(() -> { - if ((DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()) != null) || (DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()) != 0L)) { - bot.sendMsg(true, "绑定失败", groupID); + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - DatabaseManager.addBind(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功申请白名单", groupID); + bot.sendMsg(true, senderID +"拥有白名单ID:"+idForName, groupID); }); return; } - pattern = Pattern.compile(Prefix + "删除白名单"); + pattern = Pattern.compile(Prefix + "申请白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); + String[] para = PlayerName.split(" "); + if (para.length==1){ + if (PlayerName.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); + return; + } + if(Config.getAdmins().contains(senderID)) { + if (!WhitelistHelper.checkIDNotExist(PlayerName)) { + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + if (WhitelistHelper.checkCount(String.valueOf(senderID))) { + bot.sendMsg(true, "绑定失败,该用户已绑定:"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + if (!WhitelistHelper.checkIDNotExist(PlayerName)){ + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + }); + } else if (para.length==2) { + if(Config.getAdmins().contains(senderID)) { + if (!WhitelistHelper.checkIDNotExist(para[1])) { + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,"+para[0]+"目前的白名单为"+id, groupID); + } + } + return; + } + + pattern = Pattern.compile(Prefix + "删除白名单 .*"); matcher = pattern.matcher(msg); if (matcher.find()) { if (!Config.WhiteList()) { return; } + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); PlumBot.getScheduler().runTaskAsynchronously(() -> { - String idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName == null || idForName.isEmpty()) { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - DatabaseManager.removeBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单", groupID); + DatabaseManager.removeBind(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前的白名单为"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); }); return; } @@ -354,8 +455,8 @@ public void onGroupMessageReceive(GroupMessage e){ public void onGroupDecreaseNotice(GroupDecreaseNotice e) { long userId = e.getUserId(); long groupId = e.getGroupId(); - String player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (player == null) { + List player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player.isEmpty()) { return; } DatabaseManager.removeBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java new file mode 100644 index 0000000..4a6d5dd --- /dev/null +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java @@ -0,0 +1,28 @@ +package me.regadpole.plumbot.internal; + +import me.regadpole.plumbot.PlumBot; +import me.regadpole.plumbot.config.Config; +import me.regadpole.plumbot.config.DataBase; +import me.regadpole.plumbot.internal.database.Database; +import me.regadpole.plumbot.internal.database.DatabaseManager; + +import java.util.List; + +public class WhitelistHelper { + + public static boolean checkCount(String qq){ + List idList = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + int maxCount = Config.WhiteListMaxCount(); + if (idList == null) return true; + return idList.size() < maxCount; + } + + public static boolean checkIDNotExist(String id){ + return DatabaseManager.getBindId(id, DataBase.type().toLowerCase(), PlumBot.getDatabase()) == 0L; + } + + public static List addAndGet(String id, String qq, String mode, Database db){ + DatabaseManager.addBind(id, qq, mode, db); + return DatabaseManager.getBind(qq, mode, db); + } +} diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java index a2c1870..45f487a 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -8,6 +8,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; public class DatabaseManager { @@ -62,13 +64,7 @@ public static void addBind(String id, String qq, String mode, Database db) { ResultSet resultSetid = statement.executeQuery(selectid); ResultSet resultSetqq = statement1.executeQuery(selectqq); - if (!resultSetid.isBeforeFirst() && resultSetqq.isBeforeFirst()) { - statement.executeUpdate(updateid); - } else if (resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - statement.executeUpdate(updateqq); - } else if (!resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - statement.executeUpdate(insert); - } + statement.executeUpdate(insert); resultSetid.close(); resultSetqq.close(); @@ -85,13 +81,7 @@ public static void addBind(String id, String qq, String mode, Database db) { ResultSet resultSetid = connection.prepareStatement(selectid).executeQuery(); ResultSet resultSetqq = connection.prepareStatement(selectqq).executeQuery(); - if (!resultSetid.isBeforeFirst() && resultSetqq.isBeforeFirst()) { - connection.prepareStatement(updateid).executeUpdate(); - } else if (resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - connection.prepareStatement(updateqq).executeUpdate(); - } else if (!resultSetid.isBeforeFirst() && !resultSetqq.isBeforeFirst()) { - connection.prepareStatement(insert).executeUpdate(); - } + connection.prepareStatement(insert).executeUpdate(); resultSetid.close(); resultSetqq.close(); @@ -107,7 +97,7 @@ public static void addBind(String id, String qq, String mode, Database db) { public static void removeBindid(String id,String mode, Database db) { String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE id='" + id + "';"; String delete = "DELETE FROM whitelist WHERE id='" + id + "';"; try { @@ -149,9 +139,69 @@ public static void removeBindid(String id,String mode, Database db) { } } - public static void removeBind(String qq,String mode, Database db) { + public static void removeBind(String qq, int num, String mode, Database db) { String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + ";"; + + try { + Connection connection = db.getConnection(); + switch (mode){ + case "sqlite": + default: { + Statement statement = connection.createStatement(); + statement.executeUpdate(createTable); + + // 如果没有找到记录为false,找到就是true + ResultSet resultSet = statement.executeQuery(select); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + for (int i = 1; i < num; i++) { + resultSet.next(); + } + if (resultSet.isAfterLast()){ + return; + } + String id = resultSet.getString("id"); + String delete = "DELETE FROM whitelist WHERE qq=" + qq+" AND id='" + id + "';"; + statement.executeUpdate(delete); + resultSet.close(); + statement.close(); + connection.close(); + + break; + } + case "mysql": { + connection.prepareStatement(createTable).executeUpdate(); + + ResultSet resultSet = connection.prepareStatement(select).executeQuery(); + + if (resultSet.isBeforeFirst()) { + resultSet.next(); + } + for (int i = 1; i < num; i++) { + resultSet.next(); + } + if (resultSet.isAfterLast()){ + return; + } + String id = resultSet.getString("id"); + String delete = "DELETE FROM whitelist WHERE qq=" + qq+" AND id='" + id + "';"; + connection.prepareStatement(delete).executeUpdate(); + resultSet.close(); + connection.close(); + break; + } + } + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public static void removeBind(String qq, String mode, Database db) { + String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + ";"; String delete = "DELETE FROM whitelist WHERE qq=" + qq+";"; try { @@ -167,8 +217,8 @@ public static void removeBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); - statement.executeUpdate(delete); } + statement.executeUpdate(delete); resultSet.close(); statement.close(); connection.close(); @@ -182,8 +232,8 @@ public static void removeBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); - connection.prepareStatement(delete).executeUpdate(); } + connection.prepareStatement(delete).executeUpdate(); resultSet.close(); connection.close(); break; @@ -194,11 +244,11 @@ public static void removeBind(String qq,String mode, Database db) { } } - public static long getBindId(String id,String mode, Database db) { + public static long getBindId(String id, String mode, Database db) { long qq = 0L; String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE id='" + id + "' LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE id='" + id + "' ;"; try { Connection connection = db.getConnection(); @@ -238,10 +288,9 @@ public static long getBindId(String id,String mode, Database db) { } return qq; } - - @Nullable - public static String getBind(String qq,String mode, Database db) { - String id = null; + + public static List getBind(String qq,String mode, Database db) { + List id = new ArrayList<>(); String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; @@ -257,7 +306,10 @@ public static String getBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); } - id = resultSet.getString("id"); + do { + id.add(resultSet.getString("id")); + resultSet.next(); + }while(!resultSet.isAfterLast()); resultSet.close(); connection.close(); break; @@ -272,7 +324,10 @@ public static String getBind(String qq,String mode, Database db) { if (resultSet.isBeforeFirst()) { resultSet.next(); } - id = resultSet.getString("id"); + do { + id.add(resultSet.getString("id")); + resultSet.next(); + }while(!resultSet.isAfterLast()); resultSet.close(); statement.close(); connection.close(); @@ -285,4 +340,5 @@ public static String getBind(String qq,String mode, Database db) { } return id; } + } diff --git a/plumbot-bukkit/src/main/resources/config.yml b/plumbot-bukkit/src/main/resources/config.yml index 1da7596..8d1b245 100644 --- a/plumbot-bukkit/src/main/resources/config.yml +++ b/plumbot-bukkit/src/main/resources/config.yml @@ -1,5 +1,5 @@ #机器人功能设置 -Ver: "1.3.1" +Ver: "1.3.2" #QQ群聊命令前缀 Prefix: "/" @@ -17,6 +17,7 @@ DieReport: false WhiteList: enable: false kickMsg: "请加入qq群:xxx申请白名单" + maxCount: 1 #执行命令功能 CMD: true diff --git a/plumbot-bungee/pom.xml b/plumbot-bungee/pom.xml index 87d5ae9..24b3a68 100644 --- a/plumbot-bungee/pom.xml +++ b/plumbot-bungee/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 plumbot-bungee diff --git a/plumbot-velocity/pom.xml b/plumbot-velocity/pom.xml index d90cc81..2d1b455 100644 --- a/plumbot-velocity/pom.xml +++ b/plumbot-velocity/pom.xml @@ -6,7 +6,7 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 plumbot-velocity diff --git a/pom.xml b/pom.xml index 8e544af..d506f33 100644 --- a/pom.xml +++ b/pom.xml @@ -6,14 +6,14 @@ me.regadpole plumbot - 1.3.2 + 1.3.3 pom PlumBot - plumbot-velocity plumbot-bukkit plumbot-bungee + plumbot-velocity From 86141b703ac492cbaca093c8079fa496fd2eff7a Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Mon, 24 Jun 2024 18:05:35 +0800 Subject: [PATCH 07/16] =?UTF-8?q?1.=E4=BF=AE=E5=A4=8D=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=202.=E4=BF=AE=E5=A4=8D=E6=B8=B8=E6=88=8F?= =?UTF-8?q?=E5=86=85=E5=91=BD=E4=BB=A4addBind=203.=E4=BF=AE=E5=A4=8Dqq?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E6=89=A7=E8=A1=8C=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../regadpole/plumbot/command/Commands.java | 82 ++++++------- .../regadpole/plumbot/event/qq/QQEvent.java | 113 +++++++++--------- .../plumbot/internal/Environment.java | 1 + .../plumbot/internal/WhitelistHelper.java | 7 +- .../internal/database/DatabaseManager.java | 4 +- 5 files changed, 109 insertions(+), 98 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java index ece2e0a..9893108 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -29,25 +29,25 @@ public Commands(PlumBot plugin){ public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0) { - sender.sendMessage("请使用/pb help查看命令使用方法"); + sender.sendMessage(plugin.getEnvironment().prefix+"§c请使用/pb help查看命令使用方法"); return true; } switch (args[0]) { case "info": StringBuilder stringbuilder = new StringBuilder(); - stringbuilder.append("§1---PlumBot 信息---").append("\n"); - stringbuilder.append("§a作者: ").append("§f").append(plugin.getEnvironment().author).append("\n"); - stringbuilder.append("§a版本: ").append("§f").append(plugin.getEnvironment().version).append("\n"); - stringbuilder.append("§a机器人平台: ").append("§f").append(Config.getBotMode()).append("\n"); - stringbuilder.append("§a数据库模式: ").append("§f").append(DataBase.type()).append("\n"); - stringbuilder.append("§a服务端版本: ").append("§f").append(Bukkit.getVersion()).append("\n"); - stringbuilder.append("§a兼容插件: ").append("\n"); - stringbuilder.append("\t").append("§bAuthMe: ").append(plugin.getEnvironment().authme).append("\n"); - stringbuilder.append("\t").append("§bGriefDefender: ").append(plugin.getEnvironment().griefdefender).append("\n"); - stringbuilder.append("\t").append("§bResidence: ").append(plugin.getEnvironment().residence).append("\n"); - stringbuilder.append("\t").append("§bQuickShop: ").append(plugin.getEnvironment().quickshop).append("\n"); - stringbuilder.append("\t").append("§bQuickShopHikari: ").append(plugin.getEnvironment().quickshophikari).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§1---PlumBot 信息---").append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§a作者: ").append("§f").append(plugin.getEnvironment().author).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§a版本: ").append("§f").append(plugin.getEnvironment().version).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§a机器人平台: ").append("§f").append(Config.getBotMode()).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§a数据库模式: ").append("§f").append(DataBase.type()).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§a服务端版本: ").append("§f").append(Bukkit.getVersion()).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("§a兼容插件: ").append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("\t").append("§bAuthMe: ").append(plugin.getEnvironment().authme).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("\t").append("§bGriefDefender: ").append(plugin.getEnvironment().griefdefender).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("\t").append("§bResidence: ").append(plugin.getEnvironment().residence).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("\t").append("§bQuickShop: ").append(plugin.getEnvironment().quickshop).append("\n"); + stringbuilder.append(plugin.getEnvironment().prefix).append("\t").append("§bQuickShopHikari: ").append(plugin.getEnvironment().quickshophikari).append("\n"); sender.sendMessage(stringbuilder.toString()); break; case "reload": @@ -57,90 +57,90 @@ public boolean onCommand(CommandSender sender, Command command, String label, St Config.loadConfig(); DatabaseManager.start(); PlumBot.getBot().start(); - sender.sendMessage("PlumBot已重载"); + sender.sendMessage(plugin.getEnvironment().prefix+"§aPlumBot已重载"); break; case "help": if (args.length != 1) return true; - sender.sendMessage("§6PlumBot 机器人帮助菜单"); - sender.sendMessage("§6/pb reload :§f重载插件"); - sender.sendMessage("§6/pb help :§f获取插件帮助"); - sender.sendMessage("§6/pb info :§f插件基本信息"); - sender.sendMessage("§6/pb kook help :§f获取kook帮助"); - sender.sendMessage("§6/pb kook plugins :§f获取kook插件列表"); - sender.sendMessage("§6/pb queryBind :§f查询id或qq绑定数据"); - sender.sendMessage("§6/pb addBind :§f为qq添加ID白名单"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6PlumBot 机器人帮助菜单"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb reload :§f重载插件"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb help :§f获取插件帮助"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb info :§f插件基本信息"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb kook help :§f获取kook帮助"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb kook plugins :§f获取kook插件列表"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb queryBind :§f查询id或qq绑定数据"); + sender.sendMessage(plugin.getEnvironment().prefix+"§6/pb addBind :§f为qq添加ID白名单"); break; case "queryBind": if (args.length == 1) { - sender.sendMessage("命令错误,格式:/plumbot queryBind "); + sender.sendMessage(plugin.getEnvironment().prefix+"§c命令错误,格式:/plumbot queryBind "); return true; } if (args.length > 2) { - sender.sendMessage("命令错误,格式:/plumbot queryBind "); + sender.sendMessage(plugin.getEnvironment().prefix+"§c命令错误,格式:/plumbot queryBind "); return true; } if (args.length == 2) { if (args[1].startsWith("id:")) { String name = args[1].substring(3); if (name.isEmpty()) { - sender.sendMessage("id不能为空"); + sender.sendMessage(plugin.getEnvironment().prefix+"§cid不能为空"); return true; } PlumBot.getScheduler().runTaskAsynchronously(() -> { long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); if (qq==0L) { - sender.sendMessage("ID尚未申请白名单"); + sender.sendMessage(plugin.getEnvironment().prefix+"§cID尚未申请白名单"); return; } - sender.sendMessage(name+"的申请用户为"+qq); + sender.sendMessage(plugin.getEnvironment().prefix+"§a"+name+"的申请用户为"+qq); }); return true; } else if (args[1].startsWith("qq:")) { String qq = args[1].substring(3); if (qq.isEmpty()) { - sender.sendMessage("QQ不能为空"); + sender.sendMessage(plugin.getEnvironment().prefix+"§cQQ不能为空"); return true; } PlumBot.getScheduler().runTaskAsynchronously(() -> { List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); if (id.isEmpty()) { - sender.sendMessage(qq+"尚未申请白名单"); + sender.sendMessage(plugin.getEnvironment().prefix+"§c"+qq+"尚未申请白名单"); return; } - sender.sendMessage(qq+"拥有白名单ID:"+id); + sender.sendMessage(plugin.getEnvironment().prefix+"§a"+qq+"拥有白名单ID:"+id); }); return true; } break; } case "addBind": - if (args.length == 1) { - sender.sendMessage("命令错误,格式:/plumbot queryBind "); + if (args.length < 3) { + sender.sendMessage(plugin.getEnvironment().prefix+"§c命令错误,格式:/plumbot addBind "); return true; } - if (args.length > 2) { - sender.sendMessage("命令错误,格式:/plumbot queryBind "); + if (args.length > 3) { + sender.sendMessage(plugin.getEnvironment().prefix+"§c命令错误,格式:/plumbot addBind "); return true; } - if (args.length == 2) { + if (args.length == 3) { if (!WhitelistHelper.checkIDNotExist(args[1])) { - sender.sendMessage("绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); + sender.sendMessage(plugin.getEnvironment().prefix+"§c绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); return true; } List id = WhitelistHelper.addAndGet(args[1], args[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); - sender.sendMessage("成功申请白名单," + args[0] + "目前的白名单为" + id); + sender.sendMessage(plugin.getEnvironment().prefix+"§a成功申请白名单," + args[0] + "目前的白名单为" + id); } break; case "kook": if (args.length == 1) { - sender.sendMessage("命令错误,格式:/plumbot kook "); - sender.sendMessage("value可选值:plugins,help"); + sender.sendMessage(plugin.getEnvironment().prefix+"§c命令错误,格式:/plumbot kook "); + sender.sendMessage(plugin.getEnvironment().prefix+"§cvalue可选值:plugins,help"); return true; } if (args.length > 2) return true; if (args.length == 2) { if (KookBot.isKookEnabled()) { - sender.sendMessage("kook客户端未启动"); + sender.sendMessage(plugin.getEnvironment().prefix+"§ckook客户端未启动"); return true; } switch (args[1]) { @@ -156,7 +156,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St break; default: if (args.length != 1) return true; - sender.sendMessage("错误的指令用法,请使用/pb help查看命令使用方法"); + sender.sendMessage(plugin.getEnvironment().prefix+"§c错误的指令用法,请使用/pb help查看命令使用方法"); break; } return true; diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index ad31f6e..7a2e242 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -144,6 +144,7 @@ public void onGroupMessageReceive(GroupMessage e){ DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); bot.sendMsg(true, "成功移出白名单", groupID); }); + return; } else if (para.startsWith("qq:")) { String qq = para.substring(3); if (qq.isEmpty()) { @@ -158,9 +159,10 @@ public void onGroupMessageReceive(GroupMessage e){ return; } int num = Integer.parseInt(p[1]); - DatabaseManager.removeBind(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,"+p[0]+"目前拥有的白名单为"+DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + List id = WhitelistHelper.removeAndGet(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,"+p[0]+"目前拥有的白名单为"+id, groupID); }); + return; } else { int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); PlumBot.getScheduler().runTaskAsynchronously(() -> { @@ -169,11 +171,11 @@ public void onGroupMessageReceive(GroupMessage e){ bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - DatabaseManager.removeBind(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为"+id, groupID); }); + return; } - return; } pattern = Pattern.compile(Prefix+".*"); @@ -193,6 +195,51 @@ public void onGroupMessageReceive(GroupMessage e){ } } + pattern = Pattern.compile(Prefix + "查询白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String para = matcher.group().replace(Prefix + "查询白名单 ", ""); + if (para.isEmpty()) { + bot.sendMsg(true, "参数不能为空", groupID); + return; + } + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + bot.sendMsg(true, "id不能为空", groupID); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (qq==0L) { + bot.sendMsg(true, "ID尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, name+"的申请用户为"+qq, groupID); + }); + return; + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + bot.sendMsg(true, "QQ不能为空", groupID); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + bot.sendMsg(true, qq+"尚未申请白名单", groupID); + return; + } + bot.sendMsg(true, qq+"拥有白名单ID:"+id, groupID); + }); + return; + } + return; + } + } if(msg.equals(Prefix+"帮助")) { @@ -237,57 +284,12 @@ public void onGroupMessageReceive(GroupMessage e){ return; } - pattern = Pattern.compile(Prefix + "查询白名单 .*"); + pattern = Pattern.compile(Prefix + "查询白名单"); matcher = pattern.matcher(msg); if (matcher.find()) { if (!Config.WhiteList()) { return; } - if(Config.getAdmins().contains(senderID)) { - String para = matcher.group().replace(Prefix + "查询白名单 ", ""); - if (para.isEmpty()) { - bot.sendMsg(true, "参数不能为空", groupID); - return; - } - if (para.startsWith("id:")) { - String name = para.substring(3); - if (name.isEmpty()) { - bot.sendMsg(true, "id不能为空", groupID); - return; - } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (qq==0L) { - bot.sendMsg(true, "ID尚未申请白名单", groupID); - return; - } - bot.sendMsg(true, name+"的申请用户为"+qq, groupID); - }); - } else if (para.startsWith("qq:")) { - String qq = para.substring(3); - if (qq.isEmpty()) { - bot.sendMsg(true, "QQ不能为空", groupID); - return; - } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (id.isEmpty()) { - bot.sendMsg(true, qq+"尚未申请白名单", groupID); - return; - } - bot.sendMsg(true, qq+"拥有白名单ID:"+id, groupID); - }); - } else { - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List id = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (id.isEmpty()) { - bot.sendMsg(true, "您尚未申请白名单", groupID); - return; - } - bot.sendMsg(true, senderID+"拥有白名单ID:"+id, groupID); - }); - } - } PlumBot.getScheduler().runTaskAsynchronously(() -> { List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); if (idForName.isEmpty()) { @@ -319,9 +321,10 @@ public void onGroupMessageReceive(GroupMessage e){ } List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { - if (WhitelistHelper.checkCount(String.valueOf(senderID))) { + if (!WhitelistHelper.checkCount(String.valueOf(senderID))) { bot.sendMsg(true, "绑定失败,该用户已绑定:"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); return; } @@ -332,6 +335,7 @@ public void onGroupMessageReceive(GroupMessage e){ List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); }); + return; } else if (para.length==2) { if(Config.getAdmins().contains(senderID)) { if (!WhitelistHelper.checkIDNotExist(para[1])) { @@ -340,6 +344,7 @@ public void onGroupMessageReceive(GroupMessage e){ } List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); bot.sendMsg(true, "成功申请白名单,"+para[0]+"目前的白名单为"+id, groupID); + return; } } return; @@ -358,8 +363,8 @@ public void onGroupMessageReceive(GroupMessage e){ bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - DatabaseManager.removeBind(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,您目前的白名单为"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前的白名单为"+result, groupID); }); return; } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java index 5f652e8..c283cf0 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/Environment.java @@ -18,6 +18,7 @@ public final class Environment { public final String quickshop = getPluginHooked(QuickShopHook.hasQs); public final String quickshophikari = getPluginHooked(QuickShopHook.hasQsHikari); public final String residence = getPluginHooked(ResidenceHook.hasRes); + public final String prefix = "§b§l[PlumBot]§r "; private String getPluginHooked(boolean hooked){ if (hooked){ diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java index 4a6d5dd..9a8a90b 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/WhitelistHelper.java @@ -13,7 +13,7 @@ public class WhitelistHelper { public static boolean checkCount(String qq){ List idList = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); int maxCount = Config.WhiteListMaxCount(); - if (idList == null) return true; + if (idList.isEmpty()) return true; return idList.size() < maxCount; } @@ -25,4 +25,9 @@ public static List addAndGet(String id, String qq, String mode, Database DatabaseManager.addBind(id, qq, mode, db); return DatabaseManager.getBind(qq, mode, db); } + + public static List removeAndGet(String qq, int num, String mode, Database db){ + DatabaseManager.removeBind(qq, num, mode, db); + return DatabaseManager.getBind(qq, mode, db); + } } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java index 45f487a..fedb559 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -202,7 +202,7 @@ public static void removeBind(String qq, int num, String mode, Database db) { public static void removeBind(String qq, String mode, Database db) { String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; String select = "SELECT * FROM whitelist WHERE qq=" + qq + ";"; - String delete = "DELETE FROM whitelist WHERE qq=" + qq+";"; + String delete = "DELETE FROM whitelist WHERE qq=" + qq + ";"; try { Connection connection = db.getConnection(); @@ -293,7 +293,7 @@ public static List getBind(String qq,String mode, Database db) { List id = new ArrayList<>(); String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; - String select = "SELECT * FROM whitelist WHERE qq=" + qq + " LIMIT 1;"; + String select = "SELECT * FROM whitelist WHERE qq=" + qq + " ;"; try { Connection connection = db.getConnection(); From 384e6a5a1bc01bbe348eb176f58ec14f8a180862 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Wed, 26 Jun 2024 17:15:11 +0800 Subject: [PATCH 08/16] fix kook whitelist --- .../plumbot/event/kook/KookEvent.java | 200 ++++++++++++++---- .../regadpole/plumbot/event/qq/QQEvent.java | 1 + 2 files changed, 155 insertions(+), 46 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index 758bafc..58f9807 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -8,6 +8,7 @@ import me.regadpole.plumbot.event.server.ServerManager; import me.regadpole.plumbot.event.server.ServerTps; import me.regadpole.plumbot.internal.FoliaSupport; +import me.regadpole.plumbot.internal.WhitelistHelper; import me.regadpole.plumbot.internal.database.DatabaseManager; import me.regadpole.plumbot.tool.StringTool; import org.bukkit.Bukkit; @@ -97,44 +98,57 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { if (!Config.WhiteList()) { return; } - String name = matcher.group().replace(Prefix + "删除白名单 ", ""); - if (name.isEmpty()) { - e.getMessage().reply("id不能为空"); + String para = matcher.group().replace(Prefix + "删除白名单 ", ""); + if (para.isEmpty()) { + e.getMessage().reply("参数不能为空"); return; } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - long nameForId = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (nameForId == 0L) { - e.getMessage().reply("尚未申请白名单"); + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + e.getMessage().reply("id不能为空"); return; } - DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单"); - }); - return; - } - - pattern = Pattern.compile(Prefix + "删除User白名单 .*"); - matcher = pattern.matcher(msg); - if (matcher.find()) { - if (!Config.WhiteList()) { - return; - } - String qq = matcher.group().replace(Prefix + "删除User白名单 ", ""); - if (qq.isEmpty()) { - e.getMessage().reply("QQ不能为空"); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + if (WhitelistHelper.checkIDNotExist(name)) { + e.getMessage().reply("ID尚未申请白名单"); + return; + } + DatabaseManager.removeBindid(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单"); + }); return; - } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List idForName = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName.isEmpty()) { - e.getMessage().reply("尚未申请白名单"); + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + e.getMessage().reply("QQ不能为空"); return; } - DatabaseManager.removeBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单"); - }); - return; + String[] p = qq.split(" "); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(p[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + e.getMessage().reply(p[0]+"尚未申请白名单"); + return; + } + int num = Integer.parseInt(p[1]); + List id = WhitelistHelper.removeAndGet(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,"+p[0]+"目前拥有的白名单为"+id); + }); + return; + } else { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + e.getMessage().reply("您尚未申请白名单"); + return; + } + List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,您目前拥有的白名单为"+id); + }); + return; + } } pattern = Pattern.compile(Prefix+".*"); @@ -154,6 +168,52 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { } } + pattern = Pattern.compile(Prefix + "查询白名单 .*"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + String para = matcher.group().replace(Prefix + "查询白名单 ", ""); + if (para.isEmpty()) { + e.getMessage().reply("参数不能为空"); + return; + } + if (para.startsWith("id:")) { + String name = para.substring(3); + if (name.isEmpty()) { + e.getMessage().reply("id不能为空"); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq = DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (qq==0L) { + e.getMessage().reply("ID尚未申请白名单"); + return; + } + e.getMessage().reply(name+"的申请用户为"+qq); + }); + return; + } else if (para.startsWith("qq:")) { + String qq = para.substring(3); + if (qq.isEmpty()) { + e.getMessage().reply("QQ不能为空"); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List id = DatabaseManager.getBind(qq, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (id.isEmpty()) { + e.getMessage().reply(qq+"尚未申请白名单"); + return; + } + e.getMessage().reply(qq+"拥有白名单ID:"+id); + }); + return; + } + return; + } + + } if(msg.equals(Prefix+"帮助")) { @@ -163,11 +223,14 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { messages.add(Prefix+"在线人数 查看服务器当前在线人数"); messages.add(Prefix+"tps 查看服务器当前tps"); messages.add(Prefix+"申请白名单 为自己申请白名单"); - messages.add(Prefix+"删除白名单 删除自己的白名单"); + messages.add(Prefix+"删除白名单 <序号> 删除自己的白名单"); + messages.add(Prefix+"查询白名单 查询自己的白名单"); messages.add("管理命令:"); messages.add(Prefix+"cmd 向服务器发送命令"); - messages.add(Prefix+"删除白名单 删除指定游戏id的白名单"); - messages.add(Prefix+"删除User白名单 删除指定群成员的白名单"); + messages.add(Prefix+"申请白名单 为指定用户申请白名单"); + messages.add(Prefix+"删除白名单 删除指定游戏id或kook用户的白名单"); + messages.add(Prefix+"查询白名单 查询指定游戏id或kook用户的白名单"); + messages.add("ps:请通过查询白名单获得序号"); for (String message : messages) { if (messages.get(messages.size() - 1).equalsIgnoreCase(message)) { stringBuilder.append(message.replaceAll("§\\S", "")); @@ -196,6 +259,23 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } + pattern = Pattern.compile(Prefix + "查询白名单"); + matcher = pattern.matcher(msg); + if (matcher.find()) { + if (!Config.WhiteList()) { + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + e.getMessage().reply("您尚未申请白名单"); + return; + } + e.getMessage().reply(senderID +"拥有白名单ID:"+idForName); + }); + return; + } + pattern = Pattern.compile(Prefix + "申请白名单 .*"); matcher = pattern.matcher(msg); if (matcher.find()) { @@ -203,35 +283,63 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } String PlayerName = matcher.group().replace(Prefix + "申请白名单 ", ""); - if (PlayerName.isEmpty()) { - e.getMessage().reply("id不能为空"); + String[] para = PlayerName.split(" "); + if (para.length==1){ + if (PlayerName.isEmpty()) { + e.getMessage().reply("id不能为空"); + return; + } + if(Config.getAdmins().contains(senderID)) { + if (!WhitelistHelper.checkIDNotExist(PlayerName)) { + e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功申请白名单,您目前的白名单为"+id); + return; + } + PlumBot.getScheduler().runTaskAsynchronously(() -> { + if (!WhitelistHelper.checkCount(String.valueOf(senderID))) { + e.getMessage().reply("绑定失败,该用户已绑定:"+DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return; + } + if (!WhitelistHelper.checkIDNotExist(PlayerName)){ + e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功申请白名单,您目前的白名单为"+id); + }); return; - } - PlumBot.getScheduler().runTaskAsynchronously(() -> { - if ((DatabaseManager.getBind(senderID, DataBase.type().toLowerCase(), PlumBot.getDatabase())!=null) || (DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()) != 0L)) { - e.getMessage().reply("绑定失败"); + } else if (para.length==2) { + if(Config.getAdmins().contains(senderID)) { + if (!WhitelistHelper.checkIDNotExist(para[1])) { + e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return; + } + List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功申请白名单,"+para[0]+"目前的白名单为"+id); return; } - DatabaseManager.addBind(PlayerName, senderID, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功申请白名单"); - }); + } return; } - pattern = Pattern.compile(Prefix + "删除白名单"); + pattern = Pattern.compile(Prefix + "删除白名单 .*"); matcher = pattern.matcher(msg); if (matcher.find()) { if (!Config.WhiteList()) { return; } + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); PlumBot.getScheduler().runTaskAsynchronously(() -> { List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); if (idForName.isEmpty()) { e.getMessage().reply("您尚未申请白名单"); return; } - DatabaseManager.removeBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单"); + List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,您目前的白名单为"+result); }); return; } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index 7a2e242..f6309bf 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -256,6 +256,7 @@ public void onGroupMessageReceive(GroupMessage e){ messages.add(Prefix+"申请白名单 为指定用户申请白名单"); messages.add(Prefix+"删除白名单 删除指定游戏id或qq的白名单"); messages.add(Prefix+"查询白名单 查询指定游戏id或qq的白名单"); + messages.add("ps:请通过查询白名单获得序号"); for (String message : messages) { if (messages.get(messages.size() - 1).equalsIgnoreCase(message)) { stringBuilder.append(message.replaceAll("§\\S", "")); From 46bf9c83a3408765cf6d85cd0b16ec494ab0eda0 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Wed, 26 Jun 2024 17:19:23 +0800 Subject: [PATCH 09/16] fix --- .../main/java/me/regadpole/plumbot/event/kook/KookEvent.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index 58f9807..e4026b8 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -289,7 +289,7 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { e.getMessage().reply("id不能为空"); return; } - if(Config.getAdmins().contains(senderID)) { + if(admins.contains(senderID)) { if (!WhitelistHelper.checkIDNotExist(PlayerName)) { e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase())); return; @@ -312,7 +312,7 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { }); return; } else if (para.length==2) { - if(Config.getAdmins().contains(senderID)) { + if(admins.contains(senderID)) { if (!WhitelistHelper.checkIDNotExist(para[1])) { e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); return; From e784645cad2e25a933937b162aadee9676143b21 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Wed, 26 Jun 2024 17:34:44 +0800 Subject: [PATCH 10/16] update readme --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 93396f9..f6b4e52 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,10 @@ ![GitHub](https://img.shields.io/github/license/RegadPoleCN/PlumBot) [![Java CI with Maven](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven.yml/badge.svg)](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven.yml) [![Java CI dev](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven-dev.yml/badge.svg)](https://github.com/RegadPoleCN/PlumBot/actions/workflows/maven-dev.yml) -![GitHub release (with filter)](https://img.shields.io/github/v/release/RegadPoleCN/PlumBot) +[![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/RegadPoleCN/PlumBot/total?logo=github)](https://github.com/RegadPoleCN/PlumBot/releases) +[![GitHub release (with filter)](https://img.shields.io/github/v/release/RegadPoleCN/PlumBot)](https://github.com/RegadPoleCN/PlumBot/releases) +[![Modrinth Downloads](https://img.shields.io/modrinth/dt/plumbot?logo=modrinth)](https://modrinth.com/plugin/plumbot) + 本插件适用于[go-cqhttp](https://github.com/Mrs4s/go-cqhttp)中的http通信模式 和 [kook](kookapp.cn)的websocket模式 From e71d807f55f9cd863259d7684059ffbfb2587742 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Wed, 3 Jul 2024 17:45:11 +0800 Subject: [PATCH 11/16] =?UTF-8?q?1.=20try=20fix=20OutOfMemoryError=20when?= =?UTF-8?q?=20using=20database=20=E6=9C=AA=E7=BB=8F=E8=BF=87=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=EF=BC=8C=E8=AF=B7=E5=8B=BF=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../me/regadpole/plumbot/config/DataBase.java | 2 +- .../plumbot/event/kook/KookEvent.java | 40 ++++++++++-------- .../regadpole/plumbot/event/qq/QQEvent.java | 40 ++++++++++-------- .../internal/database/DatabaseManager.java | 41 +++++++++++++++---- .../plumbot/internal/database/MySQL.java | 2 +- 5 files changed, 82 insertions(+), 43 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/DataBase.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/DataBase.java index 7ed48c2..7562ed4 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/DataBase.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/DataBase.java @@ -9,7 +9,7 @@ public class DataBase { public static String mysql_host() {return Config.getConfigYaml().getString("database.settings.mysql.host");} public static String mysql_port() {return Config.getConfigYaml().getString("database.settings.mysql.port");} public static String mysql_database() {return Config.getConfigYaml().getString("database.settings.mysql.database");} - public static String mysql_username() {return Config.getConfigYaml().getString("database.settings.mysql.username");} + public static String mysql_user() {return Config.getConfigYaml().getString("database.settings.mysql.user");} public static String mysql_password() {return Config.getConfigYaml().getString("database.settings.mysql.password");} public static String mysql_parameters() {return Config.getConfigYaml().getString("database.settings.mysql.parameters");} public static long pool_connectionTimeout() {return Config.getConfigYaml().getLong("database.settings.pool.connectionTimeout");} diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index e4026b8..e9c27d0 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -290,12 +290,14 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } if(admins.contains(senderID)) { - if (!WhitelistHelper.checkIDNotExist(PlayerName)) { - e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase())); - return; - } - List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功申请白名单,您目前的白名单为"+id); + PlumBot.getScheduler().runTaskAsynchronously(()->{ + if (!WhitelistHelper.checkIDNotExist(PlayerName)) { + e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功申请白名单,您目前的白名单为"+id); + }); return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { @@ -313,12 +315,14 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { return; } else if (para.length==2) { if(admins.contains(senderID)) { - if (!WhitelistHelper.checkIDNotExist(para[1])) { - e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); - return; - } - List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功申请白名单,"+para[0]+"目前的白名单为"+id); + PlumBot.getScheduler().runTaskAsynchronously(()->{ + if (!WhitelistHelper.checkIDNotExist(para[1])) { + e.getMessage().reply("绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); + return; + } + List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功申请白名单,"+para[0]+"目前的白名单为"+id); + }); return; } } @@ -456,10 +460,12 @@ public void onPrivateMessageReceive(PrivateMessageReceivedEvent e) { public void onGroupDecreaseNotice(UserLeaveGuildEvent e) { String userId = e.getUser().getId(); String groupId = e.getGuildId(); - List player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (player.isEmpty()) { - return; - } - DatabaseManager.removeBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + PlumBot.getScheduler().runTaskAsynchronously(()->{ + List player = DatabaseManager.getBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player.isEmpty()) { + return; + } + DatabaseManager.removeBind(userId, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + }); } } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index f6309bf..3808acf 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -316,12 +316,14 @@ public void onGroupMessageReceive(GroupMessage e){ return; } if(Config.getAdmins().contains(senderID)) { - if (!WhitelistHelper.checkIDNotExist(PlayerName)) { - bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); - return; - } - List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + PlumBot.getScheduler().runTaskAsynchronously(()->{ + if (!WhitelistHelper.checkIDNotExist(PlayerName)) { + bot.sendMsg(true, "绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(PlayerName, DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(PlayerName, String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,您目前的白名单为"+id, groupID); + }); return; } PlumBot.getScheduler().runTaskAsynchronously(() -> { @@ -339,12 +341,14 @@ public void onGroupMessageReceive(GroupMessage e){ return; } else if (para.length==2) { if(Config.getAdmins().contains(senderID)) { - if (!WhitelistHelper.checkIDNotExist(para[1])) { - bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); - return; - } - List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功申请白名单,"+para[0]+"目前的白名单为"+id, groupID); + PlumBot.getScheduler().runTaskAsynchronously(()->{ + if (!WhitelistHelper.checkIDNotExist(para[1])) { + bot.sendMsg(true, "绑定失败,此ID已绑定用户"+DatabaseManager.getBindId(para[1], DataBase.type().toLowerCase(), PlumBot.getDatabase()), groupID); + return; + } + List id = WhitelistHelper.addAndGet(para[1], para[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功申请白名单,"+para[0]+"目前的白名单为"+id, groupID); + }); return; } } @@ -461,11 +465,13 @@ public void onGroupMessageReceive(GroupMessage e){ public void onGroupDecreaseNotice(GroupDecreaseNotice e) { long userId = e.getUserId(); long groupId = e.getGroupId(); - List player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (player.isEmpty()) { - return; - } - DatabaseManager.removeBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List player = DatabaseManager.getBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (player.isEmpty()) { + return; + } + DatabaseManager.removeBind(String.valueOf(userId), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + }); } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java index fedb559..18b9a86 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -3,7 +3,6 @@ import me.regadpole.plumbot.PlumBot; import me.regadpole.plumbot.config.DataBase; -import javax.annotation.Nullable; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -164,8 +163,15 @@ public static void removeBind(String qq, int num, String mode, Database db) { return; } String id = resultSet.getString("id"); - String delete = "DELETE FROM whitelist WHERE qq=" + qq+" AND id='" + id + "';"; - statement.executeUpdate(delete); + if (id == null) { + resultSet.close(); + statement.close(); + connection.close(); + break; + }else { + String delete = "DELETE FROM whitelist WHERE id='" + id + "';"; + statement.executeUpdate(delete); + } resultSet.close(); statement.close(); connection.close(); @@ -187,8 +193,14 @@ public static void removeBind(String qq, int num, String mode, Database db) { return; } String id = resultSet.getString("id"); - String delete = "DELETE FROM whitelist WHERE qq=" + qq+" AND id='" + id + "';"; - connection.prepareStatement(delete).executeUpdate(); + if (id == null) { + resultSet.close(); + connection.close(); + break; + }else { + String delete = "DELETE FROM whitelist WHERE id='" + id + "';"; + connection.prepareStatement(delete).executeUpdate(); + } resultSet.close(); connection.close(); break; @@ -307,7 +319,14 @@ public static List getBind(String qq,String mode, Database db) { resultSet.next(); } do { - id.add(resultSet.getString("id")); + String tempId = resultSet.getString("id"); + if (tempId == null){ + resultSet.close(); + connection.close(); + break; + } else { + id.add(tempId); + } resultSet.next(); }while(!resultSet.isAfterLast()); resultSet.close(); @@ -325,7 +344,15 @@ public static List getBind(String qq,String mode, Database db) { resultSet.next(); } do { - id.add(resultSet.getString("id")); + String tempId = resultSet.getString("id"); + if (tempId == null){ + resultSet.close(); + statement.close(); + connection.close(); + break; + } else { + id.add(tempId); + } resultSet.next(); }while(!resultSet.isAfterLast()); resultSet.close(); diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java index c71bcb8..02366d3 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/MySQL.java @@ -30,7 +30,7 @@ public void initialize() { config.setDriverClassName(driver); config.setPoolName("PlumBot-MySQL"); config.setJdbcUrl("jdbc:mysql://" + DataBase.mysql_host() +":"+ DataBase.mysql_port() + "/" + DataBase.mysql_database() + DataBase.mysql_parameters()); - config.setUsername(DataBase.mysql_username()); + config.setUsername(DataBase.mysql_user()); config.setPassword(DataBase.mysql_password()); if (!DataBase.pool_connectionTestQuery().isEmpty()){ config.setConnectionTestQuery(DataBase.pool_connectionTestQuery()); From cd26750131c47817dbfbe8b4859bb73c69d75a70 Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Mon, 8 Jul 2024 12:11:14 +0800 Subject: [PATCH 12/16] fix bugs --- .../plumbot/event/kook/KookEvent.java | 64 ++++++++++++------- .../regadpole/plumbot/event/qq/QQEvent.java | 64 ++++++++++++------- .../internal/database/DatabaseManager.java | 6 +- 3 files changed, 85 insertions(+), 49 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index e9c27d0..ef9d24a 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -131,22 +131,34 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { e.getMessage().reply(p[0]+"尚未申请白名单"); return; } - int num = Integer.parseInt(p[1]); - List id = WhitelistHelper.removeAndGet(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单,"+p[0]+"目前拥有的白名单为"+id); + try { + int num = Integer.parseInt(p[1]); + List id = WhitelistHelper.removeAndGet(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单," + p[0] + "目前拥有的白名单为" + id); + } catch (NumberFormatException | IndexOutOfBoundsException exception) { + e.getMessage().reply("请正确输入序号"); + } catch (Exception exception) { + exception.printStackTrace(); + } }); return; } else { - int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName.isEmpty()) { - e.getMessage().reply("您尚未申请白名单"); - return; - } - List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单,您目前拥有的白名单为"+id); - }); + try { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + e.getMessage().reply("您尚未申请白名单"); + return; + } + List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,您目前拥有的白名单为" + id); + }); + } catch (NumberFormatException | IndexOutOfBoundsException exception) { + e.getMessage().reply("请正确输入序号"); + } catch (Exception exception) { + exception.printStackTrace(); + } return; } } @@ -335,16 +347,22 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { if (!Config.WhiteList()) { return; } - int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName.isEmpty()) { - e.getMessage().reply("您尚未申请白名单"); - return; - } - List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单,您目前的白名单为"+result); - }); + try { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + e.getMessage().reply("您尚未申请白名单"); + return; + } + List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,您目前的白名单为" + result); + }); + } catch (NumberFormatException | IndexOutOfBoundsException exception) { + e.getMessage().reply("请正确输入序号"); + } catch (Exception exception) { + exception.printStackTrace(); + } return; } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index 3808acf..96f7726 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -158,22 +158,34 @@ public void onGroupMessageReceive(GroupMessage e){ bot.sendMsg(true, p[0]+"尚未申请白名单", groupID); return; } - int num = Integer.parseInt(p[1]); - List id = WhitelistHelper.removeAndGet(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,"+p[0]+"目前拥有的白名单为"+id, groupID); + try{ + int num = Integer.parseInt(p[1]); + List id = WhitelistHelper.removeAndGet(p[0], num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,"+p[0]+"目前拥有的白名单为"+id, groupID); + } catch (NumberFormatException | IndexOutOfBoundsException exception) { + bot.sendMsg(true, "请正确输入序号", groupID); + } catch (Exception exception) { + exception.printStackTrace(); + } }); return; } else { - int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName.isEmpty()) { - bot.sendMsg(true, "您尚未申请白名单", groupID); - return; - } - List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为"+id, groupID); - }); + try { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为" + id, groupID); + }); + } catch (NumberFormatException | IndexOutOfBoundsException exception) { + bot.sendMsg(true, "请正确输入序号", groupID); + } catch (Exception exception) { + exception.printStackTrace(); + } return; } } @@ -361,16 +373,22 @@ public void onGroupMessageReceive(GroupMessage e){ if (!Config.WhiteList()) { return; } - int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); - PlumBot.getScheduler().runTaskAsynchronously(() -> { - List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); - if (idForName.isEmpty()) { - bot.sendMsg(true, "您尚未申请白名单", groupID); - return; - } - List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,您目前的白名单为"+result, groupID); - }); + try { + int num = Integer.parseInt(matcher.group().replace(Prefix + "删除白名单 ", "")); + PlumBot.getScheduler().runTaskAsynchronously(() -> { + List idForName = DatabaseManager.getBind(String.valueOf(senderID), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + if (idForName.isEmpty()) { + bot.sendMsg(true, "您尚未申请白名单", groupID); + return; + } + List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前的白名单为" + result, groupID); + }); + } catch (NumberFormatException | IndexOutOfBoundsException exception) { + bot.sendMsg(true, "请正确输入序号", groupID); + } catch (Exception exception) { + exception.printStackTrace(); + } return; } diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java index 18b9a86..d84e28b 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -138,7 +138,7 @@ public static void removeBindid(String id,String mode, Database db) { } } - public static void removeBind(String qq, int num, String mode, Database db) { + public static void removeBind(String qq, int num, String mode, Database db) throws IndexOutOfBoundsException { String createTable = "CREATE TABLE IF NOT EXISTS whitelist (id TINYTEXT NOT NULL, qq long NOT NULL);"; String select = "SELECT * FROM whitelist WHERE qq=" + qq + ";"; @@ -160,7 +160,7 @@ public static void removeBind(String qq, int num, String mode, Database db) { resultSet.next(); } if (resultSet.isAfterLast()){ - return; + throw new IndexOutOfBoundsException("Error index"); } String id = resultSet.getString("id"); if (id == null) { @@ -190,7 +190,7 @@ public static void removeBind(String qq, int num, String mode, Database db) { resultSet.next(); } if (resultSet.isAfterLast()){ - return; + throw new IndexOutOfBoundsException("Error index"); } String id = resultSet.getString("id"); if (id == null) { From 99bf8b3307e5063964aee205cbe8f75db1c0ce8d Mon Sep 17 00:00:00 2001 From: RegadPole Date: Fri, 12 Jul 2024 16:58:22 +0800 Subject: [PATCH 13/16] fixed --- README.md | 4 ++-- .../regadpole/plumbot/command/Commands.java | 2 +- .../plumbot/event/kook/KookEvent.java | 20 +++++++++++++------ .../regadpole/plumbot/event/qq/QQEvent.java | 20 +++++++++++++------ 4 files changed, 31 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index f6b4e52..756653c 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ [![Modrinth Downloads](https://img.shields.io/modrinth/dt/plumbot?logo=modrinth)](https://modrinth.com/plugin/plumbot) -本插件适用于[go-cqhttp](https://github.com/Mrs4s/go-cqhttp)中的http通信模式 和 [kook](kookapp.cn)的websocket模式 +本插件适用于[go-cqhttp](https://github.com/Mrs4s/go-cqhttp)中的http通信模式 和 [kook](https://kookapp.cn)的websocket模式 测试环境:[go-cqhttp1.1.0](https://github.com/Mrs4s/go-cqhttp/releases/tag/v1.1.0) / [kook机器人](https://developer.kookapp.cn/app/index)+[paper1.20](https://papermc.io/downloads/paper)+[zulujdk17](https://www.azul.com/downloads) @@ -27,7 +27,7 @@ ## 安全状态 [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FRegadPoleCN%2FPlumBot.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FRegadPoleCN%2FPlumBot?ref=badge_large) -[![Security Status](https://www.murphysec.com/platform3/v31/badge/1744894945006768128.svg)](https://www.murphysec.com/console/report/1688753239833206784/1744894945006768128) +[![Security Status](https://www.murphysec.com/platform3/v31/badge/1811686602642419712.svg)](https://www.murphysec.com/console/report/1688753239833206784/1811686602642419712) ## 开源声明 diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java index 9893108..b01fc7f 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -127,7 +127,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St sender.sendMessage(plugin.getEnvironment().prefix+"§c绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); return true; } - List id = WhitelistHelper.addAndGet(args[1], args[0], DataBase.type().toLowerCase(), PlumBot.getDatabase()); + List id = WhitelistHelper.addAndGet(args[2], args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase()); sender.sendMessage(plugin.getEnvironment().prefix+"§a成功申请白名单," + args[0] + "目前的白名单为" + id); } break; diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java index ef9d24a..330c539 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/kook/KookEvent.java @@ -151,10 +151,14 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { e.getMessage().reply("您尚未申请白名单"); return; } - List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单,您目前拥有的白名单为" + id); + try { + List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,您目前拥有的白名单为" + id); + } catch (IndexOutOfBoundsException exception) { + e.getMessage().reply("请正确输入序号"); + } }); - } catch (NumberFormatException | IndexOutOfBoundsException exception) { + } catch (NumberFormatException exception) { e.getMessage().reply("请正确输入序号"); } catch (Exception exception) { exception.printStackTrace(); @@ -355,10 +359,14 @@ public void onChannelMessageReceive(ChannelMessageEvent e) { e.getMessage().reply("您尚未申请白名单"); return; } - List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - e.getMessage().reply("成功移出白名单,您目前的白名单为" + result); + try { + List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + e.getMessage().reply("成功移出白名单,您目前的白名单为" + result); + } catch (IndexOutOfBoundsException exception) { + e.getMessage().reply("请正确输入序号"); + } }); - } catch (NumberFormatException | IndexOutOfBoundsException exception) { + } catch (NumberFormatException exception) { e.getMessage().reply("请正确输入序号"); } catch (Exception exception) { exception.printStackTrace(); diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java index 96f7726..4b8da94 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/qq/QQEvent.java @@ -178,10 +178,14 @@ public void onGroupMessageReceive(GroupMessage e){ bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为" + id, groupID); + try { + List id = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前拥有的白名单为" + id, groupID); + } catch (IndexOutOfBoundsException exception) { + bot.sendMsg(true, "请正确输入序号", groupID); + } }); - } catch (NumberFormatException | IndexOutOfBoundsException exception) { + } catch (NumberFormatException exception) { bot.sendMsg(true, "请正确输入序号", groupID); } catch (Exception exception) { exception.printStackTrace(); @@ -381,10 +385,14 @@ public void onGroupMessageReceive(GroupMessage e){ bot.sendMsg(true, "您尚未申请白名单", groupID); return; } - List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); - bot.sendMsg(true, "成功移出白名单,您目前的白名单为" + result, groupID); + try { + List result = WhitelistHelper.removeAndGet(String.valueOf(senderID), num, DataBase.type().toLowerCase(), PlumBot.getDatabase()); + bot.sendMsg(true, "成功移出白名单,您目前的白名单为" + result, groupID); + } catch (IndexOutOfBoundsException exception) { + bot.sendMsg(true, "请正确输入序号", groupID); + } }); - } catch (NumberFormatException | IndexOutOfBoundsException exception) { + } catch (NumberFormatException exception) { bot.sendMsg(true, "请正确输入序号", groupID); } catch (Exception exception) { exception.printStackTrace(); From 1802e6eb25a71dffbad8f18d6bc6cd59df725b17 Mon Sep 17 00:00:00 2001 From: RegadPole Date: Fri, 12 Jul 2024 17:39:24 +0800 Subject: [PATCH 14/16] fix --- .../me/regadpole/plumbot/config/Config.java | 2 +- .../plumbot/event/server/ServerEvent.java | 48 ++++++++++++++++--- plumbot-bukkit/src/main/resources/config.yml | 2 +- 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java index 5233767..0b01794 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/config/Config.java @@ -41,7 +41,7 @@ public static void createConfig(){ if (!Config.getBotYamlVersion().equals("1.3.0")){ INSTANCE.saveResource(botFile.getName(), true); } - if (!Config.getConfigYamlVersion().equals("1.3.2")){ + if (!Config.getConfigYamlVersion().equals("1.3.3")){ INSTANCE.saveResource(configFile.getName(), true); } if (!Config.getCommandsYamlVersion().equals("1.2.2")){ diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java index 7590570..3fde8ab 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java @@ -104,14 +104,48 @@ public void onPreLogin(AsyncPlayerPreLoginEvent event){ @EventHandler(priority = EventPriority.MONITOR) public void onJoin(PlayerJoinEvent event){ - String name = event.getPlayer().getName(); + Player player = event.getPlayer(); + String name = player.getName(); - if (!Config.JoinAndLeave()){ - return; - } - List groups = Config.getGroupQQs(); - for (long groupID : groups){ - PlumBot.getBot().sendMsg(true, "玩家"+name+"加入游戏",groupID); + if (Config.WhiteList()) { + PlumBot.getScheduler().runTaskAsynchronously(() -> { + long qq; + qq = (DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase())); + if (qq == 0L) { + player.kickPlayer(Args.WhitelistKick()); + List groups = Config.getGroupQQs(); + for (long groupID : groups) { + PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", groupID); + } + return; + } + for (long groupID : Config.getGroupQQs()) { + if(!PlumBot.getBot().checkUserInGroup(qq, groupID)){ + player.kickPlayer(Args.WhitelistKick()); + List groups = Config.getGroupQQs(); + for (long group : groups) { + PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", group); + } + DatabaseManager.removeBind(String.valueOf(qq), DataBase.type().toLowerCase(), PlumBot.getDatabase()); + return; + } + } + if (!Config.JoinAndLeave()){ + return; + } + List groups = Config.getGroupQQs(); + for (long groupID : groups){ + PlumBot.getBot().sendMsg(true, "玩家"+name+"加入游戏",groupID); + } + }); + } else { + if (!Config.JoinAndLeave()){ + return; + } + List groups = Config.getGroupQQs(); + for (long groupID : groups){ + PlumBot.getBot().sendMsg(true, "玩家"+name+"加入游戏",groupID); + } } } diff --git a/plumbot-bukkit/src/main/resources/config.yml b/plumbot-bukkit/src/main/resources/config.yml index 8d1b245..407c69c 100644 --- a/plumbot-bukkit/src/main/resources/config.yml +++ b/plumbot-bukkit/src/main/resources/config.yml @@ -1,5 +1,5 @@ #机器人功能设置 -Ver: "1.3.2" +Ver: "1.3.3" #QQ群聊命令前缀 Prefix: "/" From 011d67348c06d8920849f875755a612f15c65c6a Mon Sep 17 00:00:00 2001 From: RegadPole Date: Sun, 21 Jul 2024 16:54:37 +0800 Subject: [PATCH 15/16] pre-fix --- .../regadpole/plumbot/event/server/ServerEvent.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java index 3fde8ab..3ae9ac9 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/event/server/ServerEvent.java @@ -78,7 +78,7 @@ public void onPreLogin(AsyncPlayerPreLoginEvent event){ long qq; qq = (DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase())); if (qq == 0L) { - event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST, Args.WhitelistKick()); + PlumBot.getScheduler().runTask(() -> event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST, Args.WhitelistKick())); List groups = Config.getGroupQQs(); for (long groupID : groups) { PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", groupID); @@ -87,7 +87,7 @@ public void onPreLogin(AsyncPlayerPreLoginEvent event){ } for (long groupID : Config.getGroupQQs()) { if(!PlumBot.getBot().checkUserInGroup(qq, groupID)){ - event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST, Args.WhitelistKick()); + PlumBot.getScheduler().runTask(() -> event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_WHITELIST, Args.WhitelistKick())); List groups = Config.getGroupQQs(); for (long group : groups) { PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", group); @@ -96,7 +96,8 @@ public void onPreLogin(AsyncPlayerPreLoginEvent event){ return; } } - event.allow(); + PlumBot.getScheduler().runTask(event::allow); + }); } } @@ -112,7 +113,7 @@ public void onJoin(PlayerJoinEvent event){ long qq; qq = (DatabaseManager.getBindId(name, DataBase.type().toLowerCase(), PlumBot.getDatabase())); if (qq == 0L) { - player.kickPlayer(Args.WhitelistKick()); + PlumBot.getScheduler().runTask(() -> player.kickPlayer(Args.WhitelistKick())); List groups = Config.getGroupQQs(); for (long groupID : groups) { PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", groupID); @@ -121,7 +122,7 @@ public void onJoin(PlayerJoinEvent event){ } for (long groupID : Config.getGroupQQs()) { if(!PlumBot.getBot().checkUserInGroup(qq, groupID)){ - player.kickPlayer(Args.WhitelistKick()); + PlumBot.getScheduler().runTask(() -> player.kickPlayer(Args.WhitelistKick())); List groups = Config.getGroupQQs(); for (long group : groups) { PlumBot.getBot().sendMsg(true, "玩家" + name + "因为未在白名单中被踢出", group); From fd349b22879e2f62701fe5e511fdea669188819c Mon Sep 17 00:00:00 2001 From: RegadPoleCN Date: Tue, 30 Jul 2024 11:26:03 +0800 Subject: [PATCH 16/16] fix bugs when using mysql & using commands --- .../me/regadpole/plumbot/command/Commands.java | 6 +++--- .../plumbot/internal/database/DatabaseManager.java | 14 ++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java index b01fc7f..f3180bd 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/command/Commands.java @@ -123,12 +123,12 @@ public boolean onCommand(CommandSender sender, Command command, String label, St return true; } if (args.length == 3) { - if (!WhitelistHelper.checkIDNotExist(args[1])) { - sender.sendMessage(plugin.getEnvironment().prefix+"§c绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase())); + if (!WhitelistHelper.checkIDNotExist(args[2])) { + sender.sendMessage(plugin.getEnvironment().prefix+"§c绑定失败,此ID已绑定用户" + DatabaseManager.getBindId(args[2], DataBase.type().toLowerCase(), PlumBot.getDatabase())); return true; } List id = WhitelistHelper.addAndGet(args[2], args[1], DataBase.type().toLowerCase(), PlumBot.getDatabase()); - sender.sendMessage(plugin.getEnvironment().prefix+"§a成功申请白名单," + args[0] + "目前的白名单为" + id); + sender.sendMessage(plugin.getEnvironment().prefix+"§a成功申请白名单," + args[1] + "目前的白名单为" + id); } break; case "kook": diff --git a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java index d84e28b..695f3ec 100644 --- a/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java +++ b/plumbot-bukkit/src/main/java/me/regadpole/plumbot/internal/database/DatabaseManager.java @@ -242,9 +242,6 @@ public static void removeBind(String qq, String mode, Database db) { ResultSet resultSet = connection.prepareStatement(select).executeQuery(); - if (resultSet.isBeforeFirst()) { - resultSet.next(); - } connection.prepareStatement(delete).executeUpdate(); resultSet.close(); connection.close(); @@ -270,10 +267,9 @@ public static long getBindId(String id, String mode, Database db) { ResultSet resultSet = connection.prepareStatement(select).executeQuery(); - if (resultSet.isBeforeFirst()) { - resultSet.next(); + if (resultSet.next()) { + qq = resultSet.getLong("qq"); } - qq = resultSet.getLong("qq"); resultSet.close(); connection.close(); break; @@ -315,8 +311,10 @@ public static List getBind(String qq,String mode, Database db) { ResultSet resultSet = connection.prepareStatement(select).executeQuery(); - if (resultSet.isBeforeFirst()) { - resultSet.next(); + if (!resultSet.next()) { + resultSet.close(); + connection.close(); + break; } do { String tempId = resultSet.getString("id");