-
Notifications
You must be signed in to change notification settings - Fork 2
/
sendmsg.go
96 lines (94 loc) · 2.48 KB
/
sendmsg.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
package chatgpt
import (
"encoding/json"
"github.com/atotto/clipboard"
"github.com/playwright-community/playwright-go"
"github.com/sirupsen/logrus"
"strings"
"time"
)
func (h *Helper) SendMsg(page playwright.Page, inputText string) (string, error) {
// 等待 //textarea
textarea, err := page.WaitForSelector("//textarea", playwright.PageWaitForSelectorOptions{
Timeout: playwright.Float(1000 * 60),
})
if err != nil {
logrus.Errorf("Error while waiting for selector: %v", err)
return "", err
}
// 输入
//inputText := "你好,我是OpenAI生产的复读机,可以复读你说的话。"
// 复制 inputText 粘贴到 textarea
h.sendMsgLock.Lock()
defer h.sendMsgLock.Unlock()
err = clipboard.WriteAll(inputText)
if err != nil {
logrus.Errorf("Error while writing to clipboard: %v", err)
return "", err
}
err = textarea.Focus()
if err != nil {
logrus.Errorf("Error while focusing textarea: %v", err)
return "", err
}
err = textarea.Press(controlA())
if err != nil {
logrus.Errorf("Error while pressing control+a: %v", err)
return "", err
}
err = textarea.Press(controlV())
if err != nil {
logrus.Errorf("Error while pressing control+v: %v", err)
return "", err
}
go func() {
for {
time.Sleep(time.Second)
// 回车
// //textarea/../button/@disabled 是否有值 如果有说明此时不能回车
selector, err := page.QuerySelector("//textarea/../button/@disabled")
if err != nil {
logrus.Errorf("Error while querying selector: %v", err)
continue
}
if selector != nil {
continue
}
err = textarea.Press("Enter")
if err != nil {
logrus.Errorf("Error while pressing enter: %v", err)
}
break
}
}()
// 等待响应
response := page.WaitForResponse("https://chat.openai.com/backend-api/conversation", playwright.PageWaitForResponseOptions{
Timeout: playwright.Float(1000 * 60),
})
// 解析 text/event-stream
{
text, _ := response.Text()
// 换行符分割,去掉 data:
lines := strings.Split(text, "\n")
var finalLine *ConversationStreamResponseItem
for _, line := range lines {
if strings.HasPrefix(line, "data:") {
line = strings.TrimPrefix(line, "data:")
// 解析json
var data = &ConversationStreamResponseItem{}
err := json.Unmarshal([]byte(line), data)
if err != nil {
continue
}
finalLine = data
}
}
if finalLine != nil {
inputText = finalLine.Text()
logrus.Infof("AI: %s", finalLine.Text())
} else {
inputText = ""
}
}
return inputText, nil
}