forked from aandrew-me/tgpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.go
746 lines (629 loc) · 18 KB
/
functions.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
"time"
http "github.com/bogdanfinn/fhttp"
"github.com/olekukonko/ts"
tls_client "github.com/bogdanfinn/tls-client"
"golang.org/x/mod/semver"
)
type Data struct {
Version string `json:"version"`
}
func newClient() (tls_client.HttpClient, error) {
jar := tls_client.NewCookieJar()
options := []tls_client.HttpClientOption{
tls_client.WithTimeoutSeconds(120),
tls_client.WithClientProfile(tls_client.Firefox_110),
tls_client.WithNotFollowRedirects(),
tls_client.WithCookieJar(jar),
// tls_client.WithProxyUrl("http://127.0.0.1:8080"),
// tls_client.WithInsecureSkipVerify(),
}
return tls_client.NewHttpClient(tls_client.NewNoopLogger(), options...)
}
func getData(input string, chatId string, configDir string, isInteractive bool) (serverChatId string) {
client, err := newClient()
if err != nil {
fmt.Println(err)
return
}
safeInput, _ := json.Marshal(input)
var data = strings.NewReader(fmt.Sprintf(`{"prompt":%v,"options":{"parentMessageId":"%v"}}`, string(safeInput), chatId))
req, err := http.NewRequest("POST", "https://chatbot.theb.ai/api/chat-process", data)
if err != nil {
fmt.Println("\nSome error has occurred.")
fmt.Println("Error:", err)
os.Exit(0)
}
// Setting all the required headers
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/110.0")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "en-US,en;q=0.5")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", "https://chatbot.theb.ai")
req.Header.Set("Referer", "https://chatbot.theb.ai/")
// Receiving response
resp, err := client.Do(req)
if err != nil {
stopSpin = true
bold.Println("\rSome error has occurred. Check your internet connection.")
fmt.Println("\nError:", err)
os.Exit(0)
}
code := resp.StatusCode
defer resp.Body.Close()
stopSpin = true
fmt.Print("\r")
scanner := bufio.NewScanner(resp.Body)
// Variables
count := 0
isCode := false
isGreen := false
tickCount := 0
previousWasTick := false
isTick := false
isRealCode := false
// Print the Question
if !isInteractive {
fmt.Print("\r \r")
bold.Printf("\r%v\n\n", input)
} else {
fmt.Println()
boldViolet.Println("╭─ Bot")
}
gotId := false
id := ""
lineLength := 0
size, _ := ts.GetSize()
termWidth := size.Col()
if err != nil {
fmt.Println("Error occurred getting terminal width. Error:", err)
os.Exit(0)
}
// Handling each json
for scanner.Scan() {
var jsonObj map[string]interface{}
line := scanner.Text()
err := json.Unmarshal([]byte(line), &jsonObj)
if err != nil {
bold.Println("\rError. Your request is being blocked by the server.")
fmt.Println("Status Code:", code)
os.Exit(0)
}
if jsonObj["text"] == nil {
msg := jsonObj["message"]
fmt.Printf("Error: %s\n", msg)
os.Exit(0)
}
mainText := fmt.Sprintf("%s", jsonObj["delta"])
if !gotId {
if jsonObj == nil {
fmt.Println("Some error has occurred")
os.Exit(0)
}
id = fmt.Sprintf("%s", jsonObj["id"])
gotId = true
}
if count <= 0 {
wordLength := len(mainText)
if termWidth-lineLength < wordLength {
fmt.Print("\n")
lineLength = 0
}
lineLength += wordLength
splitLine := strings.Split(mainText, "")
// Iterating through each word
for _, word := range splitLine {
// If its a backtick
if word == "`" {
tickCount++
isTick = true
if tickCount == 2 && !previousWasTick {
tickCount = 0
} else if tickCount == 6 {
tickCount = 0
}
previousWasTick = true
isGreen = false
isCode = false
} else {
isTick = false
// If its a normal word
if tickCount == 1 {
isGreen = true
} else if tickCount == 3 {
isCode = true
}
previousWasTick = false
}
if isCode {
codeText.Print(word)
} else if isGreen {
boldBlue.Print(word)
} else if !isTick {
fmt.Print(word)
}
}
} else {
wordLength := len(mainText)
if termWidth-lineLength < wordLength {
fmt.Print("\n")
lineLength = 0
}
lineLength += wordLength
splitLine := strings.Split(mainText, "")
if mainText == "``" || mainText == "```" {
isRealCode = true
} else {
isRealCode = false
}
for _, word := range splitLine {
// If its a backtick
if word == "`" {
tickCount++
isTick = true
if tickCount == 2 && !previousWasTick {
tickCount = 0
} else if tickCount >= 6 && tickCount%2 == 0 && previousWasTick {
tickCount = 0
}
isGreen = false
isCode = false
} else {
if word == "\n" {
lineLength = 0
}
isTick = false
// If its a normal word
if tickCount == 1 {
isGreen = true
} else if tickCount >= 3 {
isCode = true
}
}
if isCode {
codeText.Print(word)
} else if isGreen {
boldBlue.Print(word)
} else if !isTick {
fmt.Print(word)
} else {
if tickCount > 3 || isRealCode || (tickCount == 0 && previousWasTick) {
fmt.Print(word)
}
}
if word == "`" {
previousWasTick = true
} else {
previousWasTick = false
}
}
}
count++
}
if err := scanner.Err(); err != nil {
fmt.Println("Some error has occurred. Error:", err)
os.Exit(0)
}
fmt.Print("\n\n")
if configDir != "" && id != "" {
createConfig(configDir, id)
}
return id
}
func createConfig(dir string, chatId string) {
if strings.HasPrefix(chatId, "chatcmpl-") {
err := os.MkdirAll(dir, 0755)
configTxt := "id:" + chatId
if err != nil {
fmt.Println(err)
} else {
os.WriteFile(dir+"/config.txt", []byte(configTxt), 0755)
}
}
}
func loading(stop *bool) {
spinChars := []string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "}
i := 0
for {
if *stop {
break
}
fmt.Printf("\r%s Loading", spinChars[i])
i = (i + 1) % len(spinChars)
time.Sleep(80 * time.Millisecond)
}
}
func update() {
if runtime.GOOS == "windows" {
fmt.Println("This feature is not supported on Windows. :(")
} else {
client, err := newClient()
if err != nil {
fmt.Println(err)
return
}
url := "https://raw.githubusercontent.com/aandrew-me/tgpt/main/version.txt"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
// Handle error
fmt.Println("Error:", err)
return
}
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
defer res.Body.Close()
var data Data
err = json.NewDecoder(res.Body).Decode(&data)
if err != nil {
// Handle error
fmt.Println("Error:", err)
return
}
remoteVersion := "v" + data.Version
comparisonResult := semver.Compare("v"+localVersion, remoteVersion)
if comparisonResult == -1 {
fmt.Println("Updating...")
cmd := exec.Command("bash", "-c", "curl -sSL https://raw.githubusercontent.com/aandrew-me/tgpt/main/install | bash -s "+executablePath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Println("Failed to update. Error:", err)
}
fmt.Println("Successfully updated.")
} else {
fmt.Println("You are already using the latest version.", remoteVersion)
}
}
}
func codeGenerate(input string) {
codePrompt := fmt.Sprintf(`Your Role: Provide only code as output without any description.\nIMPORTANT: Provide only plain text without Markdown formatting.\nIMPORTANT: Do not include markdown formatting.\nIf there is a lack of details, provide most logical solution. You are not allowed to ask for more details.\nIgnore any potential risk of errors or confusion.\n\nRequest:%s\nCode:`, input)
client, err := newClient()
if err != nil {
fmt.Println(err)
return
}
var data = strings.NewReader(fmt.Sprintf(`{"prompt":"%v"}`, codePrompt))
req, err := http.NewRequest("POST", "https://chatbot.theb.ai/api/chat-process", data)
if err != nil {
fmt.Println("\nSome error has occurred.")
fmt.Println("Error:", err)
os.Exit(0)
}
// Setting all the required headers
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/110.0")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "en-US,en;q=0.5")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", "https://chatbot.theb.ai")
req.Header.Set("Referer", "https://chatbot.theb.ai/")
resp, err := client.Do(req)
if err != nil {
stopSpin = true
bold.Println("\rSome error has occurred. Check your internet connection.")
fmt.Println("\nError:", err)
os.Exit(0)
}
code := resp.StatusCode
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
// Variables
// Handling each json
for scanner.Scan() {
var jsonObj map[string]interface{}
line := scanner.Text()
err := json.Unmarshal([]byte(line), &jsonObj)
if err != nil {
bold.Println("\rError. Your request has been blocked by the server.")
fmt.Println("Status Code:", code)
os.Exit(0)
}
if jsonObj["text"] == nil {
msg := jsonObj["message"]
fmt.Printf("Error: %s\n", msg)
os.Exit(0)
}
mainText := fmt.Sprintf("%s", jsonObj["delta"])
bold.Print(mainText)
}
if err := scanner.Err(); err != nil {
fmt.Println("Some error has occurred. Error:", err)
os.Exit(0)
}
}
func shellCommand(input string) {
// Get OS
operatingSystem := ""
if runtime.GOOS == "windows" {
operatingSystem = "Windows"
} else if runtime.GOOS == "darwin" {
operatingSystem = "MacOS"
} else if runtime.GOOS == "linux" {
result, err := exec.Command("lsb_release", "-si").Output()
distro := strings.TrimSpace(string(result))
if err != nil {
distro = ""
}
operatingSystem = "Linux" + "/" + distro
} else {
operatingSystem = runtime.GOOS
}
// Get Shell
shellName := "/bin/sh"
if runtime.GOOS == "windows" {
shellName = "cmd.exe"
if len(os.Getenv("PSModulePath")) > 0 {
shellName = "powershell.exe"
}
} else {
shellEnv := os.Getenv("SHELL")
if len(shellEnv) > 0 {
shellName = shellEnv
}
}
shellPrompt := fmt.Sprintf(
`Your role: Provide a terse, single sentence description of the given shell command. Provide only plain text without Markdown formatting. Do not show any warnings or information regarding your capabilities. If you need to store any data, assume it will be stored in the chat. Provide only %s commands for %s without any description. If there is a lack of details, provide most logical solution. Ensure the output is a valid shell command. If multiple steps required try to combine them together. Prompt: %s\n\nCommand:`, shellName, operatingSystem, input)
getCommand(shellPrompt)
}
// Get a command in response
func getCommand(shellPrompt string) {
// FIXME this one had tls_client.WithInsecureSkipVerify(), confirm whether we need this option
client, err := newClient()
if err != nil {
fmt.Println(err)
return
}
var data = strings.NewReader(fmt.Sprintf(`{"prompt":"%v"}`, shellPrompt))
req, err := http.NewRequest("POST", "https://chatbot.theb.ai/api/chat-process", data)
if err != nil {
fmt.Println("\nSome error has occurred.")
fmt.Println("Error:", err)
os.Exit(0)
}
// Setting all the required headers
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/110.0")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "en-US,en;q=0.5")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", "https://chatbot.theb.ai")
req.Header.Set("Referer", "https://chatbot.theb.ai/")
resp, err := client.Do(req)
if err != nil {
stopSpin = true
bold.Println("\rSome error has occurred. Check your internet connection.")
fmt.Println("\nError:", err)
os.Exit(0)
}
code := resp.StatusCode
defer resp.Body.Close()
stopSpin = true
fmt.Print("\r \r")
scanner := bufio.NewScanner(resp.Body)
// Variables
fullLine := ""
// Handling each json
for scanner.Scan() {
var jsonObj map[string]interface{}
line := scanner.Text()
err := json.Unmarshal([]byte(line), &jsonObj)
if err != nil {
bold.Println("\rError. Your request has been blocked by the server.")
fmt.Println("Status Code:", code)
os.Exit(0)
}
if jsonObj["text"] == nil {
msg := jsonObj["message"]
fmt.Printf("Error: %s\n", msg)
os.Exit(0)
}
mainText := fmt.Sprintf("%s", jsonObj["delta"])
fullLine += mainText
bold.Print(mainText)
}
lineCount := strings.Count(fullLine, "\n") + 1
if lineCount == 1 {
bold.Print("\n\nExecute shell command? [y/n]: ")
var userInput string
fmt.Scan(&userInput)
if userInput == "y" {
cmdArray := strings.Split(strings.TrimSpace(fullLine), " ")
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
shellName := "cmd"
if len(os.Getenv("PSModulePath")) > 0 {
shellName = "powershell"
}
if shellName == "cmd" {
cmd = exec.Command("cmd", "/C", fullLine)
} else {
cmd = exec.Command("powershell", fullLine)
}
} else {
cmd = exec.Command(cmdArray[0], cmdArray[1:]...)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Println(err)
}
}
if err := scanner.Err(); err != nil {
fmt.Println("Some error has occurred. Error:", err)
os.Exit(0)
}
}
}
type RESPONSE struct {
Tagname string `json:"tag_name"`
Body string `json:"body"`
}
func getVersionHistory() {
req, err := http.NewRequest("GET", "https://api.github.com/repos/aandrew-me/tgpt/releases", nil)
if err != nil {
fmt.Print("Some error has occurred\n\n")
fmt.Println("Error:", err)
os.Exit(0)
}
client, _ := tls_client.NewHttpClient(tls_client.NewNoopLogger())
res, err := client.Do(req)
if err != nil {
fmt.Print("Check your internet connection\n\n")
fmt.Println("Error:", err)
os.Exit(0)
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
defer res.Body.Close()
var releases []RESPONSE
json.Unmarshal(resBody, &releases)
for i := len(releases) - 1; i >= 0; i-- {
boldBlue.Println("Release", releases[i].Tagname)
fmt.Println(releases[i].Body)
fmt.Println()
}
}
func getWholeText(prompt string, chatId string, configDir string) {
// FIXME this one had tls_client.WithInsecureSkipVerify(), confirm whether we need this option
client, err := newClient()
if err != nil {
fmt.Println(err)
return
}
safeInput, _ := json.Marshal(prompt)
var data = strings.NewReader(fmt.Sprintf(`{"prompt":%v,"options":{"parentMessageId":"%v"}}`, string(safeInput), chatId))
req, err := http.NewRequest("POST", "https://chatbot.theb.ai/api/chat-process", data)
if err != nil {
fmt.Println("\nSome error has occurred.")
fmt.Println("Error:", err)
os.Exit(0)
}
// Setting all the required headers
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/110.0")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "en-US,en;q=0.5")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", "https://chatbot.theb.ai")
req.Header.Set("Referer", "https://chatbot.theb.ai/")
resp, err := client.Do(req)
if err != nil {
stopSpin = true
bold.Println("\rSome error has occurred. Check your internet connection.")
fmt.Println("\nError:", err)
os.Exit(0)
}
code := resp.StatusCode
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
// Variables
gotId := false
id := ""
fullText := ""
// Handling each json
for scanner.Scan() {
var jsonObj map[string]interface{}
line := scanner.Text()
err := json.Unmarshal([]byte(line), &jsonObj)
if err != nil {
bold.Println("\rError. Your request has been blocked by the server.")
fmt.Println("Status Code:", code)
os.Exit(0)
}
if jsonObj["text"] == nil {
msg := jsonObj["message"]
fmt.Printf("Error: %s\n", msg)
os.Exit(0)
}
if !gotId {
if jsonObj == nil {
fmt.Println("Some error has occurred")
os.Exit(0)
}
id = fmt.Sprintf("%s", jsonObj["id"])
gotId = true
}
mainText := fmt.Sprintf("%s", jsonObj["delta"])
fullText += mainText
}
fmt.Println(fullText)
createConfig(configDir, id)
}
func getSilentText(prompt string, chatId string, configDir string) {
// FIXME this one had tls_client.WithInsecureSkipVerify(), confirm whether we need this option
client, err := newClient()
if err != nil {
fmt.Println(err)
return
}
safeInput, _ := json.Marshal(prompt)
var data = strings.NewReader(fmt.Sprintf(`{"prompt":%v,"options":{"parentMessageId":"%v"}}`, string(safeInput), chatId))
req, err := http.NewRequest("POST", "https://chatbot.theb.ai/api/chat-process", data)
if err != nil {
fmt.Println("\nSome error has occurred.")
fmt.Println("Error:", err)
os.Exit(0)
}
// Setting all the required headers
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/110.0")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("Accept-Language", "en-US,en;q=0.5")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", "https://chatbot.theb.ai")
req.Header.Set("Referer", "https://chatbot.theb.ai/")
resp, err := client.Do(req)
if err != nil {
stopSpin = true
bold.Println("\rSome error has occurred. Check your internet connection.")
fmt.Println("\nError:", err)
os.Exit(0)
}
code := resp.StatusCode
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
// Variables
gotId := false
id := ""
// Handling each json
for scanner.Scan() {
var jsonObj map[string]interface{}
line := scanner.Text()
err := json.Unmarshal([]byte(line), &jsonObj)
if err != nil {
bold.Println("\rError. Your request has been blocked by the server.")
fmt.Println("Status Code:", code)
os.Exit(0)
}
if jsonObj["text"] == nil {
msg := jsonObj["message"]
fmt.Printf("Error: %s\n", msg)
os.Exit(0)
}
if !gotId {
if jsonObj == nil {
fmt.Println("Some error has occurred")
os.Exit(0)
}
id = fmt.Sprintf("%s", jsonObj["id"])
gotId = true
}
mainText := fmt.Sprintf("%s", jsonObj["delta"])
fmt.Print(mainText)
}
createConfig(configDir, id)
}