-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
1488 lines (1262 loc) · 41.1 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package utils
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/abadojack/whatlanggo"
"github.com/google/uuid"
"github.com/hoshinonyaruko/gensokyo-llm/acnode"
"github.com/hoshinonyaruko/gensokyo-llm/config"
"github.com/hoshinonyaruko/gensokyo-llm/fmtf"
"github.com/hoshinonyaruko/gensokyo-llm/hunyuan"
"github.com/hoshinonyaruko/gensokyo-llm/server"
"github.com/hoshinonyaruko/gensokyo-llm/structs"
)
// ResponseData 是用于解析HTTP响应的结构体
type ResponseData struct {
Data struct {
MessageID int64 `json:"message_id"`
} `json:"data"`
}
// MessageIDInfo 代表消息ID及其到期时间
type MessageIDInfo struct {
MessageID int64 // 消息ID
Expires time.Time // 到期时间
}
// UserIDMessageIDs 存储每个用户ID对应的消息ID数组及其有效期
var UserIDMessageIDs = make(map[int64][]MessageIDInfo)
var muUserIDMessageIDs sync.RWMutex // 用于UserIDMessageIDs的读写锁
var (
baseURLMap = make(map[string]string)
baseURLMapMu sync.Mutex
)
// 结构体用于解析 JSON 响应
type loginInfoResponse struct {
Status string `json:"status"`
Retcode int `json:"retcode"`
Data struct {
UserID int64 `json:"user_id"`
Nickname string `json:"nickname"`
} `json:"data"`
}
// 构造 URL 并请求数据
func FetchAndStoreUserIDs() {
httpPaths := config.GetHttpPaths()
for _, baseURL := range httpPaths {
url := baseURL + "/get_login_info"
resp, err := http.Get(url)
if err != nil {
fmtf.Printf("Error fetching login info from %s: %v", url, err)
continue
}
defer resp.Body.Close()
var result loginInfoResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
fmtf.Printf("Error decoding response from %s: %v", url, err)
continue
}
if result.Retcode == 0 && result.Status == "ok" {
fmtf.Printf("成功绑定机器人selfid[%v]onebot api baseURL[%v]", result.Data.UserID, baseURL)
baseURLMapMu.Lock()
useridstr := strconv.FormatInt(result.Data.UserID, 10)
baseURLMap[useridstr] = baseURL
baseURLMapMu.Unlock()
}
}
}
// GetBaseURLByUserID 通过 user_id 获取 baseURL
func GetBaseURLByUserID(userID string) (string, bool) {
baseURLMapMu.Lock()
defer baseURLMapMu.Unlock()
url, exists := baseURLMap[userID]
return url, exists
}
func GenerateUUID() string {
return uuid.New().String()
}
func PrintChatProRequest(request *hunyuan.ChatProRequest) {
// 打印Messages
for i, msg := range request.Messages {
fmtf.Printf("Message %d:\n", i)
fmtf.Printf("Content: %s\n", *msg.Content)
fmtf.Printf("Role: %s\n", *msg.Role)
}
}
func PrintChatStdRequest(request *hunyuan.ChatStdRequest) {
// 打印Messages
for i, msg := range request.Messages {
fmtf.Printf("Message %d:\n", i)
fmtf.Printf("Content: %s\n", *msg.Content)
fmtf.Printf("Role: %s\n", *msg.Role)
}
}
func PrintChatCompletionsRequest(request *hunyuan.ChatCompletionsRequest) {
// 打印Messages
for i, msg := range request.Messages {
fmtf.Printf("Message %d:\n", i)
fmtf.Printf("Content: %s\n", *msg.Content)
fmtf.Printf("Role: %s\n", *msg.Role)
}
}
// contains 检查一个字符串切片是否包含一个特定的字符串
func Contains(slice []string, item string) bool {
for _, a := range slice {
if a == item {
return true
}
}
return false
}
// 获取复合键
func GetKey(groupid int64, userid int64) string {
return fmt.Sprintf("%d.%d", groupid, userid)
}
// 随机的分布发送
func ContainsRune(slice []rune, value rune, groupid int64) bool {
var probability int
if groupid == 0 {
// 获取概率百分比
probability = config.GetSplitByPuntuations()
} else {
// 获取概率百分比
probability = config.GetSplitByPuntuationsGroup()
}
for _, item := range slice {
if item == value {
// 将概率转换为0到1之间的浮点数
probabilityPercentage := float64(probability) / 100.0
// 生成一个0到1之间的随机浮点数
randomValue := rand.Float64()
// 如果随机数小于或等于概率,则返回true
return randomValue <= probabilityPercentage
}
}
return false
}
// 取出ai回答
func ExtractEventDetails(eventData map[string]interface{}) (string, structs.UsageInfo) {
var responseTextBuilder strings.Builder
var totalUsage structs.UsageInfo
// 提取使用信息
if usage, ok := eventData["Usage"].(map[string]interface{}); ok {
var usageInfo structs.UsageInfo
if promptTokens, ok := usage["PromptTokens"].(float64); ok {
usageInfo.PromptTokens = int(promptTokens)
}
if completionTokens, ok := usage["CompletionTokens"].(float64); ok {
usageInfo.CompletionTokens = int(completionTokens)
}
totalUsage.PromptTokens += usageInfo.PromptTokens
totalUsage.CompletionTokens += usageInfo.CompletionTokens
}
// 提取AI助手的回复
if choices, ok := eventData["Choices"].([]interface{}); ok {
for _, choice := range choices {
if choiceMap, ok := choice.(map[string]interface{}); ok {
if delta, ok := choiceMap["Delta"].(map[string]interface{}); ok {
if role, ok := delta["Role"].(string); ok && role == "assistant" {
if content, ok := delta["Content"].(string); ok {
responseTextBuilder.WriteString(content)
}
}
}
}
}
}
return responseTextBuilder.String(), totalUsage
}
func SendGroupMessage(groupID int64, userID int64, message string, selfid string) error {
//TODO: 用userid作为了echo,在ws收到回调信息的时候,加入到全局撤回数组,AddMessageID,实现撤回
if server.IsSelfIDExists(selfid) {
// 创建消息结构体
msg := map[string]interface{}{
"action": "send_group_msg",
"params": map[string]interface{}{
"group_id": groupID,
"user_id": userID,
"message": message,
},
"echo": userID,
}
// 发送消息
return server.SendMessageBySelfID(selfid, msg)
}
var baseURL string
if len(config.GetHttpPaths()) > 0 {
baseURL, _ = GetBaseURLByUserID(selfid)
} else {
// 获取基础URL
baseURL = config.GetHttpPath() // 假设config.getHttpPath()返回基础URL
}
// 构建完整的URL
baseURL = baseURL + "/send_group_msg"
// 获取PathToken并检查其是否为空
pathToken := config.GetPathToken()
// 使用net/url包构建URL
u, err := url.Parse(baseURL)
if err != nil {
panic("URL parsing failed: " + err.Error())
}
// 添加access_token参数
query := u.Query()
if pathToken != "" {
query.Set("access_token", pathToken)
}
u.RawQuery = query.Encode()
if config.GetSensitiveModeType() == 1 {
message = acnode.CheckWordOUT(message)
}
// 去除末尾的换行符 不去除会导致不好看
message = removeTrailingCRLFs(message)
// 繁体转换简体 安全策略 防止用户诱导ai发繁体绕过替换规则
message, err = ConvertTraditionalToSimplified(message)
if err != nil {
fmtf.Printf("繁体转换简体失败:%v", err)
}
// 构造请求体
requestBody, err := json.Marshal(map[string]interface{}{
"group_id": groupID,
"user_id": userID,
"message": message,
})
fmtf.Printf("发群信息请求:%v", string(requestBody))
fmtf.Printf("实际发送信息:%v", message)
if err != nil {
return fmtf.Errorf("failed to marshal request body: %w", err)
}
// 发送POST请求
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return fmtf.Errorf("failed to send POST request: %w", err)
}
defer resp.Body.Close()
// 检查响应状态
if resp.StatusCode != http.StatusOK {
return fmtf.Errorf("received non-OK response status: %s", resp.Status)
}
// 读取响应体
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// 解析响应体以获取message_id
var responseData ResponseData
if err := json.Unmarshal(bodyBytes, &responseData); err != nil {
return fmt.Errorf("failed to unmarshal response data: %w", err)
}
messageID := responseData.Data.MessageID
// 添加messageID到全局变量
AddMessageID(userID, messageID)
// 输出响应体,这一步是可选的
fmt.Println("Response Body:", string(bodyBytes))
return nil
}
func SendGroupMessageMdPromptKeyboard(groupID int64, userID int64, message string, selfid string, newmsg string, response string, promptstr string) error {
//TODO: 用userid作为了echo,在ws收到回调信息的时候,加入到全局撤回数组,AddMessageID,实现反向ws连接时候的撤回
if server.IsSelfIDExists(selfid) {
// 创建消息结构体
msg := map[string]interface{}{
"action": "send_group_msg",
"params": map[string]interface{}{
"group_id": groupID,
"user_id": userID,
"message": message,
},
"echo": userID,
}
// 发送消息
return server.SendMessageBySelfID(selfid, msg)
}
// 获取基础URL
baseURL := config.GetHttpPath() // 假设config.getHttpPath()返回基础URL
// 构建完整的URL
baseURL = baseURL + "/send_group_msg"
// 获取PathToken并检查其是否为空
pathToken := config.GetPathToken()
// 使用net/url包构建URL
u, err := url.Parse(baseURL)
if err != nil {
panic("URL parsing failed: " + err.Error())
}
// 添加access_token参数
query := u.Query()
if pathToken != "" {
query.Set("access_token", pathToken)
}
u.RawQuery = query.Encode()
if config.GetSensitiveModeType() == 1 {
message = acnode.CheckWordOUT(message)
}
// 去除末尾的换行符 不去除会导致不好看
message = removeTrailingCRLFs(message)
// 繁体转换简体 安全策略 防止用户诱导ai发繁体绕过替换规则
message, err = ConvertTraditionalToSimplified(message)
if err != nil {
fmtf.Printf("繁体转换简体失败:%v", err)
}
// 首先获取当前的keyboard
var promptkeyboard []string
if !config.GetUseAIPromptkeyboard() {
promptkeyboard = config.GetPromptkeyboard()
} else {
fmtf.Printf("ai生成气泡:%v", "Q"+newmsg+"A"+response)
promptkeyboard = GetPromptKeyboardAI("Q"+newmsg+"A"+response, promptstr)
}
// 使用acnode.CheckWordOUT()过滤promptkeyboard中的每个字符串
for i, item := range promptkeyboard {
promptkeyboard[i] = acnode.CheckWordOUT(item)
}
// 这里把message构造成一个cq,md码
// 构建Markdown内容,对promptkeyboard的内容进行URL编码
// mdContent := fmt.Sprintf(
// "%s\r[%s](mqqapi://aio/inlinecmd?command=%s&reply=true&enter=true)\r[%s](mqqapi://aio/inlinecmd?command=%s&reply=true&enter=true)\r[%s](mqqapi://aio/inlinecmd?command=%s&reply=true&enter=true)\r",
// //message,
// "123",
// promptkeyboard[0], url.QueryEscape(promptkeyboard[0]),
// promptkeyboard[1], url.QueryEscape(promptkeyboard[1]),
// promptkeyboard[2], url.QueryEscape(promptkeyboard[2]),
// )
mdContent := message
fmt.Println(mdContent)
// 构建Buttons
// buttons := make([]structs.Button, len(promptkeyboard))
// for i, label := range []string{"重置", "撤回", "重发"} {
// buttons[i] = structs.Button{
// ID: fmt.Sprintf("%d", i+1),
// RenderData: structs.RenderData{
// Label: label,
// VisitedLabel: label,
// Style: 1,
// },
// Action: structs.Action{
// Type: 1,
// Permission: structs.Permission{
// Type: 2,
// SpecifyRoleIDs: []string{"1", "2", "3"},
// },
// Data: label,
// UnsupportTips: "请升级新版手机QQ",
// },
// }
// }
// // 构建完整的PromptKeyboardMarkdown对象
// promptKeyboardMd := structs.PromptKeyboardMarkdown{
// Markdown: markdown,
// Keyboard: structs.Keyboard{
// Content: structs.KeyboardContent{
// Rows: []structs.Row{{Buttons: buttons}},
// },
// },
// Content: "keyboard",
// // MsgID: "123",
// // Timestamp: fmt.Sprintf("%d", time.Now().Unix()),
// // MsgType: 2,
// }
// 构建Buttons
buttons := []structs.Button{}
// 添加promptkeyboard的按钮,每个按钮一行
for i, label := range promptkeyboard {
buttons = append(buttons, structs.Button{
ID: fmt.Sprintf("%d", i+1),
RenderData: structs.RenderData{
Label: label,
VisitedLabel: label,
Style: 1,
},
Action: structs.Action{
Type: 2,
Permission: structs.Permission{
Type: 2,
SpecifyRoleIDs: []string{"1", "2", "3"},
},
Data: label,
UnsupportTips: "请升级新版手机QQ",
Enter: true,
Reply: true,
},
})
}
// 添加"重置", "撤回", "重发"按钮,它们在一个单独的行
rowWithThreeButtons := []structs.Button{}
for i, label := range []string{"重置", "忽略", "重发"} {
rowWithThreeButtons = append(rowWithThreeButtons, structs.Button{
ID: fmt.Sprintf("%d", i+4), // 确保ID不重复
RenderData: structs.RenderData{
Label: label,
VisitedLabel: label,
Style: 1,
},
Action: structs.Action{
Type: 1,
Permission: structs.Permission{
Type: 2,
SpecifyRoleIDs: []string{"1", "2", "3"},
},
Data: label,
UnsupportTips: "请升级新版手机QQ",
},
})
}
// 构建完整的PromptKeyboardMarkdown对象
promptKeyboardMd := structs.PromptKeyboardMarkdown{
Markdown: structs.Markdown{Content: mdContent},
Keyboard: structs.Keyboard{
Content: structs.KeyboardContent{
Rows: []structs.Row{
{Buttons: []structs.Button{buttons[0]}},
{Buttons: []structs.Button{buttons[1]}},
{Buttons: []structs.Button{buttons[2]}},
{Buttons: rowWithThreeButtons},
},
},
},
Content: "keyboard",
MsgID: "123",
Timestamp: fmt.Sprintf("%d", time.Now().Unix()),
MsgType: 2,
}
// 序列化成JSON
mdContentBytes, err := json.Marshal(promptKeyboardMd)
if err != nil {
fmt.Printf("Error marshaling to JSON: %v", err)
return nil
}
// 编码成Base64
encoded := base64.StdEncoding.EncodeToString(mdContentBytes)
segmentContent := "[CQ:markdown,data=base64://" + encoded + "]"
// 构造请求体
requestBody, err := json.Marshal(map[string]interface{}{
"group_id": groupID,
"user_id": userID,
"message": segmentContent,
})
fmtf.Printf("发群信息请求:%v", string(requestBody))
fmtf.Printf("实际发送信息:%v", message)
if err != nil {
return fmtf.Errorf("failed to marshal request body: %w", err)
}
// 发送POST请求
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return fmtf.Errorf("failed to send POST request: %w", err)
}
defer resp.Body.Close()
// 检查响应状态
if resp.StatusCode != http.StatusOK {
return fmtf.Errorf("received non-OK response status: %s", resp.Status)
}
// 读取响应体
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// 解析响应体以获取message_id
var responseData ResponseData
if err := json.Unmarshal(bodyBytes, &responseData); err != nil {
return fmt.Errorf("failed to unmarshal response data: %w", err)
}
messageID := responseData.Data.MessageID
// 添加messageID到全局变量
AddMessageID(userID, messageID)
// 输出响应体,这一步是可选的
fmt.Println("Response Body:", string(bodyBytes))
return nil
}
func SendPrivateMessage(UserID int64, message string, selfid string) error {
if server.IsSelfIDExists(selfid) {
// 创建消息结构体
msg := map[string]interface{}{
"action": "send_private_msg",
"params": map[string]interface{}{
"user_id": UserID,
"message": message,
},
"echo": UserID,
}
// 发送消息
return server.SendMessageBySelfID(selfid, msg)
}
var baseURL string
if len(config.GetHttpPaths()) > 0 {
baseURL, _ = GetBaseURLByUserID(selfid)
} else {
// 获取基础URL
baseURL = config.GetHttpPath() // 假设config.getHttpPath()返回基础URL
}
// 构建完整的URL
baseURL = baseURL + "/send_private_msg"
// 获取PathToken并检查其是否为空
pathToken := config.GetPathToken()
// 使用net/url包构建URL
u, err := url.Parse(baseURL)
if err != nil {
panic("URL parsing failed: " + err.Error())
}
// 添加access_token参数
query := u.Query()
if pathToken != "" {
query.Set("access_token", pathToken)
}
u.RawQuery = query.Encode()
if config.GetSensitiveModeType() == 1 {
message = acnode.CheckWordOUT(message)
}
// 去除末尾的换行符 不去除会导致不好看
message = removeTrailingCRLFs(message)
// 繁体转换简体 安全策略 防止用户诱导ai发繁体绕过替换规则
message, err = ConvertTraditionalToSimplified(message)
if err != nil {
fmtf.Printf("繁体转换简体失败:%v", err)
}
// 构造请求体
requestBody, err := json.Marshal(map[string]interface{}{
"user_id": UserID,
"message": message,
})
if err != nil {
return fmtf.Errorf("failed to marshal request body: %w", err)
}
fmtf.Printf("实际发送信息:%v", message)
// 发送POST请求
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return fmtf.Errorf("failed to send POST request: %w", err)
}
defer resp.Body.Close()
// 检查响应状态
if resp.StatusCode != http.StatusOK {
return fmtf.Errorf("received non-OK response status: %s", resp.Status)
}
// 读取响应体
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// 解析响应体以获取message_id
var responseData ResponseData
if err := json.Unmarshal(bodyBytes, &responseData); err != nil {
return fmt.Errorf("failed to unmarshal response data: %w", err)
}
messageID := responseData.Data.MessageID
// 添加messageID到全局变量
AddMessageID(UserID, messageID)
// 输出响应体,这一步是可选的
fmt.Println("Response Body:", string(bodyBytes))
return nil
}
func SendPrivateMessageRaw(UserID int64, message string, selfid string) error {
if server.IsSelfIDExists(selfid) {
// 创建消息结构体
msg := map[string]interface{}{
"action": "send_private_msg",
"params": map[string]interface{}{
"user_id": UserID,
"message": message,
},
"echo": UserID,
}
// 发送消息
return server.SendMessageBySelfID(selfid, msg)
}
var baseURL string
if len(config.GetHttpPaths()) > 0 {
baseURL, _ = GetBaseURLByUserID(selfid)
} else {
// 获取基础URL
baseURL = config.GetHttpPath() // 假设config.getHttpPath()返回基础URL
}
// 构建完整的URL
baseURL = baseURL + "/send_private_msg"
// 获取PathToken并检查其是否为空
pathToken := config.GetPathToken()
// 使用net/url包构建URL
u, err := url.Parse(baseURL)
if err != nil {
panic("URL parsing failed: " + err.Error())
}
// 添加access_token参数
query := u.Query()
if pathToken != "" {
query.Set("access_token", pathToken)
}
u.RawQuery = query.Encode()
// 构造请求体
requestBody, err := json.Marshal(map[string]interface{}{
"user_id": UserID,
"message": message,
})
if err != nil {
return fmtf.Errorf("failed to marshal request body: %w", err)
}
// 发送POST请求
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return fmtf.Errorf("failed to send POST request: %w", err)
}
defer resp.Body.Close()
// 检查响应状态
if resp.StatusCode != http.StatusOK {
return fmtf.Errorf("received non-OK response status: %s", resp.Status)
}
// 读取响应体
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// 解析响应体以获取message_id
var responseData ResponseData
if err := json.Unmarshal(bodyBytes, &responseData); err != nil {
return fmt.Errorf("failed to unmarshal response data: %w", err)
}
messageID := responseData.Data.MessageID
// 添加messageID到全局变量
AddMessageID(UserID, messageID)
// 输出响应体,这一步是可选的
fmt.Println("Response Body:", string(bodyBytes))
return nil
}
func SendPrivateMessageSSE(UserID int64, message structs.InterfaceBody) error {
// 获取基础URL
baseURL := config.GetHttpPath() // 假设config.GetHttpPath()返回基础URL
// 构建完整的URL
baseURL = baseURL + "/send_private_msg_sse"
// 获取PathToken并检查其是否为空
pathToken := config.GetPathToken()
// 使用net/url包构建URL
u, err := url.Parse(baseURL)
if err != nil {
panic("URL parsing failed: " + err.Error())
}
// 添加access_token参数
query := u.Query()
if pathToken != "" {
query.Set("access_token", pathToken)
}
u.RawQuery = query.Encode()
// 调试用的
if config.GetPrintHanming() {
fmtf.Printf("流式信息替换前:%v", message.Content)
}
// 检查是否需要启用敏感词过滤
if config.GetSensitiveModeType() == 1 && message.Content != "" {
message.Content = acnode.CheckWordOUT(message.Content)
}
// 调试用的
if config.GetPrintHanming() {
fmtf.Printf("流式信息替换后:%v", message.Content)
}
// 去除末尾的换行符 不去除会导致sse接口始终等待
message.Content = removeTrailingCRLFs(message.Content)
// 繁体转换简体 安全策略 防止用户诱导ai发繁体绕过替换规则
message.Content, err = ConvertTraditionalToSimplified(message.Content)
if err != nil {
fmtf.Printf("繁体转换简体失败:%v", err)
}
if message.Content == "" {
message.Content = " "
fmtf.Printf("过滤空SendPrivateMessageSSE,可能是llm api只发了换行符.")
return nil
}
fmtf.Printf("实际发送信息:%v", message.Content)
// 构造请求体,包括InterfaceBody
requestBody, err := json.Marshal(map[string]interface{}{
"user_id": UserID,
"message": message,
})
if err != nil {
return fmtf.Errorf("failed to marshal request body: %w", err)
}
// 发送POST请求
resp, err := http.Post(u.String(), "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return fmtf.Errorf("failed to send POST request: %w", err)
}
defer resp.Body.Close()
// 检查响应状态
if resp.StatusCode != http.StatusOK {
return fmtf.Errorf("received non-OK response status: %s", resp.Status)
}
// 读取响应体
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// 解析响应体以获取message_id
var responseData ResponseData
if err := json.Unmarshal(bodyBytes, &responseData); err != nil {
return fmt.Errorf("failed to unmarshal response data: %w", err)
}
messageID := responseData.Data.MessageID
// 添加messageID到全局变量
AddMessageID(UserID, messageID)
// 输出响应体,这一步是可选的
fmt.Println("Response Body:", string(bodyBytes))
return nil
}
// removeTrailingCRLFs 移除字符串末尾的所有CRLF换行符
func removeTrailingCRLFs(input string) string {
// 将字符串转换为字节切片
byteMessage := []byte(input)
// CRLF的字节表示
crlf := []byte{'\r', '\n'}
// 循环移除末尾的CRLF
for bytes.HasSuffix(byteMessage, crlf) {
byteMessage = bytes.TrimSuffix(byteMessage, crlf)
}
// LFLF的字节表示
lflf := []byte{'\n', '\n'}
// 循环移除末尾的LFLF
for bytes.HasSuffix(byteMessage, lflf) {
byteMessage = bytes.TrimSuffix(byteMessage, lflf)
}
// 将处理后的字节切片转换回字符串
return string(byteMessage)
}
// ReverseString 颠倒给定字符串中的字符顺序
func ReverseString(s string) string {
// // 将字符串转换为rune切片,以便处理多字节字符
// runes := []rune(s)
// for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
// // 交换前后对应的字符
// runes[i], runes[j] = runes[j], runes[i]
// }
// // 将颠倒后的rune切片转换回字符串
// return string(runes)
return "####" + s + "####"
}
// RemoveBracketsContent 接收一个字符串,并移除所有[[...]]的内容
func RemoveBracketsContent(input string) string {
// 编译一个正则表达式,用于匹配[[任意字符]]的模式
re := regexp.MustCompile(`\[\[.*?\]\]`)
// 使用正则表达式的ReplaceAllString方法删除匹配的部分
return re.ReplaceAllString(input, "")
}
func PostSensitiveMessages() error {
port := config.GetPort() // 从config包获取端口号
var portStr string
if config.GetLotus() == "" {
portStr = fmt.Sprintf("http://127.0.0.1:%d/gensokyo", port) // 根据端口号构建URL
} else {
portStr = config.GetLotus() + "/gensokyo"
}
file, err := os.Open("test.txt")
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var results []string
for scanner.Scan() {
text := scanner.Text()
// 使用读取的文本填充message和raw_message字段
data := structs.OnebotGroupMessage{
Font: 0,
Message: text,
MessageID: 0,
MessageSeq: 0,
MessageType: "private",
PostType: "message",
RawMessage: text,
RealMessageType: "group_private",
SelfID: 100000000,
Sender: structs.Sender{
Nickname: "测试脚本",
UserID: 100000000,
},
SubType: "friend",
Time: 1700000000,
UserID: 100000000,
}
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
response, err := http.Post(portStr, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return err
}
fmtf.Printf("测试脚本运行中:%v", results)
results = append(results, string(responseBody))
}
// 使用当前时间戳生成文件名
currentTime := time.Now()
fileName := "test_result_" + currentTime.Format("20060102_150405") + ".txt"
// 将HTTP响应结果保存到指定的文件中
return os.WriteFile(fileName, []byte(strings.Join(results, "\n")), 0644)
}
// SendSSEPrivateMessage 分割并发送消息的核心逻辑,直接遍历字符串
func SendSSEPrivateMessage(userID int64, content string) {
punctuations := []rune{'。', '!', '?', ',', ',', '.', '!', '?', '~'}
splitProbability := config.GetSplitByPuntuations()
var parts []string
var currentPart strings.Builder
for _, runeValue := range content {
currentPart.WriteRune(runeValue)
if strings.ContainsRune(string(punctuations), runeValue) {
// 根据概率决定是否分割
if rand.Intn(100) < splitProbability {
parts = append(parts, currentPart.String())
currentPart.Reset()
}
}
}
// 添加最后一部分(如果有的话)
if currentPart.Len() > 0 {
parts = append(parts, currentPart.String())
}
// 根据parts长度处理状态
for i, part := range parts {
state := 1
if i == len(parts)-2 { // 倒数第二部分
state = 11
} else if i == len(parts)-1 { // 最后一部分
state = 20
}
// 构造消息体并发送
messageSSE := structs.InterfaceBody{
Content: part,
State: state,
}
if state == 20 { // 对最后一部分特殊处理
MemoryLoadCommand := config.GetMemoryLoadCommand()
promptKeyboard := config.GetPromptkeyboard()
if len(MemoryLoadCommand) > 0 {
selectedRestoreResponse := MemoryLoadCommand[rand.Intn(len(MemoryLoadCommand))]
if len(promptKeyboard) > 0 {
promptKeyboard[0] = selectedRestoreResponse
}
}
messageSSE.PromptKeyboard = promptKeyboard
}
// 发送SSE消息函数
SendPrivateMessageSSE(userID, messageSSE)
}
}