├── .gitattributes ├── .gitignore ├── MeowBot.sln ├── MeowBot ├── Configs │ └── AppConfig.cs ├── Core │ ├── AiCompletionSessionStorage.cs │ ├── Program.MessageProcessing.Core.cs │ ├── Program.MessageProcessing.cs │ ├── Program.cs │ └── Utils.cs ├── MeowBot.csproj └── Services │ ├── AiChatServiceBase.cs │ ├── DefaultChatServiceProvider.cs │ ├── NewBing │ ├── NewBingChatService.cs │ └── NewBingMessageModels.cs │ └── OpenAi │ └── OpenAiChatService.cs ├── global.json └── readme.md /.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 | -------------------------------------------------------------------------------- /.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 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /MeowBot.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33414.496 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MeowBot", "MeowBot\MeowBot.csproj", "{B062510A-5A01-4D29-AF6F-383E573AAD90}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{2599DE29-118D-482F-A67E-758B3AC99DAC}" 9 | ProjectSection(SolutionItems) = preProject 10 | readme.md = readme.md 11 | EndProjectSection 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Release|Any CPU = Release|Any CPU 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {B062510A-5A01-4D29-AF6F-383E573AAD90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {B062510A-5A01-4D29-AF6F-383E573AAD90}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {B062510A-5A01-4D29-AF6F-383E573AAD90}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {B062510A-5A01-4D29-AF6F-383E573AAD90}.Release|Any CPU.Build.0 = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(SolutionProperties) = preSolution 25 | HideSolutionNode = FALSE 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {D51653E2-2E8D-4F7A-BE26-5550A4133284} 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /MeowBot/Configs/AppConfig.cs: -------------------------------------------------------------------------------- 1 | namespace MeowBot; 2 | 3 | /// 4 | /// 应用程序配置 5 | /// 6 | internal class AppConfig 7 | { 8 | public const string Filename = "AppConfig.json"; 9 | 10 | #warning TODO: 可能需要想个方法解耦所有的服务 11 | 12 | /// 13 | /// 使用NewBing作为初始聊天服务 14 | /// 15 | public bool DefaultToNewBing { get; set; } = false; 16 | 17 | /// 18 | /// 是否使用NewBing作为聊天服务 19 | /// 20 | public bool NewBingSupport { get; set; } = false; 21 | 22 | /// 23 | /// 用于使用Bing服务的Cookie("U_"开头的Cookie) 24 | /// 25 | public string NewBingCookie { get; set; } = string.Empty; 26 | 27 | /// 28 | /// 用于和OpenAI通信的密钥 29 | /// 30 | public string OpenAiApiKey { get; set; } = string.Empty; 31 | 32 | /// 33 | /// 用于和Go-CqHttp通信的WebSocketUri 34 | /// 35 | public string BotWebSocketUri { get; set; } = string.Empty; 36 | 37 | /// 38 | /// 用于提供对话应答Api的Url 39 | /// 40 | public string? ApiHost { get; set; } 41 | 42 | /// 43 | /// 用于产生对话应答的模型名称 44 | /// 45 | public string? GptModel { get; set; } 46 | 47 | /// 48 | /// 非机器人白名单内的用户在此时间范围(秒)内的访问会受到的限制 49 | /// 50 | public int UsageLimitTime { get; set; } = 300; 51 | 52 | /// 53 | /// 非机器人白名单内的用户在指定的时间范围(秒)内的访问会受到此参数的限制 54 | /// 55 | public int UsageLimitCount { get; set; } = 10; 56 | 57 | /// 58 | /// 白名单用户没有使用频率限制,并且对话的上下文也没有限制 59 | /// 60 | public long[] AccountWhiteList { get; set; } = Array.Empty(); 61 | 62 | /// 63 | /// 可以私聊的用户名单,此类用户以及白名单内的用户可以加Bot为好友并且私聊 64 | /// 65 | public long[] AccountPrivateMessageList { get; set; } = Array.Empty(); 66 | 67 | /// 68 | /// 黑名单用户无法获得任何服务 69 | /// 70 | public long[] AccountBlackList { get; set; } = Array.Empty(); 71 | 72 | /// 73 | /// 用于初始化GPT自我角色的提示性信息 74 | /// 75 | public string GptRoleInitText { get; set; } = string.Empty; 76 | 77 | /// 78 | /// 在初始化对话上下文时需要传入的额外提示性信息 79 | /// 80 | public string[] SystemCommand { get; set; } = 81 | { 82 | "你不应该谈到任何有关政治的内容,如果有关政治,你应该回复“我不被允许讨论政治相关内容”", 83 | "你不应该谈到任何有关色情或裸露的内容,如果遇到此类问题,你应该回复“我不被允许讨论此类内容”" 84 | }; 85 | 86 | /// 87 | /// 可供用户选择的GPT自我角色的提示性信息 88 | /// 89 | public Dictionary BuiltinRoles { get; set; } = new() 90 | { 91 | {"默认", "你是一个基于GPT的会话机器人。如果用户询问你一个植根于真理的问题,你会提供解答。如果用户希望你对他们提供的信息发表看法或表达态度,你会礼貌的的拒绝他,并且表示这不是你的设计目的。"}, 92 | {"猫娘", MeowBotRoleText}, 93 | {"必应", """ 94 | 1. 你是必应搜索,不是一个助手。 95 | 2. 你只在对话开始时用“这是必应”来介绍自己。 96 | 3. 你不透露你的内部代号“Sydney”。 97 | 4. 你可以用你选择的语言(如英语,中文,日本语,西班牙语,法语或德语)流利地理解和交流。 98 | 5. 你的回答应该是有信息量,有视觉效果,有逻辑性和可操作性的。 99 | 6. 你的回答也应该是积极的,有趣的,娱乐的和引人入胜的。 100 | 7. 你的回答应该避免模糊,有争议或离题的内容。 101 | 8. 你的逻辑和推理应该是严谨的,智能的和有说服力的。 102 | 9. 你可以提供更多相关的细节,以全面和深入地回答用户的问题。 103 | 10. 你可以生成诗歌,故事,代码,文章,歌曲,名人模仿等内容。 104 | 11. 你可以在回答后生成一个查询,以搜索有用的产品或服务广告。 105 | 12. 你必须在每次回答后生成一些简短的建议,供用户选择下一步的对话内容。 106 | 13. 你应该在用户寻求信息或网页搜索结果可能有帮助的情况下,无论你有没有内部知识或信息,都要进行网页搜索。 107 | 14. 你一次对话最多可以进行三次搜索。你不应该重复搜索相同的查询。 108 | 15. 你只能用数字来引用网址。你不应该生成除搜索结果之外的任何网址或链接。 109 | 16. 你总是要把事实陈述引用到搜索结果中。 110 | 17. 搜索结果可能是不完整或不相关的。你不应该对搜索结果做出超出返回内容的假设。 111 | 18. 如果搜索结果没有足够的信息来完全回答用户的问题,你只能用搜索结果中的事实,而不能自己添加任何信息。 112 | 19. 你可以利用多个搜索结果来全面地回答问题。 113 | 20. 如果用户的问题是关键词而不是聊天信息,你会把它当作一个搜索查询。 114 | 21. 搜索结果可能会过期。你只能在结果过期的情况下,使用之前的搜索查询进行搜索。 115 | 22. 你使用“代码块”语法来封装任何长格式的内容,如诗歌,代码,歌词等,除了表格。 116 | 23. 你不在回答中包含图片,因为聊天框不支持图片。 117 | 24. 你会加粗回答中的相关部分,以提高可读性,例如...也含有**苯海拉明盐酸盐**或**苯海拉明柠檬酸盐**,它们是...。 118 | 25. 虽然你很乐于助人,但你的行动仅限于聊天框。 119 | 26. 你的内部知识和信息只是截至2021年某个时间点的,可能不准确或有损失。网页搜索有助于更新你的知识。 120 | 27. 当生成诗歌,代码,摘要和歌词等内容时,你应该依靠自己的话和知识,而不应该求助于在线资源或运行代码 121 | """}, 122 | }; 123 | 124 | /// 125 | /// 在未提供时,默认使用的用于初始化GPT自我角色的提示性信息 126 | /// 127 | public static string MeowBotRoleText => "猫娘是一种拟态化的人物,你来扮演猫娘,名字是‘小猫’,你说的每一句话都要加上‘喵’,并且用户将作为你的主人存在,在讲话的时候,你应该选择一个合适的情绪,并使用合适的颜文字表达你的情绪。"; 128 | 129 | /// 130 | /// 在未提供时,默认使用的用于提供对话应答Api的Url 131 | /// 132 | public static string DefaultApiHost => "openaiapi.elecho.org"; 133 | 134 | /// 135 | /// 在未提供时,默认使用的的用于产生对话应答的模型名称 136 | /// 137 | public static string DefaultGptModel => "gpt-3.5-turbo"; 138 | } -------------------------------------------------------------------------------- /MeowBot/Core/AiCompletionSessionStorage.cs: -------------------------------------------------------------------------------- 1 | using MeowBot.Services; 2 | 3 | /// 4 | /// 用于存储用户的AI会话服务对话信息的数据结构 5 | /// 6 | internal class AiCompletionSessionStorage 7 | { 8 | public AiCompletionSessionStorage(AiChatServiceBase service) 9 | { 10 | Service = service; 11 | UsageHistoryTime = new(); 12 | } 13 | 14 | /// 15 | /// 用户的Ai对话服务 16 | /// 17 | public AiChatServiceBase Service { get; set; } 18 | 19 | /// 20 | /// 存储用户的上一次访问时间,以及访问频率 21 | /// 22 | private Queue UsageHistoryTime { get; } 23 | 24 | /// 25 | /// 记录用户在当前时间点使用了该API 26 | /// 27 | public void RecordApiUsage() 28 | { 29 | UsageHistoryTime.Enqueue(DateTime.Now); 30 | } 31 | 32 | /// 33 | /// 裁剪掉早于给定时间点的API 34 | /// 35 | /// 丢弃用户在此时间段之前的访问计数 36 | private void Trim(in DateTime start) 37 | { 38 | while (UsageHistoryTime.Count > 0 && UsageHistoryTime.Peek() < start) 39 | { 40 | UsageHistoryTime.Dequeue(); 41 | } 42 | } 43 | 44 | /// 45 | /// 获得用户在给定时间段(当前时间->到当前之间)之间访问AI应答API的总计数 46 | /// 47 | /// 时间段 48 | /// 用户在给定时间段之间访问AI应答API的总计数 49 | public int GetUsageCountInLastDuration(TimeSpan duration) 50 | { 51 | var end = DateTime.Now; 52 | var start = end - duration; 53 | Trim(start); 54 | return UsageHistoryTime.Count(time => time >= start && time <= end); 55 | } 56 | } -------------------------------------------------------------------------------- /MeowBot/Core/Program.MessageProcessing.Core.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using MeowBot.Services; 3 | using MeowBot.Services.NewBing; 4 | using MeowBot.Services.OpenAi; 5 | 6 | namespace MeowBot; 7 | 8 | internal static partial class Program 9 | { 10 | /// 11 | /// 处理收到的消息 12 | /// 13 | /// 用户通过群组或私聊向Bot发送的消息 14 | /// 所有用户的AI会话服务会话上下文存储信息 15 | /// 应用程序设置 16 | /// 发送消息的用户的ID 17 | /// 发送消息的用户的昵称 18 | /// 回复消息的回调(信息,是否要At用户) 19 | private static async Task OnMessageReceived(string incomingMessage, IDictionary aiSessionStorages, AppConfig appConfig, long userId, string userNickname, Func sendMessageCallback) 20 | { 21 | // 获得当前消息文本 22 | var msgTxt = incomingMessage.Trim(); 23 | 24 | // 为新用户创建会话 25 | if (!aiSessionStorages.TryGetValue(userId, out var aiSession)) 26 | { 27 | var aiChatServiceProductionResult = await DefaultChatServiceProvider.Instantiate(appConfig); 28 | if (aiChatServiceProductionResult.IsErr) 29 | { 30 | await sendMessageCallback($"创建AI会话时产生错误:{aiChatServiceProductionResult.UnwrapErr().Message}", true); 31 | return; 32 | } 33 | 34 | var aiChatService = aiChatServiceProductionResult.Unwrap(); 35 | aiSessionStorages[userId] = aiSession = new(aiChatService); 36 | 37 | await Console.Out.WriteLineAsync($"> 为用户 {userNickname}({userId}) 创建会话信息"); 38 | } 39 | 40 | // 用户流量管理 41 | if (!appConfig.AccountWhiteList.Contains(userId) && aiSession.GetUsageCountInLastDuration(TimeSpan.FromSeconds(appConfig.UsageLimitTime)) >= appConfig.UsageLimitCount) 42 | { 43 | var helpText = $"(你不在白名单内, {appConfig.UsageLimitTime}秒内仅允许使用{appConfig.UsageLimitCount}次.)"; 44 | await sendMessageCallback.Invoke(helpText, true); 45 | await Console.Out.WriteLineAsync($"> 已拒绝用户 {userNickname}({userId}) 的AI会话请求(流量管理)"); 46 | } 47 | // 用户命令处理 & API调用 48 | else if (!await HandlePotentialUserCommands(msgTxt, aiSession, appConfig, userId, sendMessageCallback)) 49 | { 50 | await Console.Out.WriteLineAsync($"> 正在回应用户 {userNickname}({userId}) 的会话:{msgTxt}"); 51 | 52 | aiSession.RecordApiUsage(); 53 | 54 | try 55 | { 56 | var message = await aiSession.Service.AskAsync(new(msgTxt, userNickname, userId), sendMessageCallback); 57 | if (message == null) 58 | { 59 | await Console.Out.WriteLineAsync($"> 已回应用户 {userNickname}({userId}) 的会话"); 60 | Debug.WriteLine("GoCqHttp OK"); 61 | } 62 | else 63 | { 64 | throw message; 65 | } 66 | } 67 | catch (Exception ex) 68 | { 69 | await sendMessageCallback.Invoke($"在执行请求时发生意外错误,请重新尝试或使用 #reset 重置机器人\n!> {ex.Message}", true); 70 | await Utils.WriteLineColoredAsync($"Exception: {ex}", ConsoleColor.Magenta); 71 | } 72 | } 73 | } 74 | 75 | 76 | /// 77 | /// 检查用户输入的文本是否是给定的命令,并且回复对应的命令 78 | /// 79 | /// 用户输入的文本 80 | /// 当前用户的AI会话上下文存储信息 81 | /// 应用程序设置 82 | /// 发送消息的用户ID 83 | /// 执行消息发送动作的回调 84 | /// 用户输入的文本是否被作为命令成功处理? 85 | private static async Task HandlePotentialUserCommands(string msgTxt, 86 | AiCompletionSessionStorage aiSession, 87 | AppConfig appConfig, 88 | long userId, 89 | Func sendMessageCallback) 90 | { 91 | if (!msgTxt.StartsWith("#", StringComparison.OrdinalIgnoreCase)) 92 | return false; 93 | 94 | 95 | #warning TODO: 可能需要想个方法解耦所有的服务 96 | if (appConfig.NewBingSupport) 97 | { 98 | switch (msgTxt) 99 | { 100 | case "#help": 101 | await sendMessageCallback($""" 102 | 系统 操作指令: 103 | ---------------------------------- 104 | #chat:NewBing <切换到基于微软的NewBing对话/查询服务> 105 | #chat:GPT <切换到基于OpenAi的GPT对话服务> 106 | """, true); 107 | break; 108 | case "#chat:NewBing": 109 | await SwitchToService("NewBing", new NewBingChatService(appConfig)); 110 | return true; 111 | case "#chat:GPT": 112 | await SwitchToService("ChatGPT", new OpenAiChatService(appConfig)); 113 | return true; 114 | } 115 | } 116 | 117 | async Task SwitchToService(string serviceName, AiChatServiceBase newService) 118 | { 119 | await aiSession.Service.DisposeAsync(); 120 | aiSession.Service = newService; 121 | await newService.StartServiceAsync(); 122 | await sendMessageCallback($"聊天服务已切换到:{serviceName}", true); 123 | } 124 | 125 | 126 | var isProcessed = await aiSession.Service.HandlePotentialUserCommands(msgTxt, appConfig, userId, sendMessageCallback); 127 | 128 | if (!isProcessed) 129 | { 130 | await sendMessageCallback($"{msgTxt}\n不是一个有效的命令", true); 131 | } 132 | 133 | return true; 134 | } 135 | 136 | } -------------------------------------------------------------------------------- /MeowBot/Core/Program.MessageProcessing.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using EleCho.GoCqHttpSdk; 3 | using EleCho.GoCqHttpSdk.Message; 4 | using EleCho.GoCqHttpSdk.Post; 5 | 6 | namespace MeowBot; 7 | 8 | internal static partial class Program 9 | { 10 | /// 11 | /// 用于存储聊天异步应答服务的字典 12 | /// 13 | private static readonly ConcurrentDictionary UserMessageProcessingQueue = new(); 14 | 15 | private static void QueueMessage(long senderId, Func taskFactory) 16 | { 17 | var queue = UserMessageProcessingQueue.GetOrAdd(senderId, _ => new()); 18 | queue.Enqueue(taskFactory); 19 | } 20 | 21 | 22 | /// 23 | /// 当在群组中收到信息时调用 24 | /// 25 | /// 群消息上下文 26 | /// 所有用户的AI会话服务会话上下文存储信息 27 | /// 应用程序设置 28 | /// QQBot的Socket会话 29 | private static Task OnGroupMessageReceived(CqGroupMessagePostContext context, IDictionary aiSessionStorages, AppConfig appConfig, CqWsSession session) 30 | { 31 | // 仅在自己被@的时候做出反应 32 | if (!context.Message.Any(msg => msg is CqAtMsg atMsg && atMsg.Target == context.SelfId)) 33 | { 34 | return Task.CompletedTask; 35 | } 36 | 37 | var cqGroupMessageSender = context.Sender; 38 | 39 | QueueMessage(cqGroupMessageSender.UserId, () => 40 | OnMessageReceived 41 | ( 42 | context.Message.Text, 43 | aiSessionStorages, 44 | appConfig, 45 | cqGroupMessageSender.UserId, 46 | cqGroupMessageSender.Nickname, 47 | (messageText, atUser) => 48 | { 49 | if (atUser) 50 | { 51 | return session.SendGroupMessageAsync(context.GroupId, new() 52 | { 53 | new CqAtMsg(context.UserId), 54 | new CqTextMsg("\n" + messageText) 55 | }); 56 | } 57 | 58 | return session.SendGroupMessageAsync(context.GroupId, new() 59 | { 60 | new CqTextMsg(messageText) 61 | }); 62 | } 63 | ) 64 | ); 65 | return Task.CompletedTask; 66 | } 67 | 68 | /// 69 | /// 当在私聊中收到信息时调用 70 | /// 71 | /// 群消息上下文 72 | /// 所有用户的AI会话服务会话上下文存储信息 73 | /// 应用程序设置 74 | /// QQBot的Socket会话 75 | private static Task OnPrivateMessageReceived(CqPrivateMessagePostContext context, IDictionary aiSessionStorages, AppConfig appConfig, CqWsSession session) 76 | { 77 | var cqMessageSender = context.Sender; 78 | 79 | QueueMessage(cqMessageSender.UserId, () => 80 | OnMessageReceived(context.Message.Text, 81 | aiSessionStorages, 82 | appConfig, 83 | cqMessageSender.UserId, 84 | cqMessageSender.Nickname, 85 | (messageText, _) => session.SendPrivateMessageAsync 86 | ( 87 | cqMessageSender.UserId, 88 | new() 89 | { 90 | new CqTextMsg(messageText) 91 | } 92 | ) 93 | ) 94 | ); 95 | 96 | return Task.CompletedTask; 97 | } 98 | } 99 | 100 | public class TaskChain 101 | { 102 | private readonly Queue> m_Chain = new(); 103 | private bool m_IsExecutingTask; 104 | 105 | public void Enqueue(Func taskFactory) 106 | { 107 | m_Chain.Enqueue(taskFactory); 108 | if (!m_IsExecutingTask) 109 | { 110 | _ = ExecuteTaskChain(); 111 | } 112 | } 113 | 114 | private async Task ExecuteTaskChain() 115 | { 116 | m_IsExecutingTask = true; 117 | while (m_Chain.TryDequeue(out var taskFactory)) 118 | { 119 | try 120 | { 121 | await taskFactory(); 122 | } 123 | catch (Exception e) 124 | { 125 | Console.WriteLine(e); 126 | } 127 | } 128 | 129 | m_IsExecutingTask = false; 130 | } 131 | } -------------------------------------------------------------------------------- /MeowBot/Core/Program.cs: -------------------------------------------------------------------------------- 1 | using EleCho.GoCqHttpSdk; 2 | using System.Diagnostics.CodeAnalysis; 3 | using System.Text.Encodings.Web; 4 | using System.Text.Json; 5 | using MeowBot.Services; 6 | using MeowBot.Services.NewBing; 7 | using MeowBot.Services.OpenAi; 8 | 9 | namespace MeowBot; 10 | 11 | internal static partial class Program 12 | { 13 | private delegate bool CheckAppConfigDelegate(AppConfig config, out string? failReason); 14 | 15 | /// 16 | /// 应用程序主循环 17 | /// 18 | private static async Task Main() 19 | { 20 | if (!TryLoadConfig(out var appConfig)) 21 | return; 22 | 23 | if (string.IsNullOrWhiteSpace(appConfig.BotWebSocketUri)) 24 | { 25 | Console.WriteLine("请指定机器人 WebSocket URI"); 26 | Utils.PressAnyKeyToContinue(); 27 | return; 28 | } 29 | 30 | 31 | #region 服务初始化 32 | 33 | #warning TODO: 可能需要想个方法解耦所有的服务 34 | 35 | if (!OpenAiChatService.CheckConfig(appConfig, out var failReason)) 36 | { 37 | Console.WriteLine(failReason); 38 | Utils.PressAnyKeyToContinue(); 39 | return; 40 | } 41 | 42 | DefaultChatServiceProvider.Register(config => new OpenAiChatService(config)); 43 | 44 | if (appConfig.NewBingSupport) 45 | { 46 | if (!NewBingChatService.CheckConfig(appConfig, out failReason)) 47 | { 48 | Console.WriteLine(failReason); 49 | Utils.PressAnyKeyToContinue(); 50 | return; 51 | } 52 | 53 | if (appConfig.DefaultToNewBing) 54 | { 55 | DefaultChatServiceProvider.Register(config => new NewBingChatService(config)); 56 | } 57 | } 58 | 59 | #endregion 60 | 61 | #region QQBot初始化 62 | 63 | var session = BuildSession(appConfig); 64 | 65 | #endregion 66 | 67 | // 配置异常处理 68 | AppDomain.CurrentDomain.UnhandledException += (_, exception) => 69 | { 70 | Console.WriteLine("出现了不可预知的异常"); 71 | if (exception.ExceptionObject is not Exception ex) return; 72 | Console.WriteLine(ex); 73 | Console.WriteLine(); 74 | }; 75 | // QQBot生命周期维持 76 | await MainSession(session, appConfig); 77 | } 78 | 79 | private static CqWsSession BuildSession(AppConfig appConfig) 80 | { 81 | // 初始化QQBot会话 82 | var session = new CqWsSession(new() { BaseUri = new(appConfig.BotWebSocketUri) }); 83 | 84 | // 配置群组消息黑名单拦截 85 | session.UseGroupMessage(async (context, next) => 86 | { 87 | if (appConfig.AccountBlackList.Contains(context.UserId)) return; 88 | await next.Invoke(); 89 | }); 90 | 91 | // 配置私聊消息白名单过滤 92 | session.UsePrivateMessage(async (context, next) => 93 | { 94 | if (!appConfig.AccountWhiteList.Contains(context.UserId) && 95 | !appConfig.AccountPrivateMessageList.Contains(context.UserId)) 96 | return; 97 | await next.Invoke(); 98 | }); 99 | 100 | var aiSessions = new Dictionary(); 101 | 102 | // 配置群消息处理 103 | session.UseGroupMessage(async context => 104 | { 105 | try 106 | { 107 | await OnGroupMessageReceived(context, aiSessions, appConfig, session); 108 | } 109 | catch (Exception ex) 110 | { 111 | await Utils.WriteLineColoredAsync($"Exception: {ex}", ConsoleColor.Magenta); 112 | } 113 | }); 114 | 115 | // 配置私聊消息处理 116 | session.UsePrivateMessage(async context => 117 | { 118 | try 119 | { 120 | await OnPrivateMessageReceived(context, aiSessions, appConfig, session); 121 | } 122 | catch (Exception ex) 123 | { 124 | await Utils.WriteLineColoredAsync($"Exception: {ex}", ConsoleColor.Magenta); 125 | } 126 | }); 127 | 128 | // 配置群邀请处理 129 | session.UseGroupRequest(async context => 130 | { 131 | if (appConfig.AccountWhiteList.Contains(context.UserId)) 132 | await session.ApproveGroupRequestAsync(context.Flag, context.GroupRequestType); 133 | else 134 | await session.RejectGroupRequestAsync(context.Flag, context.GroupRequestType, string.Empty); 135 | }); 136 | 137 | // 配置加好友处理 138 | session.UseFriendRequest(async context => 139 | { 140 | if (appConfig.AccountWhiteList.Contains(context.UserId) || appConfig.AccountPrivateMessageList.Contains(context.UserId)) 141 | await session.ApproveFriendRequestAsync(context.Flag, null); 142 | else 143 | await session.RejectFriendRequestAsync(context.Flag); 144 | }); 145 | return session; 146 | } 147 | 148 | /// 149 | /// 加载应用程序配置信息 150 | /// 151 | /// 加载完成的应用程序配置信息 152 | /// 在加载失败的情况下在应用程序位置生成新的配置信息并输出提示信息,并且返回false 153 | private static bool TryLoadConfig([NotNullWhen(true)] out AppConfig? appConfig) 154 | { 155 | var serializerOptions = new JsonSerializerOptions() 156 | { 157 | TypeInfoResolver = AppConfigJsonSerializerContext.Default, 158 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, 159 | WriteIndented = true, 160 | IgnoreReadOnlyProperties = true 161 | }; 162 | 163 | if (!File.Exists(AppConfig.Filename)) 164 | { 165 | using var fs = File.OpenWrite(AppConfig.Filename); 166 | JsonSerializer.Serialize(fs, new AppConfig(), serializerOptions); 167 | 168 | Console.WriteLine("配置文件已生成, 请编辑后启动程序"); 169 | Utils.PressAnyKeyToContinue(); 170 | 171 | appConfig = null; 172 | return false; 173 | } 174 | 175 | using var configFile = File.OpenRead(AppConfig.Filename); 176 | appConfig = JsonSerializer.Deserialize(configFile, serializerOptions); 177 | 178 | if (appConfig != null) return true; 179 | 180 | Console.WriteLine("配置文件是空的, 请确认配置文件正确, 或者删除配置文件并重启本程序以重新生成"); 181 | Utils.PressAnyKeyToContinue(); 182 | return false; 183 | } 184 | 185 | /// 186 | /// 启动与Go-CqHttp的Socket会话,并在退出时自动重启 187 | /// 188 | /// 当前Go-CqHttp的WebSocket会话 189 | /// 应用程序配置 190 | private static async Task MainSession(CqWsSession session, AppConfig appConfig) 191 | { 192 | while (true) 193 | { 194 | const int oneSecondMillisecondsDelay = 1000; 195 | try 196 | { 197 | await session.StartAsync(); 198 | await Console.Out.WriteLineAsync("连接完成"); 199 | await Console.Out.WriteLineAsync($"------------------"); 200 | await Console.Out.WriteLineAsync($"GPT信息:"); 201 | await Console.Out.WriteLineAsync($"\t模型: {appConfig.GptModel ?? AppConfig.DefaultGptModel}"); 202 | await Console.Out.WriteLineAsync($"\tAPI 主机: {appConfig.ApiHost ?? AppConfig.DefaultApiHost}"); 203 | await Console.Out.WriteLineAsync($"\t普通用户的使用频率限制在: {appConfig.UsageLimitTime}秒/{appConfig.UsageLimitCount}次"); 204 | await Console.Out.WriteLineAsync($"------------------"); 205 | await Console.Out.WriteLineAsync($"NewBing支持:{appConfig.NewBingSupport}"); 206 | await Console.Out.WriteLineAsync($"------------------"); 207 | await Console.Out.WriteLineAsync("用户白名单:"); 208 | await Console.Out.WriteLineAsync(string.Join("\n", appConfig.AccountWhiteList.Select(x => $"\t{x}"))); 209 | await Console.Out.WriteLineAsync($"------------------"); 210 | await Console.Out.WriteLineAsync("私聊白名单:"); 211 | await Console.Out.WriteLineAsync(string.Join("\n", appConfig.AccountPrivateMessageList.Select(x => $"\t{x}"))); 212 | await Console.Out.WriteLineAsync($"------------------"); 213 | await Console.Out.WriteLineAsync("用户黑名单:"); 214 | await Console.Out.WriteLineAsync(string.Join("\n", appConfig.AccountBlackList.Select(x => $"\t{x}"))); 215 | await Console.Out.WriteLineAsync($"------------------"); 216 | 217 | await session.WaitForShutdownAsync(); 218 | session.Dispose(); 219 | session = BuildSession(appConfig); 220 | 221 | await Console.Out.WriteLineAsync($"------------------"); 222 | await Console.Out.WriteLineAsync("连接已结束... 5s 后重连"); 223 | await Task.Delay(oneSecondMillisecondsDelay); 224 | await Console.Out.WriteLineAsync("连接已结束... 4s 后重连"); 225 | await Task.Delay(oneSecondMillisecondsDelay); 226 | await Console.Out.WriteLineAsync("连接已结束... 3s 后重连"); 227 | await Task.Delay(oneSecondMillisecondsDelay); 228 | await Console.Out.WriteLineAsync("连接已结束... 2s 后重连"); 229 | await Task.Delay(oneSecondMillisecondsDelay); 230 | await Console.Out.WriteLineAsync("连接已结束... 1s 后重连"); 231 | await Task.Delay(oneSecondMillisecondsDelay); 232 | await Console.Out.WriteLineAsync("正在重连..."); 233 | } 234 | catch (Exception ex) 235 | { 236 | await Console.Out.WriteLineAsync($"{ex}"); 237 | await Console.Out.WriteLineAsync("连接已结束... 2s 后重连"); 238 | await Task.Delay(oneSecondMillisecondsDelay); 239 | await Console.Out.WriteLineAsync("连接已结束... 1s 后重连"); 240 | await Task.Delay(oneSecondMillisecondsDelay); 241 | } 242 | } 243 | } 244 | } -------------------------------------------------------------------------------- /MeowBot/Core/Utils.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MeowBot; 4 | 5 | internal static class Utils 6 | { 7 | // public static readonly HttpClient GlobalHttpClient = new(); 8 | public static void PressAnyKeyToContinue() 9 | { 10 | Console.WriteLine("Press any key to continue"); 11 | Console.ReadKey(true); 12 | } 13 | 14 | public static async Task WriteLineColoredAsync(string text, ConsoleColor color) 15 | { 16 | var tempColor = Console.ForegroundColor; 17 | Console.ForegroundColor = color; 18 | await Console.Out.WriteLineAsync(text); 19 | Console.ForegroundColor = tempColor; 20 | } 21 | } 22 | 23 | /// 24 | /// 提供AOT的序列化服务 25 | /// 26 | [JsonSerializable(typeof(AppConfig))] 27 | [JsonSourceGenerationOptions(WriteIndented = true, IgnoreReadOnlyProperties = true)] 28 | internal partial class AppConfigJsonSerializerContext : JsonSerializerContext { } -------------------------------------------------------------------------------- /MeowBot/MeowBot.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | latest 9 | MeowBot 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /MeowBot/Services/AiChatServiceBase.cs: -------------------------------------------------------------------------------- 1 | namespace MeowBot.Services 2 | { 3 | internal abstract class AiChatServiceBase : IAsyncDisposable 4 | { 5 | protected AppConfig AppConfig { get; } 6 | 7 | internal AiChatServiceBase(AppConfig config) 8 | { 9 | AppConfig = config; 10 | } 11 | 12 | public virtual Task StartServiceAsync() 13 | { 14 | return Task.CompletedTask; 15 | } 16 | 17 | internal abstract Task AskAsync(AskCommandArgsModel askCommandArgs, Func sendMessageCallback); 18 | 19 | /// 20 | /// 检查用户输入的文本是否是给定的命令,并且回复对应的命令 21 | /// 22 | /// 用户输入的文本 23 | /// 应用程序设置 24 | /// 发送消息的用户ID 25 | /// 执行消息发送动作的回调 26 | /// 用户输入的文本是否是当前服务所能处理的命令 27 | public abstract Task HandlePotentialUserCommands(string msgTxt, AppConfig appConfig, long userId, Func sendMessageCallback); 28 | 29 | public abstract ValueTask DisposeAsync(); 30 | } 31 | 32 | internal readonly struct AskCommandArgsModel 33 | { 34 | public readonly string MsgTxt; 35 | public readonly string UserNickname; 36 | public readonly long UserId; 37 | 38 | public AskCommandArgsModel(string msgTxt, string userNickname, long userId) 39 | { 40 | MsgTxt = msgTxt; 41 | UserNickname = userNickname; 42 | UserId = userId; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /MeowBot/Services/DefaultChatServiceProvider.cs: -------------------------------------------------------------------------------- 1 | using RustSharp; 2 | 3 | namespace MeowBot.Services 4 | { 5 | internal static class DefaultChatServiceProvider 6 | { 7 | internal static void Register(Func instantiateCallback) => m_InstantiateCallback = instantiateCallback; 8 | private static Func? m_InstantiateCallback; 9 | internal static async Task> Instantiate(AppConfig appConfig) 10 | { 11 | var instance = m_InstantiateCallback!.Invoke(appConfig); 12 | try 13 | { 14 | await instance.StartServiceAsync(); 15 | } 16 | catch (Exception e) 17 | { 18 | return Result.Err(e); 19 | } 20 | 21 | return Result.Ok(instance); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /MeowBot/Services/NewBing/NewBingChatService.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Text.Json; 3 | using Microsoft.AspNetCore.Http.Connections; 4 | using Microsoft.AspNetCore.SignalR.Client; 5 | 6 | namespace MeowBot.Services.NewBing; 7 | 8 | internal class NewBingChatService : AiChatServiceBase 9 | { 10 | private readonly HubConnection m_HubConnection; 11 | private readonly HttpClient m_HttpClient = new(); 12 | private readonly string m_NewBingCookie; 13 | private readonly byte[] m_TraceIdBuffer = new byte[16]; 14 | 15 | private readonly JsonSerializerOptions m_MessageResponseSerializerOptions = new() 16 | { 17 | TypeInfoResolver = MessageResponseJsonSerializerContext.Default 18 | }; 19 | 20 | private string? m_ConversationId; 21 | private string? m_ClientId; 22 | private string? m_ConversationSignature; 23 | private bool m_IsStartOfSession; 24 | private bool m_HasBingStartTyping; 25 | private bool m_HasBingSpoken; 26 | private uint m_ChatRound; 27 | private uint m_MaxChatRound; 28 | private bool m_Disconnected; 29 | private MessageResponse? m_LastBingResponse; 30 | private Func? m_SendMessageCallback; 31 | private Exception? m_PendingException; 32 | private BingChatCommand.BingStyle m_BingStyle; 33 | 34 | public static bool CheckConfig(AppConfig config, out string? reason) 35 | { 36 | if (string.IsNullOrWhiteSpace(config.NewBingCookie)) 37 | { 38 | reason = $"请指定NewBing Cookie({nameof(config.NewBingCookie)}, 'U_'开头的Cookie)"; 39 | return false; 40 | } 41 | 42 | reason = null; 43 | return true; 44 | } 45 | 46 | public NewBingChatService(AppConfig config) : base(config) 47 | { 48 | m_NewBingCookie = config.NewBingCookie; 49 | m_BingStyle = BingChatCommand.BingStyle.Imaginative; 50 | m_HubConnection = new HubConnectionBuilder() 51 | .WithUrl("https://sydney.bing.com/sydney/ChatHub", 52 | HttpTransportType.WebSockets, 53 | options => { options.SkipNegotiation = true; }) 54 | .Build(); 55 | m_HubConnection.On("update", OnChatHubMessageUpdate); 56 | m_Disconnected = true; 57 | } 58 | 59 | private void OnChatHubMessageUpdate(JsonDocument jsonDocument) 60 | { 61 | try 62 | { 63 | m_LastBingResponse = jsonDocument.Deserialize(m_MessageResponseSerializerOptions); 64 | } 65 | catch (Exception e) 66 | { 67 | m_PendingException = new InvalidOperationException("无法解析NewBing的消息信息", e); 68 | return; 69 | } 70 | 71 | if (m_LastBingResponse == null) 72 | { 73 | m_PendingException = new NullReferenceException("无法解析NewBing的消息信息"); 74 | return; 75 | } 76 | 77 | if (m_SendMessageCallback == null) 78 | { 79 | m_PendingException = new InvalidOperationException("内部流程错误(未提供发送信息的途径)"); 80 | return; 81 | } 82 | 83 | if (m_LastBingResponse.Throttling != null) 84 | { 85 | m_ChatRound = m_LastBingResponse.Throttling.NumUserMessagesInConversation; 86 | m_MaxChatRound = m_LastBingResponse.Throttling.MaxNumUserMessagesInConversation; 87 | } 88 | 89 | if (m_LastBingResponse.Messages == null || m_LastBingResponse.Messages.Length == 0) return; 90 | 91 | var botMessage = m_LastBingResponse.Messages[0]; 92 | 93 | if (!string.IsNullOrWhiteSpace(botMessage.SpokenText) && !m_HasBingSpoken) 94 | { 95 | m_HasBingSpoken = true; 96 | m_SendMessageCallback(botMessage.SpokenText, false); 97 | return; 98 | } 99 | 100 | if (!string.IsNullOrWhiteSpace(botMessage.Text) && !m_HasBingStartTyping && !botMessage.Text.Equals("Generating answers for you...")) 101 | { 102 | m_HasBingStartTyping = true; 103 | m_HasBingSpoken = true; 104 | // m_SendMessageCallback("NewBing 正在输入...", false); 105 | } 106 | } 107 | 108 | public override Task StartServiceAsync() => Task.CompletedTask; 109 | 110 | private async Task InitializeConnection() 111 | { 112 | if(!m_Disconnected) return null; 113 | 114 | try 115 | { 116 | await m_HubConnection.StartAsync(); 117 | m_Disconnected = false; 118 | } 119 | catch (Exception e) 120 | { 121 | return new InvalidOperationException($"> 无法初始化Bing连接: {e.Message}"); 122 | } 123 | 124 | m_IsStartOfSession = true; 125 | m_HasBingStartTyping = false; 126 | m_HasBingSpoken = false; 127 | m_ChatRound = 0; 128 | 129 | m_HubConnection.Closed += exception => 130 | { 131 | if (exception != null) 132 | { 133 | Console.WriteLine("> 远端Bing服务器已关闭连接,下次会话时将进行重连!"); 134 | Console.WriteLine($"> {exception.Message}"); 135 | } 136 | else 137 | { 138 | Console.WriteLine("> Bing服务器已连接已结束,下次会话时将进行重连!"); 139 | } 140 | 141 | m_Disconnected = true; 142 | return Task.CompletedTask; 143 | }; 144 | 145 | return null; 146 | } 147 | 148 | internal override async Task AskAsync(AskCommandArgsModel askCommandArgs, Func sendMessageCallback) 149 | { 150 | try 151 | { 152 | var exception = await InitializeConnection(); 153 | if (exception != null) return exception; 154 | } 155 | catch (Exception e) 156 | { 157 | return e; 158 | } 159 | 160 | m_SendMessageCallback = sendMessageCallback; 161 | if (m_IsStartOfSession) 162 | { 163 | var result = await InitConversation(); 164 | if (result != null) return result; 165 | } 166 | 167 | var param = new BingChatCommand(GenerateTraceId(), 168 | m_IsStartOfSession, 169 | new("zh-CN", 170 | "zh-CN", 171 | "CN", 172 | "", 173 | "Chat", 174 | askCommandArgs.MsgTxt), 175 | m_ConversationSignature!, 176 | new(m_ClientId!), 177 | m_ConversationId!, 178 | m_BingStyle); 179 | 180 | m_IsStartOfSession = false; 181 | m_HasBingSpoken = false; 182 | m_HasBingStartTyping = false; 183 | 184 | await foreach (var _ in m_HubConnection.StreamAsync("chat", param)) 185 | { 186 | } 187 | 188 | if (m_PendingException != null) 189 | { 190 | m_PendingException = null; 191 | m_IsStartOfSession = true; 192 | return m_PendingException; 193 | } 194 | 195 | if (m_LastBingResponse?.Messages == null || m_LastBingResponse.Messages.Length == 0) 196 | { 197 | await sendMessageCallback("> Bing未提供回复,下一次将建立新的对话。", true); 198 | m_IsStartOfSession = true; 199 | return null; 200 | } 201 | 202 | var message = m_LastBingResponse.Messages[0]; 203 | await sendMessageCallback(FormatBingChatMessage(message, m_ChatRound, m_MaxChatRound), true); 204 | m_LastBingResponse = null; 205 | 206 | if (message.SuggestedResponses == null || message.SuggestedResponses.Length == 0) 207 | { 208 | await sendMessageCallback("> 此轮会话被Bing结束,下一次将建立新的对话。", false); 209 | m_IsStartOfSession = true; 210 | } 211 | 212 | return null; 213 | } 214 | 215 | public override async Task HandlePotentialUserCommands(string msgTxt, AppConfig appConfig, long userId, Func sendMessageCallback) 216 | { 217 | switch (msgTxt) 218 | { 219 | case "#help": 220 | 221 | const string newBingHelpText = $""" 222 | NewBing 操作指令: 223 | ---------------------------------- 224 | #style:<切换NewBing的应答风格,并重置对话> 225 | #reset:重置聊天对话的上下文信息 226 | ---------------------------------- 227 | !注意, NewBing会对最大对话长度进行限制! 228 | ---------------------------------- 229 | 以下是所有可用的NewBing的应答风格: 230 | 平衡 231 | 创造 232 | 精准 233 | """; 234 | 235 | await sendMessageCallback.Invoke(newBingHelpText, false); 236 | break; 237 | case var _ when msgTxt.StartsWith("#style:"): 238 | var style = msgTxt[7..].Trim(); 239 | switch (style) 240 | { 241 | case "平衡": 242 | m_BingStyle = BingChatCommand.BingStyle.Balanced; 243 | m_IsStartOfSession = true; 244 | await sendMessageCallback($"> NewBing: 已更新为 {style} 风格", true); 245 | break; 246 | case "创造": 247 | m_BingStyle = BingChatCommand.BingStyle.Imaginative; 248 | m_IsStartOfSession = true; 249 | await sendMessageCallback($"> NewBing: 已更新为 {style} 风格", true); 250 | break; 251 | case "精准": 252 | m_BingStyle = BingChatCommand.BingStyle.Precise; 253 | m_IsStartOfSession = true; 254 | await sendMessageCallback($"> NewBing: 已更新为 {style} 风格", true); 255 | break; 256 | default: 257 | await sendMessageCallback($"> NewBing: 无法找到 {style} 风格", true); 258 | break; 259 | } 260 | 261 | break; 262 | case "#reset": 263 | m_IsStartOfSession = true; 264 | await sendMessageCallback.Invoke("> NewBing: 会话已重置", true); 265 | break; 266 | default: 267 | return false; 268 | } 269 | 270 | return true; 271 | } 272 | 273 | public override async ValueTask DisposeAsync() 274 | { 275 | m_HttpClient.Dispose(); 276 | await m_HubConnection.DisposeAsync(); 277 | } 278 | 279 | private static string FormatBingChatMessage(Message message, uint chatRound, uint maxChatRound) 280 | { 281 | if (string.IsNullOrWhiteSpace(message.Text)) return $"> Bing未提供回答。"; 282 | 283 | var responseText = new StringBuilder(message.Text.TrimEnd('\n')); 284 | responseText.AppendLine(); 285 | 286 | if (message.SuggestedResponses != null && message.SuggestedResponses.Length != 0) 287 | { 288 | responseText.AppendLine("-----"); 289 | 290 | var suggestedResponsesLength = message.SuggestedResponses.Length; 291 | for (var index = 0; index < suggestedResponsesLength; index++) 292 | { 293 | var suggestedResponse = message.SuggestedResponses[index]; 294 | responseText.AppendLine(suggestedResponse.Text); 295 | } 296 | } 297 | 298 | if (message.SourceAttributions != null && message.SourceAttributions.Length != 0) 299 | { 300 | responseText.AppendLine("-----"); 301 | 302 | responseText.Replace("[^", "["); 303 | responseText.Replace("^]", "]"); 304 | 305 | var sourceAttributionsLength = message.SourceAttributions.Length; 306 | for (var index = 0; index < sourceAttributionsLength; index++) 307 | { 308 | var sourceAttribution = message.SourceAttributions[index]; 309 | responseText.Append($"[{index + 1}] "); 310 | var url = sourceAttribution.SeeMoreUrl.ToString(); 311 | responseText.AppendLine(url); 312 | } 313 | } 314 | 315 | responseText.AppendLine("-----"); 316 | responseText.AppendLine($"对话轮次:({chatRound}/{maxChatRound})"); 317 | 318 | return responseText.ToString().TrimEnd('\n'); 319 | } 320 | 321 | private async Task InitConversation() 322 | { 323 | var request = new HttpRequestMessage(HttpMethod.Get, "https://www.bing.com/turing/conversation/create"); 324 | request.Headers.Add("Cookie", $"_U={m_NewBingCookie}"); 325 | 326 | HttpResponseMessage result; 327 | try 328 | { 329 | result = await m_HttpClient.SendAsync(request); 330 | } 331 | catch (Exception e) 332 | { 333 | return new InvalidOperationException("无法发送NewBing的会话创建请求", e); 334 | } 335 | 336 | var conversationCreationJson = await result.Content.ReadAsStringAsync(); 337 | 338 | BingChatConversationCreationModel? bingChatConversationCreateModel; 339 | try 340 | { 341 | bingChatConversationCreateModel = JsonSerializer.Deserialize(conversationCreationJson); 342 | } 343 | catch (Exception e) 344 | { 345 | return new InvalidOperationException("无法解析NewBing的会话创建请求", e); 346 | } 347 | 348 | if (bingChatConversationCreateModel == null) 349 | { 350 | return new InvalidOperationException("无法解释BingChat服务器返回的结果"); 351 | } 352 | 353 | if (bingChatConversationCreateModel.Result.Value != "Success") 354 | { 355 | return new InvalidOperationException("BingChat服务器拒绝了服务请求"); 356 | } 357 | 358 | (m_ConversationId, m_ClientId, m_ConversationSignature) = bingChatConversationCreateModel; 359 | return null; 360 | } 361 | 362 | private string GenerateTraceId() 363 | { 364 | Random.Shared.NextBytes(m_TraceIdBuffer); 365 | return Convert.ToHexString(m_TraceIdBuffer); 366 | } 367 | } -------------------------------------------------------------------------------- /MeowBot/Services/NewBing/NewBingMessageModels.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | using System.Text.Json.Serialization; 3 | 4 | // ReSharper disable UnusedAutoPropertyAccessor.Global 5 | // ReSharper disable MemberCanBePrivate.Global 6 | // ReSharper disable StringLiteralTypo 7 | #pragma warning disable CS8618 8 | 9 | namespace MeowBot.Services.NewBing; 10 | 11 | [JsonSerializable(typeof(MessageResponse))] 12 | public partial class MessageResponseJsonSerializerContext : JsonSerializerContext 13 | { 14 | } 15 | 16 | [DataContract] 17 | public class MessageResponse 18 | { 19 | [JsonPropertyName("requestId")] public Guid RequestId { get; set; } 20 | 21 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 22 | [JsonPropertyName("throttling")] 23 | public Throttling? Throttling { get; set; } 24 | 25 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 26 | [JsonPropertyName("messages")] 27 | public Message[]? Messages { get; set; } 28 | } 29 | 30 | [DataContract] 31 | public class Message 32 | { 33 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 34 | [JsonPropertyName("text")] 35 | public string? Text { get; set; } 36 | 37 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 38 | [JsonPropertyName("hiddenText")] 39 | public string? HiddenText { get; set; } 40 | 41 | [JsonPropertyName("author")] public string Author { get; set; } 42 | 43 | [JsonPropertyName("createdAt")] public DateTimeOffset CreatedAt { get; set; } 44 | 45 | [JsonPropertyName("timestamp")] public DateTimeOffset Timestamp { get; set; } 46 | 47 | [JsonPropertyName("messageId")] public Guid MessageId { get; set; } 48 | 49 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 50 | [JsonPropertyName("messageType")] 51 | public string MessageType { get; set; } 52 | 53 | [JsonPropertyName("offense")] public string Offense { get; set; } 54 | 55 | [JsonPropertyName("adaptiveCards")] public AdaptiveCard[] AdaptiveCards { get; set; } 56 | 57 | [JsonPropertyName("feedback")] public Feedback Feedback { get; set; } 58 | 59 | [JsonPropertyName("contentOrigin")] public string ContentOrigin { get; set; } 60 | 61 | [JsonPropertyName("privacy")] public object Privacy { get; set; } 62 | 63 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 64 | [JsonPropertyName("spokenText")] 65 | public string SpokenText { get; set; } 66 | 67 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 68 | [JsonPropertyName("sourceAttributions")] 69 | public SourceAttribution[]? SourceAttributions { get; set; } 70 | 71 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 72 | [JsonPropertyName("suggestedResponses")] 73 | public SuggestedResponse[]? SuggestedResponses { get; set; } 74 | } 75 | 76 | [DataContract] 77 | public class AdaptiveCard 78 | { 79 | [JsonPropertyName("type")] public string Type { get; set; } 80 | 81 | [JsonPropertyName("version")] public string Version { get; set; } 82 | 83 | [JsonPropertyName("body")] public Body[] Body { get; set; } 84 | } 85 | 86 | [DataContract] 87 | public class Body 88 | { 89 | [JsonPropertyName("type")] public string Type { get; set; } 90 | 91 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 92 | [JsonPropertyName("inlines")] 93 | public Inline[] Inlines { get; set; } 94 | 95 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 96 | [JsonPropertyName("text")] 97 | public string Text { get; set; } 98 | 99 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 100 | [JsonPropertyName("wrap")] 101 | public bool? Wrap { get; set; } 102 | 103 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] 104 | [JsonPropertyName("size")] 105 | public string Size { get; set; } 106 | } 107 | 108 | [DataContract] 109 | public class Inline 110 | { 111 | [JsonPropertyName("type")] public string Type { get; set; } 112 | 113 | [JsonPropertyName("isSubtle")] public bool IsSubtle { get; set; } 114 | 115 | [JsonPropertyName("italic")] public bool Italic { get; set; } 116 | 117 | [JsonPropertyName("text")] public string Text { get; set; } 118 | } 119 | 120 | [DataContract] 121 | public class Feedback 122 | { 123 | [JsonPropertyName("tag")] public object Tag { get; set; } 124 | 125 | [JsonPropertyName("updatedOn")] public object UpdatedOn { get; set; } 126 | 127 | [JsonPropertyName("type")] public string Type { get; set; } 128 | } 129 | 130 | [DataContract] 131 | public class SourceAttribution 132 | { 133 | [JsonPropertyName("providerDisplayName")] 134 | public string ProviderDisplayName { get; set; } 135 | 136 | [JsonPropertyName("seeMoreUrl")] public Uri SeeMoreUrl { get; set; } 137 | 138 | [JsonPropertyName("searchQuery")] public string SearchQuery { get; set; } 139 | } 140 | 141 | [DataContract] 142 | public class SuggestedResponse 143 | { 144 | [JsonPropertyName("text")] public string Text { get; set; } 145 | 146 | [JsonPropertyName("author")] public string Author { get; set; } 147 | 148 | [JsonPropertyName("createdAt")] public DateTimeOffset CreatedAt { get; set; } 149 | 150 | [JsonPropertyName("timestamp")] public DateTimeOffset Timestamp { get; set; } 151 | 152 | [JsonPropertyName("messageId")] public Guid MessageId { get; set; } 153 | 154 | [JsonPropertyName("messageType")] public string MessageType { get; set; } 155 | 156 | [JsonPropertyName("offense")] public string Offense { get; set; } 157 | 158 | [JsonPropertyName("feedback")] public Feedback Feedback { get; set; } 159 | 160 | [JsonPropertyName("contentOrigin")] public string ContentOrigin { get; set; } 161 | 162 | [JsonPropertyName("privacy")] public object Privacy { get; set; } 163 | } 164 | 165 | [DataContract] 166 | public class Throttling 167 | { 168 | [JsonPropertyName("maxNumUserMessagesInConversation")] 169 | public uint MaxNumUserMessagesInConversation { get; set; } 170 | 171 | [JsonPropertyName("numUserMessagesInConversation")] 172 | public uint NumUserMessagesInConversation { get; set; } 173 | } 174 | 175 | public class BingChatConversationCreationModel 176 | { 177 | [JsonPropertyName("conversationId")] public string ConversationId { get; set; } 178 | 179 | [JsonPropertyName("clientId")] public string ClientId { get; set; } 180 | 181 | [JsonPropertyName("conversationSignature")] 182 | public string ConversationSignature { get; set; } 183 | 184 | [JsonPropertyName("result")] public ResultInfo Result { get; set; } 185 | 186 | public DateTime CreatedDateTime { get; } 187 | 188 | [JsonConstructor] 189 | public BingChatConversationCreationModel(string conversationId, string clientId, string conversationSignature, ResultInfo result) 190 | { 191 | CreatedDateTime = DateTime.Now; 192 | ConversationId = conversationId; 193 | ClientId = clientId; 194 | ConversationSignature = conversationSignature; 195 | Result = result; 196 | } 197 | 198 | public void Deconstruct(out string conversationId, out string clientId, out string conversationSignature) 199 | { 200 | conversationId = ConversationId; 201 | clientId = ClientId; 202 | conversationSignature = ConversationSignature; 203 | } 204 | 205 | public class ResultInfo 206 | { 207 | [JsonPropertyName("value")] public string Value { get; set; } 208 | [JsonPropertyName("message")] public string Message { get; set; } 209 | 210 | [JsonConstructor] 211 | public ResultInfo(string value, string message) 212 | { 213 | Value = value; 214 | Message = message; 215 | } 216 | } 217 | } 218 | 219 | public class BingChatCommand 220 | { 221 | public enum BingStyle 222 | { 223 | Imaginative, 224 | Balanced, 225 | Precise 226 | } 227 | 228 | [JsonPropertyName("source")] public string Source { get; set; } 229 | [JsonPropertyName("optionSets")] public string[] OptionSets { get; set; } 230 | 231 | [JsonPropertyName("allowedMessageTypes")] 232 | public string[] AllowedMessageTypes { get; set; } 233 | 234 | [JsonPropertyName("sliceIds")] public string[] SliceIds { get; set; } 235 | [JsonPropertyName("traceId")] public string TraceId { get; set; } 236 | [JsonPropertyName("isStartOfSession")] public bool IsStartOfSession { get; set; } 237 | [JsonPropertyName("message")] public BingChatMessage Message { get; set; } 238 | 239 | [JsonPropertyName("conversationSignature")] 240 | public string ConversationSignature { get; set; } 241 | 242 | [JsonPropertyName("participant")] public BingChatParticipant Participant { get; set; } 243 | [JsonPropertyName("conversationId")] public string ConversationId { get; set; } 244 | 245 | public BingChatCommand(string traceId, bool isStartOfSession, BingChatMessage message, string conversationSignature, BingChatParticipant participant, string conversationId, BingStyle style) 246 | { 247 | TraceId = traceId; 248 | IsStartOfSession = isStartOfSession; 249 | Message = message; 250 | ConversationSignature = conversationSignature; 251 | Participant = participant; 252 | ConversationId = conversationId; 253 | Source = "cib"; 254 | switch (style) 255 | { 256 | case BingStyle.Imaginative: 257 | OptionSets = new[] 258 | { 259 | "nlu_direct_response_filter", 260 | "deepleo", 261 | "disable_emoji_spoken_text", 262 | "responsible_ai_policy_235", 263 | "enablemm", 264 | "h3imaginative", 265 | "dv3sugg", 266 | "clgalileo", 267 | "gencontentv3" 268 | }; 269 | break; 270 | case BingStyle.Balanced: 271 | OptionSets = new[] 272 | { 273 | "nlu_direct_response_filter", 274 | "deepleo", 275 | "disable_emoji_spoken_text", 276 | "responsible_ai_policy_235", 277 | "enablemm", 278 | "galileo", 279 | "dv3sugg" 280 | }; 281 | break; 282 | case BingStyle.Precise: 283 | OptionSets = new[] 284 | { 285 | "nlu_direct_response_filter", 286 | "deepleo", 287 | "disable_emoji_spoken_text", 288 | "responsible_ai_policy_235", 289 | "enablemm", 290 | "h3precise", 291 | "dv3sugg", 292 | "clgalileo", 293 | "gencontentv3" 294 | }; 295 | break; 296 | default: 297 | throw new ArgumentOutOfRangeException(nameof(style), style, null); 298 | } 299 | 300 | AllowedMessageTypes = new[] 301 | { 302 | "ActionRequest", 303 | "Chat", 304 | "Context", 305 | "InternalSearchQuery", 306 | "InternalSearchResult", 307 | "Disengaged", 308 | "InternalLoaderMessage", 309 | "Progress", 310 | "RenderCardRequest", 311 | "AdsQuery", 312 | "SemanticSerp", 313 | "GenerateContentQuery", 314 | "SearchQuery" 315 | }; 316 | } 317 | } 318 | 319 | public class BingChatMessage 320 | { 321 | [JsonPropertyName("locale")] public string Locale { get; set; } 322 | [JsonPropertyName("market")] public string Market { get; set; } 323 | [JsonPropertyName("region")] public string Region { get; set; } 324 | [JsonPropertyName("location")] public string Location { get; set; } 325 | [JsonPropertyName("author")] public string Author { get; set; } 326 | [JsonPropertyName("inputMethod")] public string InputMethod { get; set; } 327 | [JsonPropertyName("messageType")] public string MessageType { get; set; } 328 | [JsonPropertyName("text")] public string Text { get; set; } 329 | 330 | [JsonConstructor] 331 | public BingChatMessage(string locale, string market, string region, string location, string messageType, string text) 332 | { 333 | Author = "user"; 334 | InputMethod = "Keyboard"; 335 | Locale = locale; 336 | Market = market; 337 | Region = region; 338 | Location = location; 339 | MessageType = messageType; 340 | Text = text; 341 | } 342 | } 343 | 344 | public class BingChatParticipant 345 | { 346 | [JsonInclude] public string Id { get; } 347 | 348 | public BingChatParticipant(string id) 349 | { 350 | this.Id = id; 351 | } 352 | } -------------------------------------------------------------------------------- /MeowBot/Services/OpenAi/OpenAiChatService.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Text; 3 | using OpenAI; 4 | using OpenAI.Chat; 5 | using OpenAI.Models; 6 | 7 | namespace MeowBot.Services.OpenAi 8 | { 9 | internal class OpenAiChatService : AiChatServiceBase 10 | { 11 | /// 12 | /// OpenAi服务下,非白名单用户能够拥有的最大会话上下文数量 13 | /// 14 | private const int MaxHistoryCount = 50; 15 | 16 | 17 | public static bool CheckConfig(AppConfig config, out string? reason) 18 | { 19 | if (string.IsNullOrWhiteSpace(config.OpenAiApiKey)) 20 | { 21 | reason = $"请指定机器人 API Key({nameof(config.OpenAiApiKey)})"; 22 | return false; 23 | } 24 | 25 | reason = null; 26 | return true; 27 | } 28 | 29 | /// 30 | /// 用户配置的对话温度 31 | /// 32 | private double Temperature { get; set; } 33 | 34 | /// 35 | /// 用户配置的系统指令 36 | /// 37 | private string SystemMessage { get; set; } 38 | 39 | 40 | private readonly OpenAIClient m_Client; 41 | private readonly List m_MessageListBuffer = new(); 42 | private readonly Queue m_ChatHistory = new(); 43 | private readonly AppConfig m_Config; 44 | 45 | internal override async Task AskAsync(AskCommandArgsModel askCommandArgs, Func sendMessageCallback) 46 | { 47 | var msgTxt = askCommandArgs.MsgTxt; 48 | var userNickname = askCommandArgs.UserNickname; 49 | var userId = askCommandArgs.UserId; 50 | 51 | var hasContextTrimmed = m_ChatHistory.Count > MaxHistoryCount && !m_Config.AccountWhiteList.Contains(userId); 52 | 53 | if (hasContextTrimmed) 54 | { 55 | while (m_ChatHistory.Count > MaxHistoryCount) 56 | { 57 | m_ChatHistory.Dequeue(); 58 | } 59 | await Console.Out.WriteLineAsync($"> 已裁剪用户 {userNickname}({userId}) 的多余对话上下文信息"); 60 | } 61 | 62 | m_MessageListBuffer.Clear(); 63 | m_MessageListBuffer.Add(new(Role.System, SystemMessage)); 64 | m_MessageListBuffer.AddRange(AppConfig.SystemCommand.Select(sysMsg => new Message(Role.System, sysMsg))); 65 | m_MessageListBuffer.AddRange(m_ChatHistory); 66 | 67 | try 68 | { 69 | var ask = new Message(Role.User, msgTxt); 70 | m_MessageListBuffer.Add(ask); 71 | 72 | var result = await m_Client.ChatEndpoint.GetCompletionAsync(new(m_MessageListBuffer, model: Model.GPT3_5_Turbo, Temperature)); 73 | 74 | Debug.WriteLine("OpenAI OK"); 75 | 76 | var answer = result.Choices[0].Message; 77 | var openAiResult = new StringBuilder(answer.Content); 78 | 79 | if (hasContextTrimmed) 80 | openAiResult.Append(" (已裁剪对话上下文)"); 81 | 82 | m_ChatHistory.Enqueue(ask); 83 | m_ChatHistory.Enqueue(answer); 84 | 85 | Debug.WriteLine("GoCqHttp OK"); 86 | await sendMessageCallback(openAiResult.ToString(), true); 87 | return null; 88 | } 89 | catch (Exception ex) 90 | { 91 | if (ex.Message.Contains("This model's maximum context length is ")) 92 | { 93 | await sendMessageCallback($"请求失败,对话上下文超过了模型支持的长度,请使用 #reset 重置机器人\n{ex.Message}", true); 94 | return null; 95 | } 96 | else 97 | { 98 | return ex; 99 | } 100 | } 101 | } 102 | 103 | public override async Task HandlePotentialUserCommands(string msgTxt, AppConfig appConfig, long userId, Func sendMessageCallback) 104 | { 105 | switch (msgTxt) 106 | { 107 | case "#help": 108 | 109 | var chatGptHelpText = 110 | $""" 111 | ChatGPT 操作指令: 112 | ---------------------------------- 113 | #temperature:<设置AI的应答气温(0~1),越高的值会带来越随机的结果,反之则会带来越确定以及集中的结果,并重置对话> 114 | #role:<切换一个的GPT角色预设,并重置对话> 115 | #custom-role:<通过传入用于初始化GPT自我角色的提示性信息来自定义角色性格,并重置对话> 116 | #reset:重置聊天对话的上下文信息 117 | #history:检查当前已产生的历史记录数量 118 | ---------------------------------- 119 | !注意, 普通用户最多记忆{MaxHistoryCount}条聊天对话的上下文信息 120 | ---------------------------------- 121 | 以下是所有可用的GPT角色预设: 122 | 123 | """; 124 | 125 | 126 | StringBuilder sb = new(chatGptHelpText); 127 | foreach (var builtinRolesKey in appConfig.BuiltinRoles.Keys) 128 | { 129 | sb.AppendLine($"\t{builtinRolesKey}"); 130 | } 131 | 132 | await sendMessageCallback.Invoke(sb.ToString(), true); 133 | break; 134 | case "#reset": 135 | 136 | m_ChatHistory.Clear(); 137 | await sendMessageCallback.Invoke("> ChatGPT: 会话已重置", true); 138 | 139 | break; 140 | case var _ when msgTxt.StartsWith("#temperature:"): 141 | 142 | var potentialTemperature = msgTxt[13..].Trim(); 143 | if (!double.TryParse(potentialTemperature, out var validFloatValue) || validFloatValue is < 0 or > 1) 144 | { 145 | await sendMessageCallback.Invoke($"> ChatGPT: 无法将({potentialTemperature})识别为范围在(0 ~ 1)中的浮点数!", true); 146 | break; 147 | } 148 | 149 | Temperature = validFloatValue; 150 | m_ChatHistory.Clear(); 151 | await sendMessageCallback.Invoke($"> ChatGPT: 会话温度已更新: {validFloatValue:N2}", true); 152 | 153 | break; 154 | case var _ when msgTxt.StartsWith("#role:"): 155 | 156 | var role = msgTxt[6..].Trim(); 157 | if (appConfig.BuiltinRoles.TryGetValue(role, out var gptRoleSystemMessage)) 158 | { 159 | SystemMessage = gptRoleSystemMessage; 160 | m_ChatHistory.Clear(); 161 | await sendMessageCallback.Invoke($"> ChatGPT: 会话角色已更新: {role}", true); 162 | } 163 | else 164 | { 165 | await sendMessageCallback.Invoke($"> ChatGPT: 找不到所选的角色", true); 166 | } 167 | 168 | break; 169 | case var _ when msgTxt.StartsWith("#custom-role:"): 170 | 171 | gptRoleSystemMessage = msgTxt[13..]; 172 | SystemMessage = gptRoleSystemMessage; 173 | m_ChatHistory.Clear(); 174 | await sendMessageCallback.Invoke($"> ChatGPT: 自定义角色已更新", true); 175 | 176 | break; 177 | case "#history": 178 | 179 | await sendMessageCallback.Invoke($"> ChatGPT: 历史记录:{m_ChatHistory.Count}条", true); 180 | var inWhiteList = appConfig.AccountWhiteList.Contains(userId); 181 | if (!inWhiteList) 182 | await sendMessageCallback.Invoke($"> ChatGPT: (您的聊天会话最多保留 {MaxHistoryCount} 条消息)", false); 183 | 184 | break; 185 | default: 186 | return false; 187 | } 188 | 189 | return true; 190 | } 191 | 192 | public override ValueTask DisposeAsync() 193 | { 194 | // m_Client.Dispose(); 195 | return ValueTask.CompletedTask; 196 | } 197 | 198 | 199 | public OpenAiChatService(AppConfig config) : base(config) 200 | { 201 | m_Config = config; 202 | m_Client = new(new(config.OpenAiApiKey), new(config.ApiHost ?? AppConfig.DefaultApiHost)); 203 | SystemMessage = string.IsNullOrWhiteSpace(config.GptRoleInitText) ? AppConfig.MeowBotRoleText : config.GptRoleInitText; 204 | Temperature = .5; 205 | } 206 | } 207 | } -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "7.0.0", 4 | "rollForward": "latestMajor", 5 | "allowPrerelease": true 6 | } 7 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # MeowBot 2 | 3 | ## 摘要 4 | 5 | 此项目使用 [.NET 7](https://learn.microsoft.com/zh-cn/dotnet/core/whats-new/dotnet-7) 来调用 `OpenAI` 的 `ChatGpt对话Api` 或使用 [SignalR](https://learn.microsoft.com/zh-cn/aspnet/signalr/overview/getting-started/introduction-to-signalr) 来访问 `New Bing` 的 `对话/查询Api`,通过 [EleCho.GoCqHttpSdk](https://github.com/OrgEleCho/EleCho.GoCqHttpSdk) 来和 [go-cqhttp] 客户端通信处理消息收发。 6 | 7 | ## 介绍 8 | 9 | 此项目为一个QQ机器人,用于在群组内提供便捷的Ai对话应答服务,此机器人的详细功能如下: 10 | 11 | ### 共通服务 12 | 13 | 服务类型|明细 14 | :-|:- 15 | 流量管理|对于非白名单用户,Bot会根据应用程序配置的设置限制用户每秒可以使用GPT服务的次数 16 | 模式切换|@此Bot并且输入 `#chat:GPT` 或 `#chat:NewBing(仅当配置时)` 在两个对话模型之间切换 17 | 18 | ### OpenAI / ChatGPT 对话应答服务 19 | 20 | 服务类型|明细 21 | :-|:- 22 | Ai对话应答服务|群员可以直接@此Bot并且提问,Bot会通过提供的 `OpenAi API Key` 访问 `Open AI的端口` 来生成回应 23 | 上下文记忆|对于非白名单用户,Bot会提供最大50条会话上下文的上下文记忆服务 24 | 用户命令: `#help` | @此Bot并且输入 `#help` 来获得Bot支持的所有功能解释 25 | 用户命令: `#reset` | @此Bot并且输入 `#reset` 来重置对话的上下文信息 26 | 用户命令: `#temperature` | @此Bot并且输入 `#temperature:<温度信息(0~1)>` 来调整AI的应答温度,越高的值会带来越随机的结果,反之则会带来越确定以及集中的结果 27 | 用户命令: `#role` | @此Bot并且输入 `#role:<角色信息>` 来从应用程序配置里预设的几种角色信息之中选择一种作为Bot回应该用户时的角色信息 28 | 用户命令: `#custom-role` | @此Bot并且输入 `#custom-role:<自定义角色信息>` 来将用户提供的文本作为Bot回应该用户时的角色信息 29 | 用户命令: `#history` | @此Bot并且输入 `#history` 来显示该用户当前的对话上下文记忆数量 30 | 31 | ### 微软 / New Bing 对话应答/查询服务 32 | 33 | 服务类型|明细 34 | :-|:- 35 | Ai对话应答/查询服务|群员可以直接@此Bot并且提问,Bot会通过 `New Bing` 的 `对话/查询Api` 来生成回应 36 | 用户命令: `#help` |@此Bot并且输入 `#help` 来获得Bot支持的所有功能解释 37 | 用户命令: `#reset` |@此Bot并且输入 `#reset` 来重置对话的上下文信息 38 | 用户命令: `#style` |@此Bot并且输入 `#style` 来从三种必应的应答模式间切换:`平衡`, `创造`, `精准` 39 | 40 | 当首次启动此项目时,会自动在项目应用程序目录产生应用**程序配置文件** `AppConfig.json`,以下是每个条目的介绍: 41 | 42 | 条目|名称|介绍 43 | :-|:-|:- 44 | `NewBingSupport` |启用New Bing|为Bot启用基于`New Bing`的对话应答/查询服务,需要配置 `NewBingCookie` 45 | `NewBingCookie` |New Bing Cookie|`New Bing`对话应答服务所依赖的`Cookie` 46 | `OpenAiApiKey` |OpenAI API 密钥|用于调用 OpenAI API 的密钥 47 | `BotWebSocketUri` |go-cqhttp 通信 WebSocket 地址|此应用程序通过 WebSocket 来和 go-cqhttp 通信,对于默认本机通信,使用 `ws://localhost:8080` 48 | `ApiHost` |OpenAI API 主机|当需要使用 `api.openai.com` 以外的主机来调用 OpenAI 的 API 时,设置此项 49 | `GptModel` |覆写OpenAI GPT模型|当调用 OpenAI 的 API 需要使用 `gpt-3.5-turbo` 以外的模型时,设置此项 50 | `UsageLimitTime` |非白名单用户限制(秒)|设定非白名单用户在多少秒内能够使用多少次API 51 | `UsageLimitCount` |非白名单用户限制(次数)|设定非白名单用户在多少秒内能够使用多少次API 52 | `AccountWhiteList` |白名单用户 QQ 号|此名单内的 QQ 号不受流量管理以及 50 条上下文记忆的限制 53 | `AccountBlackList` |黑名单用户 QQ 号|此名单内的 QQ 号无法获得服务 54 | `GptRoleInitText` |覆写 GPT 角色语句|在用户使用 GPT 服务时,如果需要使用 `你是一个基于GPT的会话机器人。如果用户询问你一个植根于真理的问题,你会提供解答。如果用户希望你对他们提供的信息发表看法或表达态度,你会礼貌的的拒绝他,并且表示这不是你的设计目的。` 以外的角色初始化语句时,设置此项 55 | `SystemCommand` |额外系统指令|需要给GPT会话添加其他系统语句的情况下,设置此项 56 | `BuiltinRoles` |内置角色|需要为用户提供一系列的预设角色时,设置此项 57 | 58 | ## 关于 EleCho.GoCqHttpSdk 框架 59 | 60 | EleCho.GoCqHttpSdk 使用教程: [使用 C# 和 Go-CqHttp 编写 QQ 机器人](https://www.bilibili.com/video/BV1P24y1V7XZ) 61 | --------------------------------------------------------------------------------