-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
99 lines (81 loc) · 2.05 KB
/
main.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
package chatgpt
import (
"context"
"fmt"
"net/http"
"time"
cu "github.com/Davincible/chromedp-undetected"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
type TokenGen struct {
cancel context.CancelFunc
ctx context.Context
}
func NewTokenGen() *TokenGen {
return &TokenGen{}
}
func (t *TokenGen) StartChrome() (context.Context, error) {
ctx, tcancel, err := cu.New(cu.NewConfig(
// cu.WithHeadless(),
cu.WithUserDataDir("./dp"),
cu.WithTimeout(10*time.Second),
))
if err != nil {
return nil, err
}
t.cancel = tcancel
t.ctx = ctx
return ctx, nil
}
func (t *TokenGen) CloseChrome() {
t.cancel()
}
func (t *TokenGen) GetToken(email, password string) (string, error) {
var cookiesX []*http.Cookie
if err := chromedp.Run(t.ctx,
chromedp.Navigate("https://chat.openai.com/auth/login"),
chromedp.Click(`//*[@id="__next"]/div[1]/div[1]/div[4]/button[1]`),
chromedp.WaitVisible(`//*[@id="username"]`),
chromedp.SendKeys(`//*[@id="username"]`, email),
chromedp.Click(`/html/body/div/main/section/div/div/div/div[1]/div/form/div[2]/button`),
chromedp.WaitVisible(`//*[@id="password"]`),
chromedp.SendKeys(`//*[@id="password"]`, password),
chromedp.Click(`/html/body/div/main/section/div/div/div/form/div[3]/button`),
chromedp.ActionFunc(func(ctx context.Context) error {
cookies, err := network.GetCookies().Do(ctx)
if err != nil {
return err
}
for _, cookie := range cookies {
cookiesX = append(cookiesX, &http.Cookie{
Name: cookie.Name,
Value: cookie.Value,
})
}
return nil
}),
// next page is json, display it rather than autodownload : net err
); err != nil {
return "", err
}
// balace TODO: check if token is valid
for _, cookie := range cookiesX {
if cookie.Name == "__Secure-next-auth.session-token" {
return cookie.Value, nil
}
}
return "", fmt.Errorf("token not found")
}
func main() {
t := NewTokenGen()
_, err := t.StartChrome()
if err != nil {
panic(err)
}
tok, err := t.GetToken("", "")
if err != nil {
panic(err)
}
fmt.Println(tok)
}