├── .gitattributes ├── .github └── workflows │ └── build.yml ├── .gitignore ├── .gitmodules ├── Dockerfile ├── LICENSE ├── README.md ├── kaiheila-onebot.sln ├── src ├── Assets │ ├── kaiheila.ico │ └── kaiheila.png ├── Cq │ ├── AuthorizationHelper.cs │ ├── Codes │ │ ├── CqCodeAt.cs │ │ ├── CqCodeBase.cs │ │ ├── CqCodeDice.cs │ │ ├── CqCodeEncoder.cs │ │ ├── CqCodeFace.cs │ │ ├── CqCodeHost.cs │ │ ├── CqCodeImage.cs │ │ ├── CqCodeRaw.cs │ │ ├── CqCodeRecord.cs │ │ ├── CqCodeRps.cs │ │ ├── CqCodeShake.cs │ │ ├── CqCodeText.cs │ │ └── CqCodeVideo.cs │ ├── Communication │ │ ├── HttpHost.cs │ │ └── WsHost.cs │ ├── Controllers │ │ ├── CqControllerBase.cs │ │ ├── CqControllerFile.cs │ │ ├── CqControllerFriend.cs │ │ ├── CqControllerGroup.cs │ │ ├── CqControllerSendMessage.cs │ │ └── CqControllerStatus.cs │ ├── CqContext.cs │ ├── CqHost.cs │ ├── Database │ │ ├── CqAsset.cs │ │ └── CqDatabaseContext.cs │ ├── Events │ │ ├── CqEventBase.cs │ │ ├── CqEventGroupMessage.cs │ │ └── CqEventHelper.cs │ ├── Handlers │ │ ├── CqActionHandler.cs │ │ └── CqEventHandler.cs │ └── Message │ │ ├── CqMessage.cs │ │ └── CqMessageHost.cs ├── Kh │ └── KhHost.cs ├── Program.cs ├── Resources │ ├── config.json │ └── create_db.sql ├── Storage │ ├── Config.cs │ ├── ConfigHelper.cs │ └── StorageHelper.cs ├── Utils │ ├── CommunicationHelper.cs │ └── LifecycleHost.cs └── kaiheila-onebot.csproj └── test ├── Cq ├── Code │ └── CqCodes.cs ├── Controllers │ └── CqControllers.cs ├── Events │ └── CqEvents.cs └── Message │ └── CqMessages.cs └── kaiheila-onebot-test.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | name: Build and Test 8 | 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - uses: actions/checkout@v2 13 | with: 14 | submodules: recursive 15 | - name: Setup .NET Core 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: '5.0' 19 | - name: Install dependencies 20 | run: dotnet restore 21 | - name: Build 22 | run: dotnet build ./src/kaiheila-onebot.csproj --configuration Release --no-restore 23 | - name: Test 24 | run: dotnet test ./test/kaiheila-onebot-test.csproj --no-restore --verbosity normal 25 | 26 | pack: 27 | name: Build Package 28 | 29 | needs: [build] 30 | 31 | runs-on: ubuntu-latest 32 | 33 | steps: 34 | - uses: actions/checkout@v2 35 | with: 36 | submodules: recursive 37 | - name: Setup .NET Core 38 | uses: actions/setup-dotnet@v1 39 | with: 40 | dotnet-version: '5.0' 41 | - name: Install dependencies 42 | run: dotnet restore 43 | - name: Build 44 | run: dotnet build ./src/kaiheila-onebot.csproj --configuration Release --no-restore 45 | - name: Pack 46 | run: dotnet pack ./src/kaiheila-onebot.csproj -o src/bin/publish/ --configuration Release --no-restore 47 | - name: Archive production artifacts 48 | uses: actions/upload-artifact@v2 49 | with: 50 | name: kaiheila-onebot-nupkg-${{ github.sha }} 51 | path: src/bin/publish 52 | 53 | docker: 54 | name: Build Image 55 | 56 | needs: [build] 57 | 58 | runs-on: ubuntu-latest 59 | 60 | steps: 61 | - uses: actions/checkout@v2 62 | with: 63 | submodules: recursive 64 | - name: Docker Build 65 | run: docker build -t kaiheila-onebot . 66 | - name: Export Image 67 | run: | 68 | mkdir image 69 | docker save kaiheila-onebot > ./image/kaiheila-onebot-docker.tar 70 | - name: Archive production artifacts 71 | uses: actions/upload-artifact@v2 72 | with: 73 | name: kaiheila-onebot-docker-${{ github.sha }} 74 | path: image 75 | 76 | publish: 77 | name: Build Binary 78 | 79 | strategy: 80 | matrix: 81 | target: 82 | - '{"rid":"win-x64","os":"windows-latest"}' 83 | - '{"rid":"win-x86","os":"windows-latest"}' 84 | - '{"rid":"win-arm","os":"windows-latest"}' 85 | - '{"rid":"win-arm64","os":"windows-latest"}' 86 | - '{"rid":"linux-x64","os":"ubuntu-latest"}' 87 | - '{"rid":"linux-arm","os":"ubuntu-latest"}' 88 | - '{"rid":"linux-arm64","os":"ubuntu-latest"}' 89 | - '{"rid":"osx-x64","os":"macos-latest"}' 90 | 91 | needs: [build] 92 | 93 | runs-on: ${{ fromJson(matrix.target).os }} 94 | 95 | steps: 96 | - uses: actions/checkout@v2 97 | with: 98 | submodules: recursive 99 | - name: Setup .NET Core 100 | uses: actions/setup-dotnet@v1 101 | with: 102 | dotnet-version: '5.0' 103 | - name: Publish 104 | run: dotnet publish src/kaiheila-onebot.csproj -o src/bin/${{ fromJson(matrix.target).rid }}/publish -c Release -r ${{ fromJson(matrix.target).rid }} --self-contained true -p:PublishReadyToRun=true -p:PublishSingleFile=true -p:PublishTrimmed=true -p:IncludeNativeLibrariesForSelfExtract=true 105 | - name: Remove pdb Files 106 | shell: bash 107 | run: rm src/bin/${{ fromJson(matrix.target).rid }}/publish/*.pdb 108 | - name: Archive production artifacts 109 | uses: actions/upload-artifact@v2 110 | with: 111 | name: kaiheila-onebot-${{ fromJson(matrix.target).rid }}-${{ github.sha }} 112 | path: src/bin/${{ fromJson(matrix.target).rid }}/publish 113 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | 342 | # Temp files 343 | Temp/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "sdk"] 2 | path = sdk 3 | url = https://github.com/kaiheila-community/kaiheila-dotnet.git 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build and Test 2 | FROM mcr.microsoft.com/dotnet/sdk AS build 3 | LABEL maintainer="afanyiyu@hotmail.com" 4 | # Copy Files 5 | COPY . /app 6 | WORKDIR /app 7 | # Build 8 | RUN dotnet restore 9 | RUN dotnet build ./src/kaiheila-onebot.csproj --configuration Release --no-restore 10 | RUN dotnet test ./test/kaiheila-onebot-test.csproj --no-restore --verbosity normal 11 | 12 | # Pack 13 | FROM mcr.microsoft.com/dotnet/runtime AS final 14 | # Copy Files 15 | WORKDIR /app 16 | COPY --from=build /app/src/bin/Release/net5.0 /app 17 | RUN mkdir storage 18 | VOLUME /app/storage 19 | EXPOSE 5700 6700 20 | ENTRYPOINT docker kaiheila-onebot.dll 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 kaiheila-community 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kaiheila-onebot 2 | 3 | OneBot(原CQHTTP)的开黑啦(kaiheila)平台实现。 4 | 5 | ## ⚠WIP⚠ 6 | 7 | 虽然大部分代码已经可用,项目仍在建设中。目前,项目内仍有大量的过时代码和无用代码。 8 | 9 | 在 `v0.1.0` 发布之前,不接受任何 Pull Request。你可以在 Issues 中发起讨论。 10 | -------------------------------------------------------------------------------- /kaiheila-onebot.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26124.0 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "kaiheila-onebot", "src\kaiheila-onebot.csproj", "{8D14A36F-4568-4353-8D84-B10B42980B69}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "kaiheila-onebot-test", "test\kaiheila-onebot-test.csproj", "{F638334B-56AF-4543-9853-CB67777418CD}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sdk", "sdk", "{6489D2FB-597F-4C6D-974A-C0F80A3A5C22}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{0AFA46A3-0ADE-42C2-9DBC-F418E7A89A60}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "kaiheila-dotnet", "sdk\src\core\kaiheila-dotnet.csproj", "{83854AFC-9C80-4E13-B405-B2C74DC3CC96}" 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{E5EEB2B3-65FF-409D-BDE9-7B9DC9592148}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "kaiheila-dotnet-test", "sdk\test\core\kaiheila-dotnet-test.csproj", "{4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}" 19 | EndProject 20 | Global 21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 22 | Debug|Any CPU = Debug|Any CPU 23 | Debug|x64 = Debug|x64 24 | Debug|x86 = Debug|x86 25 | Release|Any CPU = Release|Any CPU 26 | Release|x64 = Release|x64 27 | Release|x86 = Release|x86 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 33 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Debug|x64.ActiveCfg = Debug|Any CPU 36 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Debug|x64.Build.0 = Debug|Any CPU 37 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Debug|x86.ActiveCfg = Debug|Any CPU 38 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Debug|x86.Build.0 = Debug|Any CPU 39 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Release|x64.ActiveCfg = Release|Any CPU 42 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Release|x64.Build.0 = Release|Any CPU 43 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Release|x86.ActiveCfg = Release|Any CPU 44 | {8D14A36F-4568-4353-8D84-B10B42980B69}.Release|x86.Build.0 = Release|Any CPU 45 | {F638334B-56AF-4543-9853-CB67777418CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {F638334B-56AF-4543-9853-CB67777418CD}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {F638334B-56AF-4543-9853-CB67777418CD}.Debug|x64.ActiveCfg = Debug|Any CPU 48 | {F638334B-56AF-4543-9853-CB67777418CD}.Debug|x64.Build.0 = Debug|Any CPU 49 | {F638334B-56AF-4543-9853-CB67777418CD}.Debug|x86.ActiveCfg = Debug|Any CPU 50 | {F638334B-56AF-4543-9853-CB67777418CD}.Debug|x86.Build.0 = Debug|Any CPU 51 | {F638334B-56AF-4543-9853-CB67777418CD}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {F638334B-56AF-4543-9853-CB67777418CD}.Release|Any CPU.Build.0 = Release|Any CPU 53 | {F638334B-56AF-4543-9853-CB67777418CD}.Release|x64.ActiveCfg = Release|Any CPU 54 | {F638334B-56AF-4543-9853-CB67777418CD}.Release|x64.Build.0 = Release|Any CPU 55 | {F638334B-56AF-4543-9853-CB67777418CD}.Release|x86.ActiveCfg = Release|Any CPU 56 | {F638334B-56AF-4543-9853-CB67777418CD}.Release|x86.Build.0 = Release|Any CPU 57 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 58 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Debug|Any CPU.Build.0 = Debug|Any CPU 59 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Debug|x64.ActiveCfg = Debug|Any CPU 60 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Debug|x64.Build.0 = Debug|Any CPU 61 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Debug|x86.ActiveCfg = Debug|Any CPU 62 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Debug|x86.Build.0 = Debug|Any CPU 63 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Release|Any CPU.ActiveCfg = Release|Any CPU 64 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Release|Any CPU.Build.0 = Release|Any CPU 65 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Release|x64.ActiveCfg = Release|Any CPU 66 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Release|x64.Build.0 = Release|Any CPU 67 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Release|x86.ActiveCfg = Release|Any CPU 68 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96}.Release|x86.Build.0 = Release|Any CPU 69 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 70 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Debug|Any CPU.Build.0 = Debug|Any CPU 71 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Debug|x64.ActiveCfg = Debug|Any CPU 72 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Debug|x64.Build.0 = Debug|Any CPU 73 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Debug|x86.ActiveCfg = Debug|Any CPU 74 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Debug|x86.Build.0 = Debug|Any CPU 75 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Release|Any CPU.ActiveCfg = Release|Any CPU 76 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Release|Any CPU.Build.0 = Release|Any CPU 77 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Release|x64.ActiveCfg = Release|Any CPU 78 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Release|x64.Build.0 = Release|Any CPU 79 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Release|x86.ActiveCfg = Release|Any CPU 80 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24}.Release|x86.Build.0 = Release|Any CPU 81 | EndGlobalSection 82 | GlobalSection(NestedProjects) = preSolution 83 | {0AFA46A3-0ADE-42C2-9DBC-F418E7A89A60} = {6489D2FB-597F-4C6D-974A-C0F80A3A5C22} 84 | {83854AFC-9C80-4E13-B405-B2C74DC3CC96} = {0AFA46A3-0ADE-42C2-9DBC-F418E7A89A60} 85 | {E5EEB2B3-65FF-409D-BDE9-7B9DC9592148} = {6489D2FB-597F-4C6D-974A-C0F80A3A5C22} 86 | {4FD5396A-F6F0-4B91-AA6C-3DBB5EC6CB24} = {E5EEB2B3-65FF-409D-BDE9-7B9DC9592148} 87 | EndGlobalSection 88 | EndGlobal 89 | -------------------------------------------------------------------------------- /src/Assets/kaiheila.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaiheila-community/kaiheila-onebot/f9dba11186fe8dc88eefb071f34db1b9d7b7803e/src/Assets/kaiheila.ico -------------------------------------------------------------------------------- /src/Assets/kaiheila.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kaiheila-community/kaiheila-onebot/f9dba11186fe8dc88eefb071f34db1b9d7b7803e/src/Assets/kaiheila.png -------------------------------------------------------------------------------- /src/Cq/AuthorizationHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Net; 3 | using System.Threading.Tasks; 4 | using Kaiheila.OneBot.Storage; 5 | using Kaiheila.OneBot.Utils; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.Extensions.Options; 9 | using Microsoft.Extensions.Primitives; 10 | 11 | namespace Kaiheila.OneBot.Cq 12 | { 13 | public class AuthorizationMiddleware 14 | { 15 | private const string AuthorizationHeader = "Authorization"; 16 | private const string BearerPrefix = "Bearer "; 17 | 18 | public AuthorizationMiddleware( 19 | RequestDelegate next, 20 | IOptions options) 21 | { 22 | _next = next; 23 | _options = options; 24 | } 25 | 26 | private RequestDelegate _next; 27 | private readonly IOptions _options; 28 | 29 | public async Task InvokeAsync(HttpContext context) 30 | { 31 | // Skip Authorization When IsNullOrEmpty 32 | if (string.IsNullOrEmpty(_options.Value.Config.CqConfig.CqAuthConfig.AccessToken)) 33 | { 34 | await _next(context); 35 | return; 36 | } 37 | 38 | bool hasAccessTokenInHeader = context.Request.Headers 39 | .TryGetValue(AuthorizationHeader, out StringValues authValue) && authValue.Any(); 40 | 41 | if (hasAccessTokenInHeader) 42 | { 43 | if ( 44 | authValue.FirstOrDefault() == 45 | BearerPrefix + _options.Value.Config.CqConfig.CqAuthConfig.AccessToken) 46 | { 47 | await _next(context); 48 | return; 49 | } 50 | 51 | context.Response.SetStatusCode(HttpStatusCode.Forbidden); 52 | return; 53 | } 54 | 55 | bool hasAccessTokenInQuery = 56 | context.Request.Query.TryGetValue("access_token", out authValue) && 57 | authValue.Any(); 58 | 59 | if (hasAccessTokenInQuery) 60 | { 61 | if ( 62 | authValue.FirstOrDefault() == 63 | _options.Value.Config.CqConfig.CqAuthConfig.AccessToken) 64 | { 65 | await _next(context); 66 | return; 67 | } 68 | 69 | context.Response.SetStatusCode(HttpStatusCode.Forbidden); 70 | return; 71 | } 72 | 73 | context.Response.SetStatusCode(HttpStatusCode.Unauthorized); 74 | } 75 | } 76 | 77 | public static class AuthorizationExtensions 78 | { 79 | public static IApplicationBuilder UseCqAuthorization( 80 | this IApplicationBuilder builder, 81 | ConfigHelper configHelper) 82 | { 83 | builder.UseMiddleware( 84 | Options.Create(configHelper)); 85 | return builder; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeAt.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("at")] 6 | public class CqCodeAt : CqCodeBase 7 | { 8 | public CqCodeAt(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | Target = Params["qq"]; 12 | } 13 | 14 | public CqCodeAt(string target) 15 | { 16 | Target = target; 17 | } 18 | 19 | public readonly string Target; 20 | 21 | public override async Task ConvertToString() => $"(@:{Target} )"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using Kaiheila.Events; 5 | 6 | namespace Kaiheila.OneBot.Cq.Codes 7 | { 8 | public abstract class CqCodeBase 9 | { 10 | public Dictionary Params = new Dictionary(); 11 | 12 | public virtual async Task ConvertToKhEvent( 13 | CqContext context, 14 | long channel) => 15 | new KhEventTextMessage 16 | { 17 | Content = await ConvertToString() 18 | }; 19 | 20 | public abstract Task ConvertToString(); 21 | } 22 | 23 | [AttributeUsage(AttributeTargets.Class)] 24 | public sealed class CqCodeAttribute : Attribute 25 | { 26 | public CqCodeAttribute(string type) => Type = type; 27 | 28 | public readonly string Type; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeDice.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("dice")] 6 | public class CqCodeDice : CqCodeBase 7 | { 8 | public CqCodeDice(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | } 12 | 13 | public override async Task ConvertToString() => "(掷骰子)"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeEncoder.cs: -------------------------------------------------------------------------------- 1 | // References: 2 | // https://github.com/frank-bots/cqhttp.Cyan/blob/master/cqhttp.Cyan/Globals.cs 3 | 4 | namespace Kaiheila.OneBot.Cq.Codes 5 | { 6 | public static class CqCodeEncoder 7 | { 8 | public static string EncodeText(string enc) => 9 | enc 10 | .Replace("&", "&") 11 | .Replace("[", "[") 12 | .Replace("]", "]"); 13 | 14 | public static string EncodeValue(string text) => 15 | EncodeText(text) 16 | .Replace(",", ","); 17 | 18 | public static string Decode(string enc) => 19 | enc 20 | .Replace("[", "[") 21 | .Replace("]", "]") 22 | .Replace(",", ",") 23 | .Replace("&", "&"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeFace.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("face")] 6 | public class CqCodeFace : CqCodeBase 7 | { 8 | public CqCodeFace(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | Id = ushort.Parse(Params["id"]); 12 | } 13 | 14 | public CqCodeFace(ushort id) 15 | { 16 | Id = id; 17 | } 18 | 19 | public readonly ushort Id; 20 | 21 | public override async Task ConvertToString() => $"(表情:{Id} )"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeHost.cs: -------------------------------------------------------------------------------- 1 | // References: 2 | // https://github.com/frank-bots/cqhttp.Cyan/blob/master/cqhttp.Cyan/Globals.cs 3 | // https://github.com/frank-bots/cqhttp.Cyan/blob/master/cqhttp.Cyan/Messages/Serialization.cs 4 | 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Composition; 8 | using System.Linq; 9 | using System.Text.RegularExpressions; 10 | using Microsoft.Extensions.Logging; 11 | using Newtonsoft.Json.Linq; 12 | 13 | namespace Kaiheila.OneBot.Cq.Codes 14 | { 15 | /// 16 | /// CQ码主机。 17 | /// 18 | [Export] 19 | public class CqCodeHost 20 | { 21 | /// 22 | /// 初始化CQ码主机。 23 | /// 24 | /// CQ码主机日志记录器。 25 | public CqCodeHost( 26 | ILogger logger) 27 | { 28 | _logger = logger; 29 | 30 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => 31 | x.GetTypes() 32 | .Where(type => Attribute.GetCustomAttribute(type, typeof(CqCodeAttribute)) is not null))) 33 | { 34 | string cqType = (Attribute.GetCustomAttribute(type, typeof(CqCodeAttribute)) as CqCodeAttribute)?.Type; 35 | if (cqType == null || _codeTypes.ContainsKey(cqType) || type.FullName == null) continue; 36 | 37 | _codeTypes.Add(cqType, type); 38 | } 39 | 40 | _logger.LogInformation($"加载了{_codeTypes.Count}个CQ码类型。"); 41 | } 42 | 43 | #region Regex 44 | 45 | public static readonly Regex ExtractRegex 46 | = new Regex(@"\[CQ:\w+?.*?\]"); 47 | 48 | public static readonly Regex ParseTypeRegex 49 | = new Regex(@"\[CQ:(\w+)"); 50 | 51 | public static readonly Regex ParseParamsRegex 52 | = new Regex(@",([\w\-\.]+?)=([^,\]]+)"); 53 | 54 | #endregion 55 | 56 | #region Parser 57 | 58 | public CqCodeBase Parse(string code) 59 | { 60 | string cqType; 61 | 62 | try 63 | { 64 | cqType = ParseTypeRegex.Match(code).Groups[1].Value; 65 | } 66 | catch (Exception e) 67 | { 68 | throw new CqCodeException("解析CQ码时出现错误。", e, CqCodePart.Struct, code); 69 | } 70 | 71 | if (string.IsNullOrEmpty(cqType) || !_codeTypes.ContainsKey(cqType)) 72 | throw new CqCodeException($"不支持的CQ码类型:{cqType}", null, CqCodePart.Type, code); 73 | 74 | CqCodeRaw cqCode = new CqCodeRaw(); 75 | 76 | try 77 | { 78 | foreach (Match match in ParseParamsRegex.Matches(code)) 79 | cqCode.Params.Add(match.Groups[1].Value, CqCodeEncoder.Decode(match.Groups[2].Value)); 80 | } 81 | catch (Exception e) 82 | { 83 | throw new CqCodeException("解析CQ码参数时出现错误。", e, CqCodePart.Params, code); 84 | } 85 | 86 | return Activator.CreateInstance(_codeTypes[cqType], cqCode) as CqCodeBase; 87 | } 88 | 89 | public CqCodeBase Parse(JToken token) 90 | { 91 | try 92 | { 93 | if (token["type"] is null || token["type"].Type != JTokenType.String) 94 | throw new CqCodeException("解析CQ码时出现错误。", null, CqCodePart.Type, token.ToString()); 95 | 96 | string cqType = token["type"].ToObject(); 97 | 98 | if (string.IsNullOrEmpty(cqType) || !_codeTypes.ContainsKey(cqType)) 99 | throw new CqCodeException($"不支持的CQ码类型:{cqType}", null, CqCodePart.Type, token.ToString()); 100 | 101 | return Activator.CreateInstance(_codeTypes[cqType], 102 | new CqCodeRaw(token["data"]?.ToObject>())) as CqCodeBase; 103 | } 104 | catch (Exception e) 105 | { 106 | throw new CqCodeException("解析CQ码时出现错误。", e, CqCodePart.Struct, token.ToString()); 107 | } 108 | } 109 | 110 | #endregion 111 | 112 | #region Code Types 113 | 114 | private readonly Dictionary _codeTypes = new Dictionary(); 115 | 116 | #endregion 117 | 118 | /// 119 | /// CQ码主机日志记录器。 120 | /// 121 | private readonly ILogger _logger; 122 | } 123 | 124 | [Serializable] 125 | public class CqCodeException : Exception 126 | { 127 | public CqCodeException( 128 | string message = "", 129 | Exception inner = null, 130 | CqCodePart part = CqCodePart.Struct, 131 | string code = "" 132 | ) : base(message, inner) 133 | { 134 | Part = part; 135 | Code = code; 136 | } 137 | 138 | public CqCodePart Part; 139 | 140 | public string Code; 141 | } 142 | 143 | public enum CqCodePart 144 | { 145 | Struct = 0, 146 | Type = 1, 147 | Params = 2 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeImage.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Kaiheila.Events; 3 | using Kaiheila.OneBot.Cq.Database; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace Kaiheila.OneBot.Cq.Codes 7 | { 8 | [CqCode("image")] 9 | public class CqCodeImage : CqCodeBase 10 | { 11 | public CqCodeImage(CqCodeRaw cqCode) 12 | { 13 | Params = cqCode.Params; 14 | File = Params["file"]; 15 | Url = Params.ContainsKey("url") ? Params["url"] : string.Empty; 16 | } 17 | 18 | public CqCodeImage(string file, string url) 19 | { 20 | File = file; 21 | Url = url; 22 | } 23 | 24 | public readonly string File; 25 | 26 | public readonly string Url; 27 | 28 | public override async Task ConvertToKhEvent(CqContext context, long channel) 29 | { 30 | CqDatabaseContext database = new CqDatabaseContext(); 31 | 32 | try 33 | { 34 | CqAsset asset = await database.Assets.SingleOrDefaultAsync(x => x.Url == Url); 35 | 36 | if (asset is null) 37 | { 38 | KhEventImage image = await context.KhHost.Bot.UploadImage( 39 | File, 40 | channel, 41 | Url); 42 | 43 | await database.Assets.AddAsync(new CqAsset 44 | { 45 | Path = image.Path, 46 | Url = Url, 47 | Name = File 48 | }); 49 | 50 | await database.SaveChangesAsync(); 51 | 52 | return image; 53 | } 54 | else 55 | { 56 | return new KhEventImage( 57 | asset.Path, 58 | asset.Name); 59 | } 60 | } 61 | finally 62 | { 63 | await database.DisposeAsync(); 64 | } 65 | } 66 | 67 | public override async Task ConvertToString() => $"(图片:{Url} )"; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeRaw.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | 4 | namespace Kaiheila.OneBot.Cq.Codes 5 | { 6 | [CqCode("raw")] 7 | public class CqCodeRaw : CqCodeBase 8 | { 9 | public CqCodeRaw() 10 | { 11 | 12 | } 13 | 14 | public CqCodeRaw(Dictionary @params) 15 | { 16 | Params = @params; 17 | } 18 | 19 | public override async Task ConvertToString() => "(不支持的消息)"; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeRecord.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("record")] 6 | public class CqCodeRecord : CqCodeBase 7 | { 8 | public CqCodeRecord(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | File = Params["file"]; 12 | Url = Params.ContainsKey("url") ? Params["url"] : string.Empty; 13 | } 14 | 15 | public CqCodeRecord(string file, string url) 16 | { 17 | File = file; 18 | Url = url; 19 | } 20 | 21 | public readonly string File; 22 | 23 | public readonly string Url; 24 | 25 | public override async Task ConvertToString() => $"(语音:{Url} )"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeRps.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("rps")] 6 | public class CqCodeRps : CqCodeBase 7 | { 8 | public CqCodeRps(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | } 12 | 13 | public override async Task ConvertToString() => "(猜拳)"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeShake.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("shake")] 6 | public class CqCodeShake : CqCodeBase 7 | { 8 | public CqCodeShake(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | } 12 | 13 | public override async Task ConvertToString() => "(窗口抖动)"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeText.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("text")] 6 | public class CqCodeText : CqCodeBase 7 | { 8 | public CqCodeText(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | Text = Params["text"]; 12 | } 13 | 14 | public CqCodeText(string text) 15 | { 16 | Text = text; 17 | } 18 | 19 | public readonly string Text; 20 | 21 | public override async Task ConvertToString() => Text; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Cq/Codes/CqCodeVideo.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace Kaiheila.OneBot.Cq.Codes 4 | { 5 | [CqCode("video")] 6 | public class CqCodeVideo : CqCodeBase 7 | { 8 | public CqCodeVideo(CqCodeRaw cqCode) 9 | { 10 | Params = cqCode.Params; 11 | File = Params["file"]; 12 | Url = Params.ContainsKey("url") ? Params["url"] : string.Empty; 13 | } 14 | 15 | public CqCodeVideo(string file, string url) 16 | { 17 | File = file; 18 | Url = url; 19 | } 20 | 21 | public readonly string File; 22 | 23 | public readonly string Url; 24 | 25 | public override async Task ConvertToString() => $"(视频:{Url} )"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Cq/Communication/HttpHost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Composition; 3 | using Kaiheila.OneBot.Cq.Handlers; 4 | using Kaiheila.OneBot.Storage; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace Kaiheila.OneBot.Cq.Communication 9 | { 10 | /// 11 | /// CQHTTP HTTP主机,负责OneBot协议中HTTP接口的监听和事件处理。 12 | /// 13 | [Export] 14 | public class HttpHost : IDisposable 15 | { 16 | /// 17 | /// 初始化CQHTTP HTTP主机。 18 | /// 19 | /// CQHTTP HTTP主机日志记录器。 20 | /// CQHTTP任务处理器。 21 | /// 提供访问应用配置能力的帮助类型。 22 | public HttpHost( 23 | ILogger logger, 24 | CqActionHandler cqActionHandler, 25 | ConfigHelper configHelper) 26 | { 27 | _logger = logger; 28 | _cqActionHandler = cqActionHandler; 29 | _configHelper = configHelper; 30 | } 31 | 32 | /// 33 | /// 启动CQHTTP HTTP主机。 34 | /// 35 | public void Run() 36 | { 37 | _logger.LogInformation("初始化CQHTTP HTTP主机。"); 38 | 39 | _webHost = CreateWebHostBuilder().Build(); 40 | 41 | _webHost.RunAsync(); 42 | _logger.LogInformation( 43 | $"CQHTTP HTTP主机已经开始在http://{_configHelper.Config.CqConfig.CqHttpHostConfig.Host}:{_configHelper.Config.CqConfig.CqHttpHostConfig.Port}上监听。"); 44 | } 45 | 46 | /// 47 | /// 释放CQHTTP HTTP主机和连接资源。 48 | /// 49 | public void Dispose() 50 | { 51 | _webHost?.Dispose(); 52 | } 53 | 54 | #region Web Host 55 | 56 | private IWebHost _webHost; 57 | 58 | private IWebHostBuilder CreateWebHostBuilder() => 59 | new WebHostBuilder() 60 | .UseKestrel() 61 | .UseUrls($"http://{_configHelper.Config.CqConfig.CqHttpHostConfig.Host}:{_configHelper.Config.CqConfig.CqHttpHostConfig.Port}") 62 | .Configure(builder => 63 | { 64 | builder 65 | .UseCqAuthorization(_configHelper) 66 | .UseCqActionHandler(_cqActionHandler); 67 | }); 68 | 69 | #endregion 70 | 71 | /// 72 | /// CQHTTP HTTP主机日志记录器。 73 | /// 74 | private readonly ILogger _logger; 75 | 76 | /// 77 | /// CQHTTP任务处理器。 78 | /// 79 | private readonly CqActionHandler _cqActionHandler; 80 | 81 | /// 82 | /// 提供访问应用配置能力的帮助类型。 83 | /// 84 | private readonly ConfigHelper _configHelper; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/Cq/Communication/WsHost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Composition; 4 | using System.Threading.Tasks; 5 | using Fleck; 6 | using Kaiheila.OneBot.Cq.Events; 7 | using Kaiheila.OneBot.Cq.Handlers; 8 | using Kaiheila.OneBot.Storage; 9 | using Microsoft.Extensions.Logging; 10 | using Newtonsoft.Json.Linq; 11 | 12 | namespace Kaiheila.OneBot.Cq.Communication 13 | { 14 | /// 15 | /// CQHTTP WS主机,负责OneBot协议中WS接口的监听和事件处理。 16 | /// 17 | [Export] 18 | public class WsHost : IDisposable 19 | { 20 | /// 21 | /// 初始化CQHTTP WS主机。 22 | /// 23 | /// CQHTTP WS主机日志记录器。 24 | /// CQHTTP任务处理器。 25 | /// CQHTTP事件处理器。 26 | /// 提供访问应用配置能力的帮助类型。 27 | public WsHost( 28 | ILogger logger, 29 | CqActionHandler cqActionHandler, 30 | CqEventHandler cqEventHandler, 31 | ConfigHelper configHelper) 32 | { 33 | _logger = logger; 34 | _cqActionHandler = cqActionHandler; 35 | _cqEventHandler = cqEventHandler; 36 | _configHelper = configHelper; 37 | } 38 | 39 | /// 40 | /// 启动CQHTTP WS主机。 41 | /// 42 | public void Run() 43 | { 44 | _logger.LogInformation("初始化CQHTTP WS主机。"); 45 | 46 | _server = new WebSocketServer( 47 | $"ws://{_configHelper.Config.CqConfig.CqWsHostConfig.Host}:{_configHelper.Config.CqConfig.CqWsHostConfig.Port}") 48 | { 49 | RestartAfterListenError = true 50 | }; 51 | 52 | _server.Start(socket => 53 | { 54 | _sockets.Add(socket); 55 | _logger.LogInformation($"WebSocket客户端接入。现在的客户端数量:{_sockets.Count}"); 56 | socket.OnMessage = async s => await SocketOnMessage(socket, s); 57 | socket.OnClose = () => 58 | { 59 | if (_sockets.Contains(socket)) _sockets.Remove(socket); 60 | _logger.LogInformation($"WebSocket客户端关闭。现在的客户端数量:{_sockets.Count}"); 61 | }; 62 | }); 63 | 64 | _cqEventHandler.Event.Subscribe(OnCqEvent); 65 | 66 | _logger.LogInformation( 67 | $"CQHTTP WS主机已经开始在ws://{_configHelper.Config.CqConfig.CqWsHostConfig.Host}:{_configHelper.Config.CqConfig.CqWsHostConfig.Port}上监听。"); 68 | } 69 | 70 | #region Event 71 | 72 | private void OnCqEvent(CqEventBase obj) => _sockets.ForEach(x => x.Send(obj.Result.ToString())); 73 | 74 | #endregion 75 | 76 | private async Task SocketOnMessage(IWebSocketConnection socket, string raw) 77 | { 78 | JObject json; 79 | JToken echo; 80 | string action; 81 | JToken payload; 82 | 83 | try 84 | { 85 | json = JObject.Parse(raw); 86 | echo = json["echo"]; 87 | // ReSharper disable once PossibleNullReferenceException 88 | action = json["action"].ToObject(); 89 | payload = json["params"]; 90 | } 91 | catch (Exception) 92 | { 93 | await socket.Send("{\"status\": \"failed\",\"retcode\": 1400,\"data\": null}"); 94 | return; 95 | } 96 | 97 | JToken token = _cqActionHandler.Process(action, payload); 98 | token["echo"] = echo; 99 | await socket.Send(token.ToString()); 100 | } 101 | 102 | /// 103 | /// 释放CQHTTP WS主机和连接资源。 104 | /// 105 | public void Dispose() 106 | { 107 | _server?.Dispose(); 108 | } 109 | 110 | #region WebSocket 111 | 112 | private WebSocketServer _server; 113 | 114 | private List _sockets = new List(); 115 | 116 | #endregion 117 | 118 | /// 119 | /// CQHTTP WS主机日志记录器。 120 | /// 121 | private readonly ILogger _logger; 122 | 123 | /// 124 | /// CQHTTP任务处理器。 125 | /// 126 | private readonly CqActionHandler _cqActionHandler; 127 | 128 | /// 129 | /// CQHTTP事件处理器。 130 | /// 131 | private readonly CqEventHandler _cqEventHandler; 132 | 133 | /// 134 | /// 提供访问应用配置能力的帮助类型。 135 | /// 136 | private readonly ConfigHelper _configHelper; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/Cq/Controllers/CqControllerBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json.Linq; 3 | 4 | namespace Kaiheila.OneBot.Cq.Controllers 5 | { 6 | /// 7 | /// CQHTTP任务控制器。 8 | /// 9 | public abstract class CqControllerBase 10 | { 11 | /// 12 | /// 初始化CQHTTP任务控制器。 13 | /// 14 | /// 任务上下文。 15 | protected CqControllerBase(CqContext context) 16 | { 17 | Context = context; 18 | } 19 | 20 | /// 21 | /// 执行任务。 22 | /// 23 | /// JSON报文。 24 | public abstract JToken Process(JToken payload); 25 | 26 | /// 27 | /// 任务上下文。 28 | /// 29 | protected readonly CqContext Context; 30 | } 31 | 32 | /// 33 | /// CQHTTP任务控制器。 34 | /// 35 | [AttributeUsage(AttributeTargets.Class)] 36 | public sealed class CqControllerAttribute : Attribute 37 | { 38 | /// 39 | /// 初始化CQHTTP任务控制器。 40 | /// 41 | /// 控制器的任务。 42 | public CqControllerAttribute(string action) => Action = action; 43 | 44 | /// 45 | /// 控制器的任务。 46 | /// 47 | public readonly string Action; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Cq/Controllers/CqControllerFile.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json.Linq; 2 | 3 | namespace Kaiheila.OneBot.Cq.Controllers 4 | { 5 | [CqController("can_send_image")] 6 | public class CqControllerCanSendImage : CqControllerBase 7 | { 8 | public CqControllerCanSendImage(CqContext context) : base(context) 9 | { 10 | } 11 | 12 | public override JToken Process(JToken payload) => 13 | JToken.FromObject(new 14 | { 15 | yes = true 16 | }); 17 | } 18 | 19 | [CqController("can_send_record")] 20 | public class CqControllerCanSendRecord : CqControllerBase 21 | { 22 | public CqControllerCanSendRecord(CqContext context) : base(context) 23 | { 24 | } 25 | 26 | public override JToken Process(JToken payload) => 27 | JToken.FromObject(new 28 | { 29 | yes = false 30 | }); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Cq/Controllers/CqControllerFriend.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using Kaiheila.Data; 5 | using Newtonsoft.Json.Linq; 6 | 7 | namespace Kaiheila.OneBot.Cq.Controllers 8 | { 9 | [CqController("get_login_info")] 10 | public class CqControllerGetLoginInfo : CqControllerBase 11 | { 12 | public CqControllerGetLoginInfo(CqContext context) : base(context) 13 | { 14 | } 15 | 16 | public override JToken Process(JToken payload) 17 | { 18 | Task getUserStateAsync = Context.KhHost.Bot.GetUserState(); 19 | getUserStateAsync.Wait(); 20 | KhUser user = getUserStateAsync.Result; 21 | return JObject.FromObject(new 22 | { 23 | user_id = user.Id, 24 | nickname = user.Username 25 | }); 26 | } 27 | } 28 | 29 | [CqController("get_friend_list")] 30 | public class CqControllerGetFriendList : CqControllerBase 31 | { 32 | public CqControllerGetFriendList(CqContext context) : base(context) 33 | { 34 | } 35 | 36 | public override JToken Process(JToken payload) 37 | { 38 | Task> getFriendsAsync = Context.KhHost.Bot.GetFriends(KhFriendsType.Friend); 39 | getFriendsAsync.Wait(); 40 | List users = getFriendsAsync.Result; 41 | return JArray.FromObject(users.Select(user => new 42 | { 43 | user_id = user.Id, 44 | nickname = user.Username, 45 | remark = "" 46 | })); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Cq/Controllers/CqControllerGroup.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Kaiheila.Data; 3 | using Newtonsoft.Json.Linq; 4 | 5 | namespace Kaiheila.OneBot.Cq.Controllers 6 | { 7 | [CqController("get_stranger_info")] 8 | public class CqControllerGetStrangerInfo : CqControllerBase 9 | { 10 | public CqControllerGetStrangerInfo(CqContext context) : base(context) 11 | { 12 | } 13 | 14 | public override JToken Process(JToken payload) 15 | { 16 | Task getUserStateAsync = Context.KhHost.Bot.GetUserState(long.Parse(payload["user_id"]?.ToObject()!)); 17 | getUserStateAsync.Wait(); 18 | KhUser user = getUserStateAsync.Result; 19 | 20 | return JToken.FromObject(new 21 | { 22 | user_id = user.Id, 23 | nickname = user.Username, 24 | sex = "unknown", 25 | age = 18 26 | }); 27 | } 28 | } 29 | 30 | [CqController("get_group_member_info")] 31 | public class CqControllerGetGroupMemberInfo : CqControllerBase 32 | { 33 | public CqControllerGetGroupMemberInfo(CqContext context) : base(context) 34 | { 35 | } 36 | 37 | public override JToken Process(JToken payload) 38 | { 39 | Task getUserStateAsync = Context.KhHost.Bot.GetUserState(long.Parse(payload["user_id"]?.ToObject()!)); 40 | getUserStateAsync.Wait(); 41 | KhUser user = getUserStateAsync.Result; 42 | 43 | return JToken.FromObject(new 44 | { 45 | user_id = user.Id, 46 | nickname = user.Username, 47 | card = "", 48 | sex = "unknown", 49 | age = 18, 50 | area = "", 51 | join_time = 0, 52 | last_sent_time = 0, 53 | level = "", 54 | role = "member", 55 | unfriendly = false, 56 | title = "", 57 | title_expire_time = 0, 58 | card_changeable = false 59 | }); 60 | } 61 | } 62 | 63 | [CqController("get_group_info")] 64 | public class CqControllerGetGroupInfo : CqControllerBase 65 | { 66 | public CqControllerGetGroupInfo(CqContext context) : base(context) 67 | { 68 | } 69 | 70 | public override JToken Process(JToken payload) 71 | { 72 | Task getChannelStateAsync = Context.KhHost.Bot.GetChannelState(long.Parse(payload["group_id"]?.ToObject()!)); 73 | getChannelStateAsync.Wait(); 74 | KhChannel channel = getChannelStateAsync.Result; 75 | 76 | return JToken.FromObject(new 77 | { 78 | group_id = channel.ChannelId, 79 | group_name = channel.ChannelName, 80 | member_count = int.MaxValue, 81 | max_member_count = int.MaxValue 82 | }); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Cq/Controllers/CqControllerSendMessage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Kaiheila.Events; 6 | using Kaiheila.OneBot.Storage; 7 | using Newtonsoft.Json.Linq; 8 | 9 | namespace Kaiheila.OneBot.Cq.Controllers 10 | { 11 | [CqController("send_private_msg")] 12 | public class CqControllerSendPrivateMessage : CqControllerBase 13 | { 14 | public CqControllerSendPrivateMessage(CqContext context) : base(context) 15 | { 16 | } 17 | 18 | public override JToken Process(JToken payload) 19 | { 20 | throw new System.NotImplementedException(); 21 | } 22 | } 23 | 24 | [CqController("send_group_msg")] 25 | public class CqControllerSendGroupMessage : CqControllerBase 26 | { 27 | public CqControllerSendGroupMessage(CqContext context) : base(context) 28 | { 29 | } 30 | 31 | public override JToken Process(JToken payload) 32 | { 33 | switch (Context.ConfigHelper.Config.KhConfig.KhSendingMode) 34 | { 35 | case KhSendingMode.Normal: 36 | long channel = long.Parse(payload["group_id"]?.ToObject()!); 37 | Context.KhHost.Bot.SendEvents( 38 | new List( 39 | Context.CqMessageHost.Parse(payload["message"]).CodeList 40 | .Select(x => 41 | { 42 | Task convertTask = x.ConvertToKhEvent( 43 | Context, 44 | channel); 45 | convertTask.Wait(); 46 | return convertTask.Result; 47 | })), 48 | new KhEventBase 49 | { 50 | ChannelId = channel 51 | }, 52 | Context.KhEventCombinerHost).Wait(); 53 | break; 54 | case KhSendingMode.Plain: 55 | Context.KhHost.Bot.SendTextMessage(long.Parse(payload["group_id"]?.ToObject()!), 56 | Context.CqMessageHost.Parse(payload["message"]).CodeList 57 | .Aggregate("", (s, b) => 58 | { 59 | Task taskString = b.ConvertToString(); 60 | taskString.Wait(); 61 | return s + taskString.Result; 62 | })).Wait(); 63 | break; 64 | default: 65 | throw new ArgumentOutOfRangeException(); 66 | } 67 | 68 | return JToken.FromObject(new 69 | { 70 | message_id = 0 71 | }); 72 | } 73 | } 74 | 75 | [CqController("send_msg")] 76 | public class CqControllerSendMessage : CqControllerBase 77 | { 78 | public CqControllerSendMessage(CqContext context) : base(context) 79 | { 80 | } 81 | 82 | public override JToken Process(JToken payload) 83 | { 84 | throw new System.NotImplementedException(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/Cq/Controllers/CqControllerStatus.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using Newtonsoft.Json.Linq; 4 | 5 | namespace Kaiheila.OneBot.Cq.Controllers 6 | { 7 | [CqController("get_status")] 8 | public class CqControllerGetStatus : CqControllerBase 9 | { 10 | public CqControllerGetStatus(CqContext context) : base(context) 11 | { 12 | } 13 | 14 | public override JToken Process(JToken payload) => 15 | JToken.FromObject(new 16 | { 17 | online = true, 18 | good = true 19 | }); 20 | } 21 | 22 | [CqController("get_version_info")] 23 | public class CqControllerGetVersionInfo : CqControllerBase 24 | { 25 | public CqControllerGetVersionInfo(CqContext context) : base(context) 26 | { 27 | } 28 | 29 | public override JToken Process(JToken payload) => 30 | JToken.FromObject(new 31 | { 32 | app_name = "kaiheila-cqhttp", 33 | app_version = Assembly.GetExecutingAssembly().GetName().Version?.ToString(), 34 | protocol_version = "v11", 35 | coolq_edition = "pro", 36 | coolq_directory = AppContext.BaseDirectory, 37 | plugin_version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() 38 | }); 39 | } 40 | 41 | [CqController("set_restart")] 42 | public class CqControllerSetRestart : CqControllerBase 43 | { 44 | public CqControllerSetRestart(CqContext context) : base(context) 45 | { 46 | } 47 | 48 | public override JToken Process(JToken payload) => JToken.FromObject(new{}); 49 | } 50 | 51 | [CqController("clean_cache")] 52 | public class CqControllerCleanCache : CqControllerBase 53 | { 54 | public CqControllerCleanCache(CqContext context) : base(context) 55 | { 56 | } 57 | 58 | public override JToken Process(JToken payload) => JToken.FromObject(new { }); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/Cq/CqContext.cs: -------------------------------------------------------------------------------- 1 | using System.Composition; 2 | using Kaiheila.Events.Combiners; 3 | using Kaiheila.OneBot.Cq.Message; 4 | using Kaiheila.OneBot.Kh; 5 | using Kaiheila.OneBot.Storage; 6 | 7 | namespace Kaiheila.OneBot.Cq 8 | { 9 | /// 10 | /// CQHTTP上下文。 11 | /// 12 | [Export] 13 | public class CqContext 14 | { 15 | /// 16 | /// 初始化CQHTTP上下文。 17 | /// 18 | /// Kaiheila主机。 19 | /// 提供访问应用配置能力的帮助类型。 20 | /// CQ消息主机。 21 | /// Kaiheila事件合并器主机。 22 | public CqContext( 23 | KhHost khHost, 24 | ConfigHelper configHelper, 25 | CqMessageHost cqMessageHost, 26 | KhEventCombinerHost khEventCombinerHost) 27 | { 28 | KhHost = khHost; 29 | ConfigHelper = configHelper; 30 | CqMessageHost = cqMessageHost; 31 | KhEventCombinerHost = khEventCombinerHost; 32 | } 33 | 34 | /// 35 | /// Kaiheila主机。 36 | /// 37 | public readonly KhHost KhHost; 38 | 39 | /// 40 | /// 提供访问应用配置能力的帮助类型。 41 | /// 42 | public readonly ConfigHelper ConfigHelper; 43 | 44 | /// 45 | /// CQ消息主机。 46 | /// 47 | public readonly CqMessageHost CqMessageHost; 48 | 49 | /// 50 | /// Kaiheila事件合并器主机。 51 | /// 52 | public readonly KhEventCombinerHost KhEventCombinerHost; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Cq/CqHost.cs: -------------------------------------------------------------------------------- 1 | using System.Composition; 2 | using Kaiheila.OneBot.Cq.Communication; 3 | using Kaiheila.OneBot.Storage; 4 | 5 | namespace Kaiheila.OneBot.Cq 6 | { 7 | /// 8 | /// CQHTTP主机,负责OneBot协议的接口监听和事件处理。 9 | /// 10 | [Export] 11 | public sealed class CqHost 12 | { 13 | /// 14 | /// 初始化CQHTTP主机。 15 | /// 16 | /// 提供访问应用配置能力的帮助类型。 17 | /// CQHTTP HTTP主机。 18 | /// CQHTTP WS主机。 19 | public CqHost( 20 | ConfigHelper configHelper, 21 | HttpHost httpHost, 22 | WsHost wsHost) 23 | { 24 | _configHelper = configHelper; 25 | 26 | _httpHost = httpHost; 27 | _wsHost = wsHost; 28 | 29 | if (configHelper.Config.CqConfig.CqHttpHostConfig.Enable) _httpHost.Run(); 30 | if (configHelper.Config.CqConfig.CqWsHostConfig.Enable) _wsHost.Run(); 31 | } 32 | 33 | #region Communication Hosts 34 | 35 | /// 36 | /// CQHTTP HTTP主机。 37 | /// 38 | private readonly HttpHost _httpHost; 39 | 40 | /// 41 | /// CQHTTP WS主机。 42 | /// 43 | private readonly WsHost _wsHost; 44 | 45 | #endregion 46 | 47 | /// 48 | /// 提供访问应用配置能力的帮助类型。 49 | /// 50 | private readonly ConfigHelper _configHelper; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/Cq/Database/CqAsset.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace Kaiheila.OneBot.Cq.Database 4 | { 5 | public class CqAsset 6 | { 7 | [Key] 8 | [Required] 9 | public string Url { get; set; } 10 | 11 | [Required] 12 | public string Name { get; set; } 13 | 14 | [Required] 15 | public string Path { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Cq/Database/CqDatabaseContext.cs: -------------------------------------------------------------------------------- 1 | using Kaiheila.OneBot.Storage; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace Kaiheila.OneBot.Cq.Database 5 | { 6 | public sealed class CqDatabaseContext : DbContext 7 | { 8 | public CqDatabaseContext() 9 | { 10 | } 11 | 12 | public CqDatabaseContext(DbContextOptions options) : base(options) 13 | { 14 | } 15 | 16 | protected override void OnConfiguring(DbContextOptionsBuilder options) 17 | { 18 | options.UseSqlite(ConnectionString); 19 | } 20 | 21 | public DbSet Assets { get; set; } 22 | 23 | public static readonly string ConnectionString = @$"Data Source={StorageHelper.GetRootFilePath("database.db")}"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Cq/Events/CqEventBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json.Linq; 3 | 4 | namespace Kaiheila.OneBot.Cq.Events 5 | { 6 | public abstract class CqEventBase 7 | { 8 | protected CqEventBase(CqContext context) 9 | { 10 | _context = context; 11 | } 12 | 13 | public JObject Result; 14 | 15 | /// 16 | /// CQHTTP上下文。 17 | /// 18 | protected readonly CqContext _context; 19 | } 20 | 21 | [AttributeUsage(AttributeTargets.Class, Inherited = false)] 22 | public sealed class CqEventAttribute : Attribute 23 | { 24 | public CqEventAttribute(Type type) => Type = type; 25 | 26 | public readonly Type Type; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Cq/Events/CqEventGroupMessage.cs: -------------------------------------------------------------------------------- 1 | using Kaiheila.Events; 2 | using Newtonsoft.Json.Linq; 3 | 4 | namespace Kaiheila.OneBot.Cq.Events 5 | { 6 | [CqEvent(typeof(KhEventTextMessage))] 7 | public class CqEventGroupMessage : CqEventBase 8 | { 9 | public CqEventGroupMessage(CqContext context, KhEventBase eventBase) : base(context) 10 | { 11 | if (!(eventBase is KhEventTextMessage eventMessage)) return; 12 | 13 | Result = _context.CreateEventObject(CqEventPostType.Message); 14 | Result["message_type"] = "group"; 15 | Result["sub_type"] = "normal"; 16 | Result["message_id"] = 0; 17 | Result["group_id"] = eventMessage.ChannelId; 18 | Result["user_id"] = eventMessage.User.Id; 19 | Result["anonymous"] = null; 20 | Result["message"] = eventMessage.Content; 21 | Result["raw_message"] = eventMessage.Content; 22 | Result["font"] = 0; 23 | Result["sender"] = JToken.FromObject(new 24 | { 25 | user_id = eventMessage.User.Id, 26 | nickname = eventMessage.User.Username, 27 | card = "", 28 | sex = "unknown", 29 | age = 18, 30 | area = "", 31 | level = "", 32 | role = "member", 33 | title = "" 34 | }); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Cq/Events/CqEventHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Newtonsoft.Json.Linq; 3 | 4 | namespace Kaiheila.OneBot.Cq.Events 5 | { 6 | public static class CqEventHelper 7 | { 8 | private const long InitialJavaScriptDateTicks = 621355968000000000; 9 | 10 | private static long ConvertDateToJsTicks(DateTime dateTime) 11 | { 12 | TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); 13 | long ret; 14 | if (dateTime.Kind == DateTimeKind.Utc || dateTime == DateTime.MaxValue || dateTime == DateTime.MinValue) 15 | ret = dateTime.Ticks; 16 | else 17 | { 18 | long num = dateTime.Ticks - offset.Ticks; 19 | if (num > 3155378975999999999L) 20 | ret = 3155378975999999999; 21 | else 22 | ret = num < 0L ? 0L : num; 23 | } 24 | 25 | return ((dateTime.Kind == DateTimeKind.Utc 26 | ? dateTime.Ticks 27 | : ret) - InitialJavaScriptDateTicks) / 10000L; 28 | } 29 | 30 | public static JObject CreateEventObject(this CqContext context, CqEventPostType type) => 31 | JObject.FromObject(new 32 | { 33 | time = ConvertDateToJsTicks(DateTime.UtcNow), 34 | self_id = context.KhHost.Bot.Self.Id, 35 | post_type = GetPostTypeString(type) 36 | }); 37 | 38 | public static string GetPostTypeString(CqEventPostType type) => 39 | type switch 40 | { 41 | CqEventPostType.Message => "message", 42 | CqEventPostType.Notice => "notice", 43 | CqEventPostType.Request => "request", 44 | CqEventPostType.MetaEvent => "meta_event", 45 | _ => throw new System.NotImplementedException() 46 | }; 47 | } 48 | 49 | public enum CqEventPostType 50 | { 51 | Message = 0, 52 | Notice = 1, 53 | Request = 2, 54 | MetaEvent = 3 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Cq/Handlers/CqActionHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Composition; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using Kaiheila.OneBot.Cq.Controllers; 11 | using Kaiheila.OneBot.Kh; 12 | using Kaiheila.OneBot.Storage; 13 | using Kaiheila.OneBot.Utils; 14 | using Microsoft.AspNetCore.Builder; 15 | using Microsoft.AspNetCore.Http; 16 | using Microsoft.Extensions.Logging; 17 | using Microsoft.Extensions.Options; 18 | using Newtonsoft.Json.Linq; 19 | 20 | namespace Kaiheila.OneBot.Cq.Handlers 21 | { 22 | /// 23 | /// CQHTTP任务处理器。 24 | /// 25 | [Export] 26 | public class CqActionHandler 27 | { 28 | /// 29 | /// 初始化CQHTTP任务处理器。 30 | /// 31 | /// Kaiheila主机。 32 | /// CQHTTP上下文。 33 | /// CQHTTP任务处理器日志记录器。 34 | /// 提供访问应用配置能力的帮助类型。 35 | public CqActionHandler( 36 | KhHost khHost, 37 | CqContext cqContext, 38 | ILogger logger, 39 | ConfigHelper configHelper) 40 | { 41 | _khHost = khHost; 42 | _cqContext = cqContext; 43 | _logger = logger; 44 | _configHelper = configHelper; 45 | 46 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => 47 | x.GetTypes() 48 | .Where(type => Attribute.GetCustomAttribute(type, typeof(CqControllerAttribute)) is not null))) 49 | { 50 | string action = (Attribute.GetCustomAttribute(type, typeof(CqControllerAttribute)) as CqControllerAttribute)?.Action; 51 | if (action == null || _controllers.ContainsKey(action) || type.FullName == null) continue; 52 | 53 | _controllers.Add(action, Activator.CreateInstance(type, _cqContext) as CqControllerBase); 54 | } 55 | 56 | _logger.LogInformation($"加载了{_controllers.Count}个CQHTTP任务控制器。"); 57 | } 58 | 59 | #region Process 60 | 61 | /// 62 | /// 执行任务。 63 | /// 64 | /// 要执行的任务。 65 | /// JSON报文。 66 | public JToken Process(string action, JToken payload) 67 | { 68 | if (action.EndsWith("_async")) 69 | { 70 | action = action.Replace("_async", ""); 71 | Task.Factory.StartNew(() => 72 | { 73 | try 74 | { 75 | if (!_controllers.TryGetValue(action, out CqControllerBase ctrl)) 76 | { 77 | // TODO: Log 78 | return; 79 | } 80 | 81 | ctrl.Process(payload); 82 | } 83 | catch (CqControllerException e) 84 | { 85 | // TODO: Log 86 | } 87 | }); 88 | 89 | return JToken.FromObject(new 90 | { 91 | status = "async", 92 | retcode = 1 93 | }); 94 | } 95 | 96 | if (!_controllers.TryGetValue(action, out CqControllerBase controller)) 97 | throw new HttpRequestException(null, null, HttpStatusCode.NotFound); 98 | 99 | try 100 | { 101 | return JToken.FromObject(new 102 | { 103 | status = "ok", 104 | retcode = 0, 105 | data = controller.Process(payload) 106 | }); 107 | } 108 | catch (CqControllerException e) 109 | { 110 | // TODO: Log 111 | 112 | return JToken.FromObject(new 113 | { 114 | status = "failed", 115 | retcode = e.RetCode 116 | }); 117 | } 118 | } 119 | 120 | #endregion 121 | 122 | #region Controllers 123 | 124 | /// 125 | /// CQHTTP任务控制器。 126 | /// 127 | private readonly Dictionary _controllers = new Dictionary(); 128 | 129 | #endregion 130 | 131 | /// 132 | /// CQHTTP上下文。 133 | /// 134 | private readonly CqContext _cqContext; 135 | 136 | /// 137 | /// Kaiheila主机。 138 | /// 139 | private readonly KhHost _khHost; 140 | 141 | /// 142 | /// CQHTTP任务处理器日志记录器。 143 | /// 144 | private readonly ILogger _logger; 145 | 146 | /// 147 | /// 提供访问应用配置能力的帮助类型。 148 | /// 149 | private readonly ConfigHelper _configHelper; 150 | } 151 | 152 | public class CqActionHandlerMiddleware 153 | { 154 | public CqActionHandlerMiddleware( 155 | RequestDelegate next, 156 | IOptions options) 157 | { 158 | _next = next; 159 | _options = options; 160 | } 161 | 162 | private RequestDelegate _next; 163 | private readonly IOptions _options; 164 | 165 | public async Task InvokeAsync(HttpContext context) 166 | { 167 | JObject payload; 168 | 169 | switch (context.Request.ContentType) 170 | { 171 | case "application/json": 172 | try 173 | { 174 | payload = JObject.Parse(await new StreamReader(context.Request.Body).ReadToEndAsync()); 175 | } 176 | catch (Exception) 177 | { 178 | context.Response.SetStatusCode(HttpStatusCode.BadRequest); 179 | return; 180 | } 181 | break; 182 | default: 183 | context.Response.SetStatusCode(HttpStatusCode.NotAcceptable); 184 | return; 185 | } 186 | 187 | if (string.IsNullOrEmpty(context.Request.Path.Value)) 188 | { 189 | context.Response.SetStatusCode(HttpStatusCode.BadRequest); 190 | return; 191 | } 192 | 193 | try 194 | { 195 | JToken token = _options.Value.Process(context.Request.Path.Value.Trim('/'), payload); 196 | context.Response.ContentType = "application/json"; 197 | await context.Response.WriteAsync(token.ToString()); 198 | } 199 | catch (HttpRequestException e) 200 | { 201 | if (e.StatusCode != null) context.Response.SetStatusCode((HttpStatusCode)e.StatusCode); 202 | } 203 | catch (Exception) 204 | { 205 | // Ignore 206 | } 207 | } 208 | } 209 | 210 | public static class CqActionHandlerExtensions 211 | { 212 | public static IApplicationBuilder UseCqActionHandler( 213 | this IApplicationBuilder builder, 214 | CqActionHandler cqActionHandler) 215 | { 216 | builder.UseMiddleware( 217 | Options.Create(cqActionHandler)); 218 | return builder; 219 | } 220 | } 221 | 222 | [Serializable] 223 | public class CqControllerException : Exception 224 | { 225 | public CqControllerException( 226 | int retCode = 100, 227 | string message = "", 228 | Exception inner = null) : base(message, inner) 229 | { 230 | RetCode = retCode; 231 | } 232 | 233 | public readonly int RetCode; 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/Cq/Handlers/CqEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Composition; 4 | using System.Linq; 5 | using System.Reactive.Linq; 6 | using System.Reactive.Subjects; 7 | using Kaiheila.Events; 8 | using Kaiheila.OneBot.Cq.Events; 9 | using Kaiheila.OneBot.Kh; 10 | using Kaiheila.OneBot.Storage; 11 | using Microsoft.Extensions.Logging; 12 | 13 | namespace Kaiheila.OneBot.Cq.Handlers 14 | { 15 | /// 16 | /// CQHTTP事件处理器。 17 | /// 18 | [Export] 19 | public class CqEventHandler 20 | { 21 | /// 22 | /// 初始化CQHTTP事件处理器。 23 | /// 24 | /// Kaiheila主机。 25 | /// CQHTTP上下文。 26 | /// CQHTTP事件处理器日志记录器。 27 | /// 提供访问应用配置能力的帮助类型。 28 | public CqEventHandler( 29 | KhHost khHost, 30 | CqContext cqContext, 31 | ILogger logger, 32 | ConfigHelper configHelper) 33 | { 34 | _khHost = khHost; 35 | _cqContext = cqContext; 36 | _logger = logger; 37 | _configHelper = configHelper; 38 | 39 | _logger.LogInformation("初始化CQHTTP事件处理器。"); 40 | 41 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => 42 | x.GetTypes() 43 | .Where(type => Attribute.GetCustomAttribute(type, typeof(CqEventAttribute)) is not null))) 44 | { 45 | Type khEventType = (Attribute.GetCustomAttribute(type, typeof(CqEventAttribute)) as CqEventAttribute)?.Type; 46 | if (khEventType == null || _eventTypes.ContainsKey(khEventType) || type.FullName == null) continue; 47 | 48 | _eventTypes.Add(khEventType, type); 49 | } 50 | 51 | khHost.Bot.Event.Select(Process).Subscribe(Event); 52 | 53 | _logger.LogInformation($"加载了{_eventTypes.Count}个CQHTTP事件类型。"); 54 | } 55 | 56 | #region Event 57 | 58 | private CqEventBase Process(KhEventBase khEvent) 59 | { 60 | if (!_eventTypes.TryGetValue(khEvent.GetType(), out Type eventType)) 61 | return null; 62 | 63 | CqEventBase cqEvent = Activator.CreateInstance(eventType, _cqContext, khEvent) as CqEventBase; 64 | return cqEvent; 65 | } 66 | 67 | public Subject Event = new Subject(); 68 | 69 | #endregion 70 | 71 | #region Event Types 72 | 73 | private readonly Dictionary _eventTypes = new Dictionary(); 74 | 75 | #endregion 76 | 77 | /// 78 | /// Kaiheila主机。 79 | /// 80 | private readonly KhHost _khHost; 81 | 82 | /// 83 | /// CQHTTP上下文。 84 | /// 85 | private readonly CqContext _cqContext; 86 | 87 | /// 88 | /// CQHTTP事件处理器日志记录器。 89 | /// 90 | private readonly ILogger _logger; 91 | 92 | /// 93 | /// 提供访问应用配置能力的帮助类型。 94 | /// 95 | private readonly ConfigHelper _configHelper; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Cq/Message/CqMessage.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Kaiheila.OneBot.Cq.Codes; 3 | 4 | namespace Kaiheila.OneBot.Cq.Message 5 | { 6 | public class CqMessage 7 | { 8 | #region Data 9 | 10 | public List CodeList = new List(); 11 | 12 | #endregion 13 | 14 | internal CqMessage() 15 | { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Cq/Message/CqMessageHost.cs: -------------------------------------------------------------------------------- 1 | using System.Composition; 2 | using System.Text.RegularExpressions; 3 | using Kaiheila.OneBot.Cq.Codes; 4 | using Newtonsoft.Json; 5 | using Newtonsoft.Json.Linq; 6 | 7 | namespace Kaiheila.OneBot.Cq.Message 8 | { 9 | /// 10 | /// CQ消息主机。 11 | /// 12 | [Export] 13 | public class CqMessageHost 14 | { 15 | /// 16 | /// 初始化CQ消息主机。 17 | /// 18 | /// CQ码主机。 19 | public CqMessageHost( 20 | CqCodeHost cqCodeHost) 21 | { 22 | _cqCodeHost = cqCodeHost; 23 | } 24 | 25 | #region Parser 26 | 27 | public CqMessage Parse(string raw) 28 | { 29 | CqMessage message = new CqMessage(); 30 | 31 | Match match = CqCodeHost.ExtractRegex.Match(raw); 32 | while (match.Success) 33 | { 34 | if (match.Index > 0) message.CodeList.Add(new CqCodeText(raw.Substring(0, match.Index))); 35 | 36 | message.CodeList.Add(_cqCodeHost.Parse(match.Value)); 37 | raw = raw.Substring(match.Index + match.Length); 38 | match = CqCodeHost.ExtractRegex.Match(raw); 39 | } 40 | 41 | if (raw.Length != 0) message.CodeList.Add(new CqCodeText(raw)); 42 | 43 | return message; 44 | } 45 | 46 | public CqMessage Parse(JToken token) 47 | { 48 | switch (token.Type) 49 | { 50 | case JTokenType.String: 51 | return Parse(token.ToObject()); 52 | case JTokenType.Array: 53 | CqMessage message = new CqMessage(); 54 | foreach (JToken cqCodeToken in token) message.CodeList.Add(_cqCodeHost.Parse(cqCodeToken)); 55 | return message; 56 | default: 57 | throw new JsonReaderException("不支持的CQ消息。消息必须是字符串或数组格式。"); 58 | } 59 | } 60 | 61 | #endregion 62 | 63 | private CqCodeHost _cqCodeHost; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Kh/KhHost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Composition; 3 | using Kaiheila.Client; 4 | using Kaiheila.OneBot.Storage; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace Kaiheila.OneBot.Kh 8 | { 9 | /// 10 | /// Kaiheila主机。 11 | /// 12 | [Export] 13 | public class KhHost : IDisposable 14 | { 15 | #region Constructor 16 | 17 | /// 18 | /// 初始化Kaiheila主机。 19 | /// 20 | /// Kaiheila主机日志记录器。 21 | /// 提供访问应用配置能力的帮助类型。 22 | public KhHost( 23 | ILogger logger, 24 | ConfigHelper configHelper) 25 | { 26 | _logger = logger; 27 | _configHelper = configHelper; 28 | 29 | _logger.LogInformation( 30 | $"使用{_configHelper.Config.KhConfig.KhClientMode}的Bot提供程序初始化Kaiheila主机。"); 31 | 32 | switch (_configHelper.Config.KhConfig.KhClientMode) 33 | { 34 | case KhClientMode.WebHook: 35 | throw new NotImplementedException(); 36 | case KhClientMode.WebSocket: 37 | throw new NotImplementedException(); 38 | case KhClientMode.V2: 39 | Bot = new ZeroClient(); 40 | break; 41 | default: 42 | throw new ArgumentOutOfRangeException(); 43 | } 44 | } 45 | 46 | #endregion 47 | 48 | #region Lifecycle 49 | 50 | public void Dispose() 51 | { 52 | Bot?.Dispose(); 53 | } 54 | 55 | #endregion 56 | 57 | #region Bot 58 | 59 | /// 60 | /// Kaiheila机器人。 61 | /// 62 | public readonly BotBase Bot; 63 | 64 | #endregion 65 | 66 | /// 67 | /// Kaiheila主机日志记录器。 68 | /// 69 | private readonly ILogger _logger; 70 | 71 | /// 72 | /// 提供访问应用配置能力的帮助类型。 73 | /// 74 | private readonly ConfigHelper _configHelper; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Composition; 3 | using System.Linq; 4 | using System.Reflection; 5 | using Kaiheila.OneBot.Utils; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | using Microsoft.Extensions.Logging.Console; 10 | 11 | namespace Kaiheila.OneBot 12 | { 13 | /// 14 | /// 应用程序的入口点。 15 | /// 16 | public static class Program 17 | { 18 | /// 19 | /// 应用程序的入口点。 20 | /// 21 | /// 应用程序初始化命令参数。 22 | public static void Main(string[] args) 23 | { 24 | IHost host = CreateHostBuilder(args).Build(); 25 | _ = host.Services.GetService(); 26 | host.Run(); 27 | } 28 | 29 | /// 30 | /// 创建泛型主机构建器。 31 | /// 32 | /// 应用程序初始化命令参数。 33 | /// 泛型主机构建器。 34 | private static IHostBuilder CreateHostBuilder(string[] args) => 35 | Host.CreateDefaultBuilder(args) 36 | .ConfigureServices((context, services) => 37 | { 38 | // Register Services 39 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies() 40 | .Concat(Assembly.GetExecutingAssembly().GetReferencedAssemblies() 41 | .Select(Assembly.Load)) 42 | .SelectMany(x => 43 | x.GetTypes() 44 | .Where(type => 45 | Attribute.GetCustomAttribute(type, typeof(ExportAttribute)) is not null))) 46 | services.AddSingleton(type); 47 | 48 | // Register Database Service 49 | //services.AddDbContextPool(CreateCqDatabaseContextPool, 64); 50 | }) 51 | .ConfigureLogging(builder => builder 52 | .AddDebug() 53 | .AddSimpleConsole(options => 54 | { 55 | options.ColorBehavior = LoggerColorBehavior.Enabled; 56 | options.SingleLine = true; 57 | options.IncludeScopes = true; 58 | }) 59 | .AddSystemdConsole()); 60 | 61 | //private static void CreateCqDatabaseContextPool(DbContextOptionsBuilder options) => 62 | // options.UseSqlite(CqDatabaseContext.ConnectionString); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Resources/config.json: -------------------------------------------------------------------------------- 1 | /*! 2 | * kaiheila-onebot 配置文件 3 | * 版本 1.0 4 | * 随附于 kaiheila-onebot >= v0.1.0 5 | * 6 | * 可在 7 | * https://github.com/kaiheila-community/kaiheila-onebot 8 | * 找到文档的帮助。 9 | * 10 | * 配置文件内允许使用注释,总是在对象成员后跟随逗号以及不带双引号的键名。 11 | * 12 | * 注意:不推荐移除任何配置项,因为在版本升级时kaiheila-onebot的默认行为总是有可能发生改变。 13 | * 14 | * 注意:随着kaiheila-onebot的版本迭代,此配置文件中可能会有更多的配置项加入进来。 15 | * 你随时可以在 16 | * https://github.com/kaiheila-community/kaiheila-onebot/blob/master/src/Resources/config.json 17 | * 处找到最新的默认配置文件。 18 | * 19 | * 注意:当默认配置文件版本号的MajorVersion发生改变时,即表明 20 | * 此配置文件版本之前的所有配置文件都不能再与更新版本的kaiheila-onebot兼容。 21 | * 你可能需要进行手动迁移。 22 | */ 23 | { 24 | /* 25 | * 指定兼容性模式。 26 | * 27 | * 兼容性模式等级说明: 28 | * 29 | * 0 - Off 30 | * 31 | * 指定严格模式关闭会使kaiheila-onebot捕获并处理任何OneBot主机抛出的异常。 32 | * 这种模式下,使用任何不正确的请求载荷都不会使kaiheila-onebot出现异常。 33 | * 34 | * 如果你在向kaiheila-onebot接入第三方的OneBot客户端框架,你可以使用这个模式。 35 | * 36 | * ********** 37 | * 38 | * 20 - OneBot 39 | * 40 | * 指定OneBot兼容模式会使kaiheila-onebot尝试处理任何OneBot协议中指定的 41 | * API和CQ码,即使他们不被Kaiheila主机所支持。 42 | * 通常情况下,不被支持的操作将会尝试使用Plain模式发送 43 | * (参见「消息发送模式」)。 44 | * 45 | * 如果你在向kaiheila-onebot接入严格支持OneBot协议的 46 | * 第三方的OneBot客户端框架或自己编写的OneBot客户端程序, 47 | * 我们推荐你使用这个模式。 48 | * 49 | * ********** 50 | * 51 | * 30 - Strict 52 | * 53 | * 启用严格模式将会导致任何kaiheila-onebot不支持的内容均抛出异常, 54 | * 这些内容可以是不支持的CqCode或HTTP API路由。 55 | * 56 | * 如果你面向kaiheila-onebot进行开发,我们建议你使用严格模式。 57 | */ 58 | "compatibility_mode": 0, 59 | 60 | "kaiheila": { 61 | /* 62 | * 指定Kaiheila客户端模式。 63 | * 64 | * 客户端模式等级说明: 65 | * 66 | * 0 - WebHook 67 | * 68 | * 使用APIv3通过WebHook方式连接服务器。 69 | * 70 | * 这是Kaiheila官方推荐的连接模式。 71 | * 72 | * ********** 73 | * 74 | * 1 - WebSocket 75 | * 76 | * 使用APIv3通过WebSocket方式连接服务器。 77 | * 78 | * 请注意,WebSocket模式下的并发性能可能不如WebHook。 79 | * 80 | * ********** 81 | * 82 | * 10 - V2 83 | * 84 | * 使用V2Client连接服务器。 85 | * 86 | * 这种方法可以使机器人模拟用户登录。不推荐使用。 87 | */ 88 | "mode": 10, 89 | 90 | /* 91 | * 指定Kaiheila消息发送模式。 92 | * 93 | * 消息发送模式等级说明: 94 | * 95 | * 0 - Normal 96 | * 97 | * 消息通过调用对应的API进行发送。 98 | * 99 | * 这是推荐的消息发送模式。 100 | * 101 | * ********** 102 | * 103 | * 10 - Plain 104 | * 105 | * 所有消息都在转换为纯文本之后发送。 106 | * 107 | * 某些特殊情况下,你可以选择启用这个模式。 108 | * Kaiheila客户端仍然可以解析部分图片链接。 109 | */ 110 | "sending_mode": 0, 111 | 112 | /* 113 | * Kaiheila V2客户端配置。 114 | */ 115 | "v2": { 116 | /* 117 | * WS客户端连接的IP。 118 | */ 119 | "host": "127.0.0.1", 120 | 121 | /* 122 | * WS客户端连接的端口。 123 | */ 124 | "port": "7700", 125 | }, 126 | 127 | /* 128 | * Kaiheila鉴权配置。 129 | */ 130 | "auth": { 131 | /* 132 | * Kaiheila鉴权使用的Cookie中的auth字段。 133 | */ 134 | "cookie_auth": "", 135 | }, 136 | }, 137 | 138 | /* 139 | * OneBot配置。 140 | * 141 | * 使用此节点配置kaiheila-onebot与你的Bot服务进行连接的相关配置。 142 | * 143 | * 我们最为推荐的通信方式是ws(WebSocket),但是你可以根据自己的实际情况 144 | * 选择最为适合的通信方式。 145 | */ 146 | "onebot": { 147 | "http": { 148 | /* 149 | * 是否启用HTTP。 150 | * 151 | * 虽然我们推荐使用ws进行通信,但默认的配置文件会与onebot的默认配置保持一致。 152 | * 默认情况下,只有HTTP通信会开启。 153 | */ 154 | "enable": true, 155 | 156 | /* 157 | * HTTP服务器监听的IP。 158 | * 159 | * 使用"0.0.0.0"监听任何IP, 160 | * 使用"127.0.0.1"监听本机环回。 161 | */ 162 | "host": "0.0.0.0", 163 | 164 | "port": "5700", // HTTP服务器监听的端口。 165 | }, 166 | 167 | /* 168 | * OneBot HTTP POST配置。 169 | */ 170 | "http_post": { 171 | /* 172 | * HTTP POST事件上报 URL。 173 | * 174 | * 键为Url,值为对应Url的Secret。 175 | */ 176 | "urls": { 177 | // "http://127.0.0.1:5701": "secret", 178 | }, 179 | 180 | /* 181 | * 以秒为单位的HTTP POST超时时间。 182 | * 183 | * 0表示不设置超时。 184 | */ 185 | "timeout": 0, 186 | }, 187 | 188 | /* 189 | * OneBot WS配置。 190 | * 191 | * 这是我们推荐的通信方式。 192 | */ 193 | "ws": { 194 | /* 195 | * 是否启用WS。 196 | */ 197 | "enable": false, 198 | 199 | /* 200 | * WS服务器监听的IP。 201 | * 202 | * 使用"0.0.0.0"监听任何IP, 203 | * 使用"127.0.0.1"监听本机环回。 204 | */ 205 | "host": "0.0.0.0", 206 | 207 | "port": "6700", // WS服务器监听的端口。 208 | }, 209 | 210 | /* 211 | * OneBot WS Reverse配置。 212 | */ 213 | "ws_reverse": { 214 | /* 215 | * 是否启用WS Reverse。 216 | */ 217 | "enable": false, 218 | }, 219 | 220 | /* 221 | * OneBot 鉴权配置。 222 | */ 223 | "auth": { 224 | /* 225 | * OneBot 鉴权Access Token。 226 | */ 227 | "access_token": "", 228 | }, 229 | }, 230 | } 231 | -------------------------------------------------------------------------------- /src/Resources/create_db.sql: -------------------------------------------------------------------------------- 1 | BEGIN TRANSACTION; 2 | 3 | CREATE TABLE "Assets" ( 4 | "Url" TEXT NOT NULL CONSTRAINT "PK_Assets" PRIMARY KEY, 5 | "Name" TEXT NOT NULL, 6 | "Path" TEXT NOT NULL 7 | ); 8 | 9 | COMMIT; 10 | -------------------------------------------------------------------------------- /src/Storage/Config.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Newtonsoft.Json; 3 | 4 | namespace Kaiheila.OneBot.Storage 5 | { 6 | /// 7 | /// 应用配置。 8 | /// 9 | [JsonObject(MemberSerialization.OptIn)] 10 | public class Config 11 | { 12 | /// 13 | /// 指定兼容性模式。 14 | /// 15 | [JsonProperty("compatibility_mode")] 16 | public CompatibilityMode CompatibilityMode { get; set; } = CompatibilityMode.Off; 17 | 18 | /// 19 | /// Kaiheila配置。 20 | /// 21 | [JsonProperty("kaiheila")] 22 | public KhConfig KhConfig { get; set; } = new KhConfig(); 23 | 24 | /// 25 | /// OneBot配置。 26 | /// 27 | [JsonProperty("onebot")] 28 | public CqConfig CqConfig { get; set; } = new CqConfig(); 29 | } 30 | 31 | /// 32 | /// 兼容性模式。 33 | /// 34 | public enum CompatibilityMode 35 | { 36 | Off = 0, 37 | OneBot = 20, 38 | Strict = 30 39 | } 40 | 41 | /// 42 | /// Kaiheila配置。 43 | /// 44 | [JsonObject(MemberSerialization.OptIn)] 45 | public class KhConfig 46 | { 47 | /// 48 | /// 指定Kaiheila客户端模式。 49 | /// 50 | [JsonProperty("mode")] 51 | public KhClientMode KhClientMode { get; set; } = KhClientMode.WebHook; 52 | 53 | /// 54 | /// 指定Kaiheila消息发送模式。 55 | /// 56 | [JsonProperty("sending_mode")] 57 | public KhSendingMode KhSendingMode { get; set; } = KhSendingMode.Normal; 58 | 59 | /// 60 | /// Kaiheila V2客户端配置。 61 | /// 62 | [JsonProperty("v2")] 63 | public KhClientV2Config KhClientV2Config { get; set; } = new KhClientV2Config(); 64 | 65 | /// 66 | /// Kaiheila鉴权配置。 67 | /// 68 | [JsonProperty("auth")] 69 | public KhAuthConfig KhAuthConfig { get; set; } = new KhAuthConfig(); 70 | } 71 | 72 | /// 73 | /// Kaiheila客户端模式。 74 | /// 75 | public enum KhClientMode 76 | { 77 | WebHook = 0, 78 | WebSocket = 1, 79 | V2 = 10 80 | } 81 | 82 | /// 83 | /// Kaiheila消息发送模式。 84 | /// 85 | public enum KhSendingMode 86 | { 87 | Normal = 0, 88 | Plain = 10 89 | } 90 | 91 | /// 92 | /// Kaiheila V2客户端配置。 93 | /// 94 | [JsonObject(MemberSerialization.OptIn)] 95 | public class KhClientV2Config 96 | { 97 | /// 98 | /// WS客户端连接的IP。 99 | /// 100 | [JsonProperty("host")] 101 | public string Host { get; set; } = "127.0.0.1"; 102 | 103 | /// 104 | /// WS客户端连接的端口。 105 | /// 106 | [JsonProperty("port")] 107 | public int Port { get; set; } = 7700; 108 | } 109 | 110 | /// 111 | /// Kaiheila鉴权配置。 112 | /// 113 | [JsonObject(MemberSerialization.OptIn)] 114 | public class KhAuthConfig 115 | { 116 | /// 117 | /// Kaiheila鉴权使用的Cookie中的auth字段。 118 | /// 119 | [JsonProperty("cookie_auth")] 120 | public string CookieAuth { get; set; } = ""; 121 | } 122 | 123 | /// 124 | /// OneBot配置。 125 | /// 126 | [JsonObject(MemberSerialization.OptIn)] 127 | public class CqConfig 128 | { 129 | /// 130 | /// OneBot HTTP主机配置。 131 | /// 132 | [JsonProperty("http")] 133 | public CqHttpHostConfig CqHttpHostConfig { get; set; } = new CqHttpHostConfig(); 134 | 135 | /// 136 | /// OneBot HTTP POST主机配置。 137 | /// 138 | [JsonProperty("http_post")] 139 | public CqHttpPostHostConfig CqHttpPostHostConfig { get; set; } = new CqHttpPostHostConfig(); 140 | 141 | /// 142 | /// OneBot WS主机配置。 143 | /// 144 | [JsonProperty("ws")] 145 | public CqWsHostConfig CqWsHostConfig { get; set; } = new CqWsHostConfig(); 146 | 147 | /// 148 | /// OneBot WS Reverse主机配置。 149 | /// 150 | [JsonProperty("ws_reverse")] 151 | public CqWsReverseHostConfig CqWsReverseHostConfig { get; set; } = new CqWsReverseHostConfig(); 152 | 153 | /// 154 | /// OneBot 鉴权配置。 155 | /// 156 | [JsonProperty("auth")] 157 | public CqAuthConfig CqAuthConfig { get; set; } = new CqAuthConfig(); 158 | } 159 | 160 | /// 161 | /// OneBot HTTP主机配置。 162 | /// 163 | [JsonObject(MemberSerialization.OptIn)] 164 | public class CqHttpHostConfig 165 | { 166 | /// 167 | /// 是否启用HTTP。 168 | /// 169 | [JsonProperty("enable")] 170 | public bool Enable { get; set; } = true; 171 | 172 | /// 173 | /// HTTP服务器监听的IP。 174 | /// 175 | [JsonProperty("host")] 176 | public string Host { get; set; } = "0.0.0.0"; 177 | 178 | /// 179 | /// HTTP服务器监听的端口。 180 | /// 181 | [JsonProperty("port")] 182 | public int Port { get; set; } = 5700; 183 | } 184 | 185 | /// 186 | /// OneBot HTTP POST主机配置。 187 | /// 188 | [JsonObject(MemberSerialization.OptIn)] 189 | public class CqHttpPostHostConfig 190 | { 191 | /// 192 | /// HTTP POST事件上报 URL。 193 | /// 194 | /// 195 | /// 键为Url,值为对应Url的Secret。 196 | /// 197 | [JsonProperty("urls")] 198 | public Dictionary UrlList { get; set; } = new Dictionary(); 199 | 200 | /// 201 | /// 以秒为单位的HTTP POST超时时间。 202 | /// 203 | /// 204 | /// 0表示不设置超时。 205 | /// 206 | [JsonProperty("timeout")] 207 | public int Timeout { get; set; } 208 | } 209 | 210 | /// 211 | /// OneBot WS主机配置。 212 | /// 213 | [JsonObject(MemberSerialization.OptIn)] 214 | public class CqWsHostConfig 215 | { 216 | /// 217 | /// 是否启用WS。 218 | /// 219 | [JsonProperty("enable")] 220 | public bool Enable { get; set; } 221 | 222 | /// 223 | /// WS服务器监听的IP。 224 | /// 225 | [JsonProperty("host")] 226 | public string Host { get; set; } = "0.0.0.0"; 227 | 228 | /// 229 | /// WS服务器监听的端口。 230 | /// 231 | [JsonProperty("port")] 232 | public int Port { get; set; } = 6700; 233 | } 234 | 235 | /// 236 | /// OneBot WS Reverse主机配置。 237 | /// 238 | [JsonObject(MemberSerialization.OptIn)] 239 | public class CqWsReverseHostConfig 240 | { 241 | /// 242 | /// 是否启用WS Reverse。 243 | /// 244 | [JsonProperty("enable")] 245 | public bool Enable { get; set; } 246 | } 247 | 248 | /// 249 | /// OneBot鉴权配置。 250 | /// 251 | public class CqAuthConfig 252 | { 253 | /// 254 | /// OneBot 鉴权Access Token。 255 | /// 256 | [JsonProperty("access_token")] 257 | public string AccessToken { get; set; } = ""; 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /src/Storage/ConfigHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Composition; 3 | using System.IO; 4 | using System.Reflection; 5 | using Kaiheila.OneBot.Cq.Database; 6 | using Microsoft.Data.Sqlite; 7 | using Microsoft.Extensions.Logging; 8 | using Newtonsoft.Json; 9 | 10 | namespace Kaiheila.OneBot.Storage 11 | { 12 | /// 13 | /// 提供访问应用配置能力的帮助类型。 14 | /// 15 | [Export] 16 | public sealed class ConfigHelper 17 | { 18 | /// 19 | /// 初始化应用配置。 20 | /// 21 | /// 配置日志记录器。 22 | public ConfigHelper(ILogger logger) 23 | { 24 | _logger = logger; 25 | _logger.LogInformation("开始加载配置。"); 26 | 27 | ReloadConfig(); 28 | } 29 | 30 | /// 31 | /// 重载应用配置。 32 | /// 33 | public void ReloadConfig() 34 | { 35 | ConfigFilePath = StorageHelper.GetRootFilePath("config.json"); 36 | var databaseFilePath = StorageHelper.GetRootFilePath("database.db"); 37 | 38 | if (!File.Exists(ConfigFilePath)) 39 | { 40 | Console.WriteLine(Figgle.FiggleFonts.Standard.Render("Kaiheila.OneBot")); 41 | 42 | _logger.LogInformation("没有找到配置文件。"); 43 | 44 | Stream configFileStream = File.OpenWrite(ConfigFilePath); 45 | Stream configResourceStream = Assembly.GetExecutingAssembly() 46 | .GetManifestResourceStream("Kaiheila.OneBot.Resources.config.json"); 47 | 48 | if (configResourceStream is null) 49 | throw new ArgumentNullException(nameof(configResourceStream)); 50 | 51 | configResourceStream.CopyTo(configFileStream); 52 | 53 | if (!File.Exists(databaseFilePath)) 54 | { 55 | using Stream databaseResourceStream = Assembly.GetExecutingAssembly() 56 | .GetManifestResourceStream("Kaiheila.OneBot.Resources.create_db.sql"); 57 | 58 | if (databaseResourceStream is null) 59 | throw new ArgumentNullException(nameof(databaseResourceStream)); 60 | 61 | using StreamReader dbScriptReader = new StreamReader(databaseResourceStream); 62 | string createDatabaseScript = dbScriptReader.ReadToEnd(); 63 | 64 | using SqliteConnection connection = new SqliteConnection(CqDatabaseContext.ConnectionString); 65 | connection.Open(); 66 | 67 | using var command = connection.CreateCommand(); 68 | command.CommandText = createDatabaseScript; 69 | 70 | command.ExecuteNonQuery(); 71 | } 72 | 73 | configFileStream.Close(); 74 | configResourceStream.Close(); 75 | 76 | _logger.LogInformation("已经生成了默认的配置文件。修改配置,然后重启应用。"); 77 | 78 | Console.ReadKey(); 79 | Environment.Exit(1); 80 | } 81 | 82 | try 83 | { 84 | Config = JsonConvert.DeserializeObject(File.ReadAllText(ConfigFilePath)) ?? new Config(); 85 | } 86 | catch (Exception exception) 87 | { 88 | _logger.LogCritical(exception, "加载配置文件时发生了错误。"); 89 | 90 | Console.ReadKey(); 91 | Environment.Exit(1); 92 | } 93 | } 94 | 95 | /// 96 | /// 配置日志记录器。 97 | /// 98 | private readonly ILogger _logger; 99 | 100 | /// 101 | /// 配置文件的完整路径。 102 | /// 103 | public string ConfigFilePath; 104 | 105 | /// 106 | /// 应用配置。 107 | /// 108 | public Config Config; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/Storage/StorageHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace Kaiheila.OneBot.Storage 5 | { 6 | /// 7 | /// 提供访问应用存储能力的帮助类型。 8 | /// 9 | public static class StorageHelper 10 | { 11 | /// 12 | /// 从存储根目录中获取文件。 13 | /// 14 | /// 要获取的文件的文件名。 15 | /// 文件的完整路径。 16 | public static string GetRootFilePath(string filename) => Path.Combine(GetRootPath(), filename); 17 | 18 | /// 19 | /// 从存储根目录中获取分类文件夹。 20 | /// 21 | /// 分类的名称。 22 | /// 文件夹的完整路径。 23 | public static string GetSectionFolderPath(string sectionName) 24 | { 25 | string folderPath = Path.Combine(GetRootPath(), $"{sectionName}/"); 26 | Directory.CreateDirectory(folderPath); 27 | return folderPath; 28 | } 29 | 30 | /// 31 | /// 从分类存储目录中获取文件。 32 | /// 33 | /// 分类的名称。 34 | /// 要获取的文件的文件名。 35 | /// 文件的完整路径。 36 | public static string GetSectionFilePath(string sectionName, string filename) => 37 | Path.Combine(GetSectionFolderPath(sectionName), filename); 38 | 39 | /// 40 | /// 从存储目录中获取图片文件夹。 41 | /// 42 | /// 文件夹的完整路径。 43 | public static string GetImagesFolderPath() => 44 | GetSectionFolderPath("images"); 45 | 46 | /// 47 | /// 从存储目录中获取临时文件夹。 48 | /// 49 | /// 文件夹的完整路径。 50 | public static string GetTempFolderPath() => 51 | GetSectionFolderPath("temp"); 52 | 53 | /// 54 | /// 从存储目录中获取临时文件。 55 | /// 56 | /// 要获取的文件的文件名。 57 | /// 文件的完整路径。 58 | public static string GetTempFilePath(string file) => 59 | Path.Combine(GetTempFolderPath(), file); 60 | 61 | /// 62 | /// 获取存储根目录的路径。 63 | /// 64 | /// 存储根目录的路径。 65 | private static string GetRootPath() 66 | { 67 | string rootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "storage/"); 68 | Directory.CreateDirectory(rootPath); 69 | return rootPath; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Utils/CommunicationHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Microsoft.AspNetCore.Http; 3 | 4 | namespace Kaiheila.OneBot.Utils 5 | { 6 | public static class CommunicationHelper 7 | { 8 | public static void SetStatusCode(this HttpResponse httpResponse, HttpStatusCode httpStatusCode) => 9 | httpResponse.StatusCode = (int)httpStatusCode; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Utils/LifecycleHost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Composition; 3 | using Kaiheila.OneBot.Cq; 4 | using Microsoft.Extensions.Logging; 5 | 6 | namespace Kaiheila.OneBot.Utils 7 | { 8 | /// 9 | /// 生命周期主机。 10 | /// 11 | [Export] 12 | public sealed class LifecycleHost 13 | { 14 | /// 15 | /// 初始化生命周期主机。 16 | /// 17 | /// CQHTTP主机。 18 | /// 生命周期主机日志记录器。 19 | public LifecycleHost( 20 | CqHost cqHost, 21 | ILogger logger) 22 | { 23 | _logger = logger; 24 | 25 | AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => 26 | _logger.LogCritical( 27 | eventArgs.ExceptionObject as Exception, 28 | "出现异常。这个异常是由kaiheila-cqhttp引起的。"); 29 | 30 | _cqHost = cqHost; 31 | } 32 | 33 | /// 34 | /// CQHTTP主机。 35 | /// 36 | private readonly CqHost _cqHost; 37 | 38 | /// 39 | /// 生命周期主机日志记录器。 40 | /// 41 | private readonly ILogger _logger; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/kaiheila-onebot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | Kaiheila.OneBot 7 | Kaiheila.OneBot 8 | Il Harper 9 | Kaiheila.OneBot 10 | OneBot(原CQHTTP)的开黑啦(kaiheila)平台实现。 11 | MIT 12 | 2020 Il Harper 13 | https://github.com/kaiheila-community/kaiheila-onebot 14 | https://github.com/kaiheila-community/kaiheila-onebot 15 | git 16 | kaiheila,onebot,cqhttp 17 | 0.0.1 18 | kaiheila.png 19 | 20 | 21 | 22 | 23 | 24 | 25 | True 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | all 45 | runtime; build; native; contentfiles; analyzers; buildtransitive 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /test/Cq/Code/CqCodes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Kaiheila.OneBot.Cq.Codes; 4 | using Xunit; 5 | 6 | namespace Kaiheila.OneBot.Test.Cq.Code 7 | { 8 | public class CqCodes 9 | { 10 | [Fact] 11 | public static void CqCodeTypesBasedOnCqCode() 12 | { 13 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => 14 | x.GetTypes() 15 | .Where(type => Attribute.GetCustomAttribute(type, typeof(CqCodeAttribute)) is not null))) 16 | Assert.Equal(typeof(CqCodeBase), type.BaseType); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/Cq/Controllers/CqControllers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Kaiheila.OneBot.Cq.Controllers; 4 | using Xunit; 5 | 6 | namespace Kaiheila.OneBot.Test.Cq.Controllers 7 | { 8 | public class CqControllers 9 | { 10 | [Fact] 11 | public static void CqControllerBasedOnCqControllerBase() 12 | { 13 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => 14 | x.GetTypes() 15 | .Where(type => Attribute.GetCustomAttribute(type, typeof(CqControllerAttribute)) is not null))) 16 | Assert.Equal(typeof(CqControllerBase), type.BaseType); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/Cq/Events/CqEvents.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using Kaiheila.OneBot.Cq.Events; 4 | using Xunit; 5 | 6 | namespace Kaiheila.OneBot.Test.Cq.Events 7 | { 8 | public static class CqEvents 9 | { 10 | [Fact] 11 | public static void CqEventBasedOnCqEventBase() 12 | { 13 | foreach (Type type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => 14 | x.GetTypes() 15 | .Where(type => Attribute.GetCustomAttribute(type, typeof(CqEventAttribute)) is not null))) 16 | Assert.Equal(typeof(CqEventBase), type.BaseType); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/Cq/Message/CqMessages.cs: -------------------------------------------------------------------------------- 1 | using Kaiheila.OneBot.Cq.Codes; 2 | using Kaiheila.OneBot.Cq.Message; 3 | using Microsoft.Extensions.Logging; 4 | using Microsoft.Extensions.Logging.Abstractions; 5 | using Newtonsoft.Json.Linq; 6 | using Xunit; 7 | 8 | namespace Kaiheila.OneBot.Test.Cq.Message 9 | { 10 | public class CqMessages 11 | { 12 | #region Data 13 | 14 | private const string StringToken = "[CQ:face,id=178]看看我刚拍的照片[CQ:image,file=123.jpg]"; 15 | 16 | // ReSharper disable once InconsistentNaming 17 | private static readonly JArray ArrayToken = JArray.FromObject( 18 | new object[] 19 | { 20 | new 21 | { 22 | type = "face", 23 | data = new 24 | { 25 | id = "178" 26 | } 27 | }, 28 | new 29 | { 30 | type = "text", 31 | data = new 32 | { 33 | text = "看看我刚拍的照片" 34 | } 35 | }, 36 | new 37 | { 38 | type = "image", 39 | data = new 40 | { 41 | file = "123.jpg" 42 | } 43 | } 44 | }); 45 | 46 | #endregion 47 | 48 | private static void ParseMessage(JToken token) 49 | { 50 | CqMessageHost cqMessageHost = new CqMessageHost(new CqCodeHost(new Logger(new NullLoggerFactory()))); 51 | 52 | CqMessage message = cqMessageHost.Parse(token); 53 | 54 | Assert.Equal(3, message.CodeList.Count); 55 | 56 | Assert.IsType(message.CodeList[0]); 57 | Assert.IsType(message.CodeList[1]); 58 | Assert.IsType(message.CodeList[2]); 59 | 60 | Assert.Equal(178, ((CqCodeFace) message.CodeList[0]).Id); 61 | Assert.Equal("看看我刚拍的照片", ((CqCodeText) message.CodeList[1]).Text); 62 | Assert.Equal("123.jpg", ((CqCodeImage) message.CodeList[2]).File); 63 | } 64 | 65 | [Fact] 66 | public static void ParseStringMessage() => ParseMessage(JValue.CreateString(StringToken)); 67 | 68 | [Fact] 69 | public static void ParseArrayMessage() => ParseMessage(ArrayToken); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /test/kaiheila-onebot-test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | Kaiheila.OneBot.Test 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | all 16 | 17 | 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | all 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | --------------------------------------------------------------------------------