├── .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