From c950a26602c77d7007278c53492a078be8351876 Mon Sep 17 00:00:00 2001 From: Miguel Piedrafita <github@miguelpiedrafita.com> Date: Sun, 4 Dec 2022 03:19:29 +0000 Subject: [PATCH] init --- .github/workflows/build.yaml | 25 +++ .github/workflows/release.yaml | 40 +++++ .gitignore | 2 + .vscode/launch.json | 15 ++ LICENSE | 9 + Makefile | 12 ++ README.md | 17 ++ env.example | 2 + go.mod | 15 ++ go.sum | 25 +++ main.go | 318 +++++++++++++++++++++++++++++++++ 11 files changed, 480 insertions(+) create mode 100644 .github/workflows/build.yaml create mode 100644 .github/workflows/release.yaml create mode 100644 .gitignore create mode 100644 .vscode/launch.json create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 env.example create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..c7e5aa5 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,25 @@ +name: Build +on: [push, pull_request] +jobs: + build: + name: Build + runs-on: ${{ matrix.os }} + + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + goarch: [amd64, arm64] + exclude: + - os: windows-latest + goarch: arm64 + + steps: + - name: Check out source code + uses: actions/checkout@v3 + - name: Setup + uses: actions/setup-go@v3 + with: + go-version-file: "go.mod" + cache: true + - name: Build + run: env GOARCH=${{ matrix.goarch }} make diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..ab1393d --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,40 @@ +on: + release: + types: [created] + +jobs: + releases-matrix: + name: Release Go Binary + runs-on: ubuntu-latest + strategy: + matrix: + goos: [linux, windows, darwin] + goarch: [amd64, arm64] + exclude: + - goarch: arm64 + goos: windows + steps: + - name: Get Release Info + run: | + echo "RELEASE_TAG=${GITHUB_REF/refs\/tags\//}" >> $GITHUB_ENV + echo "REPOSITORY_NAME=${GITHUB_REPOSITORY#*/}" >> $GITHUB_ENV + echo "OS_NAME=${{ matrix.goos }}" >> $GITHUB_ENV + - name: Uppercase Darwin + if: matrix.goos == 'darwin' + run: echo "OS_NAME=Darwin" >> $GITHUB_ENV + - name: Uppercase Linux + if: matrix.goos == 'linux' + run: echo "OS_NAME=Linux" >> $GITHUB_ENV + - name: Uppercase Windows + if: matrix.goos == 'windows' + run: echo "OS_NAME=Win" >> $GITHUB_ENV + - uses: actions/checkout@v3 + - uses: wangyoucao577/go-release-action@v1.34 + with: + md5sum: false + extra_files: README.md LICENSE env.example + goos: ${{ matrix.goos }} + goarch: ${{ matrix.goarch }} + github_token: ${{ secrets.GITHUB_TOKEN }} + goversion: "https://dl.google.com/go/go1.19.3.linux-amd64.tar.gz" + asset_name: "${{ env.REPOSITORY_NAME }}-${{ env.OS_NAME }}-${{ matrix.goarch }}" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..226ca36 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.env +vendor diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..fa41044 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Package", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${fileDirname}" + } + ] +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3434263 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Miguel Piedrafita + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b0ddd13 --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +GIT_COMMIT=$(shell git describe --always) + +.PHONY: all build clean test + +all: build +default: build + +build: + go build + +clean: + rm chatgpt-telegram diff --git a/README.md b/README.md new file mode 100644 index 0000000..f02ee82 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +# ChatGPT-bot + +> Interact with ChatGPT + +Go CLI to fuels a Telegram bot that lets you interact with [ChatGPT](https://openai.com/blog/chatgpt/), a large language model trained by OpenAI. + +## Installation + +Download the file corresponding to your OS in the [releases page](https://github.com/m1guelpf/chatgpt-telegram/releases/latest). After you extract it, copy `env.example` to `.env` and fill in your Bot's details (you'll need your bot token, which you can find [here](https://core.telegram.org/bots/tutorial#obtain-your-bot-token), and optionally your telegram id, which you can find by DMing @userinfobot on Telegram. + +## Usage + +Run the `chatgpt-telegram` binary! + +## License + +This repository is licensed under the [MIT License](LICENSE). diff --git a/env.example b/env.example new file mode 100644 index 0000000..47324e9 --- /dev/null +++ b/env.example @@ -0,0 +1,2 @@ +TELEGRAM_ID= +TELEGRAM_TOKEN= diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..91b1479 --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module github.com/m1guelpf/chatgpt-telegram + +go 1.19 + +require ( + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/joho/godotenv v1.4.0 + github.com/playwright-community/playwright-go v0.2000.1 +) + +require ( + github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 // indirect + github.com/go-stack/stack v1.8.1 // indirect + gopkg.in/square/go-jose.v2 v2.6.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..55b55dd --- /dev/null +++ b/go.sum @@ -0,0 +1,25 @@ +github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ= +github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/h2non/filetype v1.1.1/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= +github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg= +github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/playwright-community/playwright-go v0.2000.1 h1:2JViSHpJQ/UL/PO1Gg6gXV5IcXAAsoBJ3KG9L3wKXto= +github.com/playwright-community/playwright-go v0.2000.1/go.mod h1:1y9cM9b9dVHnuRWzED1KLM7FtbwTJC8ibDjI6MNqewU= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/square/go-jose.v2 v2.6.0 h1:NGk74WTnPKBNUhNzQX7PYcTLUjoq7mzKk2OKbvwk2iI= +gopkg.in/square/go-jose.v2 v2.6.0/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..999b8f2 --- /dev/null +++ b/main.go @@ -0,0 +1,318 @@ +package main + +import ( + "errors" + "fmt" + "log" + "os" + "os/signal" + "strconv" + "strings" + "sync" + "syscall" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/joho/godotenv" + "github.com/playwright-community/playwright-go" +) + +func main() { + runOptions := playwright.RunOptions{ + Browsers: []string{"chromium"}, + Verbose: false, + } + err := playwright.Install(&runOptions) + if err != nil { + log.Fatalf("Couldn't install headless browser: %v", err) + } + + pw, err := playwright.Run(&runOptions) + if err != nil { + log.Fatalf("Couldn't start headless browser: %v", err) + } + + browser, page := launchBrowser(pw, "https://chat.openai.com", true) + + for !isLoggedIn(page) { + cookies := <-logIn(pw) + for _, cookie := range cookies { + convertedCookie := playwright.BrowserContextAddCookiesOptionsCookies{ + Name: &cookie.Name, + Value: &cookie.Value, + Domain: &cookie.Domain, + Path: &cookie.Path, + Expires: &cookie.Expires, + Secure: &cookie.Secure, + HttpOnly: &cookie.HttpOnly, + SameSite: &cookie.SameSite, + } + if err := browser.AddCookies(convertedCookie); err != nil { + log.Fatalf("Couldn't add cookies: %v", err) + } + } + + if _, err = page.Goto("https://chat.openai.com"); err != nil { + log.Fatalf("Couldn't reload website: %v", err) + } + } + + if _, err := page.Evaluate("localStorage.setItem('oai/apps/hasSeenOnboarding/chat', 'true')"); err != nil { + log.Fatalf("Couldn't update localstorage: %v", err) + } + if _, err = page.Reload(); err != nil { + log.Fatalf("Couldn't reload website: %v", err) + } + log.Println("Started ChatGPT") + + err = godotenv.Load() + if err != nil { + log.Fatalf("Couldn't load .env file: %v", err) + } + + bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_TOKEN")) + if err != nil { + log.Fatalf("Couldn't start Telegram bot: %v", err) + } + + c := make(chan os.Signal, 2) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + go func() { + <-c + bot.StopReceivingUpdates() + if err = browser.Close(); err != nil { + log.Fatalf("could not close browser: %v", err) + } + if err = pw.Stop(); err != nil { + log.Fatalf("could not stop Playwright: %v", err) + } + os.Exit(0) + }() + + updateConfig := tgbotapi.NewUpdate(0) + updateConfig.Timeout = 30 + updates := bot.GetUpdatesChan(updateConfig) + + log.Printf("Started Telegram bot! Message @%s to start.", bot.Self.UserName) + + for update := range updates { + if update.Message == nil { + continue + } + + msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") + msg.ReplyToMessageID = update.Message.MessageID + msg.ParseMode = "Markdown" + + userId := strconv.FormatInt(update.Message.Chat.ID, 10) + if os.Getenv("TELEGRAM_ID") != "" && userId != os.Getenv("TELEGRAM_ID") { + msg.Text = "You are not authorized to use this bot." + bot.Send(msg) + continue + } + + if !update.Message.IsCommand() { + response, err := query_chatgpt(update.Message.Text, page, bot, tgbotapi.NewChatAction(update.Message.Chat.ID, "typing")) + if err != nil { + msg.Text = fmt.Sprintf("Error: %v", err) + } else { + msg.Text = response + } + + if _, err := bot.Send(msg); err != nil { + log.Fatalf("Couldn't send message: %v", err) + } + continue + } + + switch update.Message.Command() { + case "help": + msg.Text = "Help!" + case "start": + msg.Text = "Hi :)" + case "reload": + if _, err = page.Reload(); err != nil { + log.Fatalf("Couldn't reload website: %v", err) + } + msg.Text = "New conversation!" + default: + continue + } + + if _, err := bot.Send(msg); err != nil { + log.Fatalf("Couldn't send message: %v", err) + } + } +} + +func query_chatgpt(query string, page playwright.Page, bot *tgbotapi.BotAPI, showTyping tgbotapi.ChatActionConfig) (string, error) { + input := getChatBox(page) + + if err := input.Click(); err != nil { + log.Fatalf("Couldn't type query: %v", err) + } + if err := input.Fill(query); err != nil { + log.Fatalf("Couldn't type query: %v", err) + } + if err := input.Press("Enter"); err != nil { + log.Fatalf("Couldn't type query: %v", err) + } + + loading, err := page.QuerySelectorAll( + "button[class^='PromptTextarea__PositionSubmit']>.text-2xl", + ) + if err != nil { + log.Fatalf("Couldn't get loading element: %v", err) + } + bot.Request(showTyping) + start_time := time.Now() + + for len(loading) > 0 { + if (time.Now().Sub(start_time)).Seconds() > 45 { + return "", errors.New("Loading took too long") + } + + time.Sleep(500 * time.Millisecond) + + loading, err = page.QuerySelectorAll( + "button[class^='PromptTextarea__PositionSubmit']>.text-2xl", + ) + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + bot.Request(showTyping) + } + + pageElements, err := page.QuerySelectorAll("div[class*='ConversationItem__Message']") + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + lastElement := pageElements[len(pageElements)-1] + prose, err := lastElement.QuerySelector(".prose") + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + codeBlocks, err := prose.QuerySelectorAll("pre") + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + + response := "" + if len(codeBlocks) > 0 { + children, err := prose.QuerySelectorAll("p, pre") + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + + for _, child := range children { + tagName, err := child.GetProperty("tagName") + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + if tagName.String() == "PRE" { + codeContainer, err := child.QuerySelector("code") + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + innerText, err := codeContainer.InnerText() + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + response += fmt.Sprintf("\n\n```\n%s\n```", escapeMarkdown(innerText)) + } else { + text, err := child.InnerText() + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + response += escapeMarkdown(text) + } + } + response = strings.ReplaceAll(response, "<code>", "`") + response = strings.ReplaceAll(response, "</code>", "`") + } else { + innerText, err := prose.InnerText() + if err != nil { + return "", errors.New("Something went wrong! Try running /reload, or restart the CLI.") + } + response = escapeMarkdown(innerText) + } + + return response, nil +} + +func launchBrowser(pw *playwright.Playwright, url string, headless bool) (playwright.BrowserContext, playwright.Page) { + browser, err := pw.Chromium.LaunchPersistentContext("/tmp/chatgpt", playwright.BrowserTypeLaunchPersistentContextOptions{Headless: playwright.Bool(headless)}) + if err != nil { + log.Fatalf("Couldn't launch headless browser: %v", err) + } + page, err := browser.NewPage() + if err != nil { + log.Fatalf("Couldn't create a new tab on headless browser: %v", err) + } + + if _, err = page.Goto(url); err != nil { + log.Fatalf("Couldn't open website: %v", err) + } + + return browser, page +} + +func isLoggedIn(page playwright.Page) bool { + return page.URL() == "https://chat.openai.com/chat" +} + +func getChatBox(page playwright.Page) playwright.ElementHandle { + input, err := page.QuerySelector("textarea") + if err != nil { + log.Fatalf("Couldn't get chatbox: %v", err) + } + + return input +} + +func logIn(pw *playwright.Playwright) <-chan []*playwright.BrowserContextCookiesResult { + var lock sync.Mutex + r := make(chan []*playwright.BrowserContextCookiesResult) + + lock.Lock() + go func() { + defer close(r) + defer lock.Unlock() + + browser, page := launchBrowser(pw, "https://chat.openai.com/", false) + log.Println("Please log in to OpenAI Chat") + + page.On("framenavigated", func(frame playwright.Frame) { + if frame.URL() != "https://chat.openai.com/chat" { + return + } + + lock.Unlock() + }) + + lock.Lock() + + cookies, err := browser.Cookies("https://chat.openai.com/") + if err != nil { + log.Fatalf("Couldn't store authentication: %v", err) + } + + if err := browser.Close(); err != nil { + log.Fatalf("could not close browser: %v", err) + } + + r <- cookies + }() + + return r +} + +func escapeMarkdown(text string) string { + escape_chars := []string{"_", "*", "`", "["} + + for _, char := range escape_chars { + text = strings.ReplaceAll(text, char, "\\"+char) + } + + return text +}