Skip to content

Instantly share code, notes, and snippets.

@jerry-tao
Created March 22, 2023 09:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerry-tao/8393283c9ac7c08e8f72a5b3f8101a61 to your computer and use it in GitHub Desktop.
Save jerry-tao/8393283c9ac7c08e8f72a5b3f8101a61 to your computer and use it in GitHub Desktop.
Simple ChatGPT Telegram Bot
package main
// Import necessary packages
import (
"context"
"fmt"
"log"
"net/http"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sashabaranov/go-openai"
)
/*
Please read the follow link for set proxy.
- https://github.com/noobnooc/noobnooc/discussions/9
- https://gist.github.com/ihciah/665fd43b597141fa93a7c85340917835
*/
// Define the ChatGPT API URL and API key
const chatGPTAPIURL = "https://set-your-own-url/v1"
const chatGPTAPIKey = "set-your-own-secret"
// Define the telegram bot token and api url
const botToken = "set-your-own-telegram-bot"
const botApiURL = "https://set-your-own-url/bot%s/%s"
func main() {
// Only allow user can use it.
// if you don't know your id, you could send a message to you bot.
userList := map[int64]bool{0: true}
// if you don't need proxy, use:
// bot, err := tgbotapi.NewBotAPI(botToken)
bot, err := tgbotapi.NewBotAPIWithAPIEndpoint(botToken, botApiURL)
if err != nil {
log.Panic(err)
}
// Set the bot's update configuration
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
// Get updates from the bot
updates := bot.GetUpdatesChan(u)
// create a chatgpt client
// if you don't need proxy, use:
// client:=openai.NewClient(chatGPTAPIKey)
config := openai.DefaultConfig(chatGPTAPIKey)
config.BaseURL = chatGPTAPIURL
config.HTTPClient = http.DefaultClient
client := openai.NewClientWithConfig(config)
var messages []openai.ChatCompletionMessage
// Process updates received from the bot
for update := range updates {
if !userList[update.Message.From.ID] {
log.Println("received message from user:", update.Message.From.ID)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("Sorry, %s! I'm a private Telegram bot!", update.Message.From.FirstName))
msg.ParseMode = tgbotapi.ModeHTML
_, err := bot.Send(msg)
if err != nil {
log.Println("send message error:", err)
}
continue
}
if update.Message.IsCommand() {
// Extract the command from the message text
command := update.Message.Command()
switch command {
// typo /new to start a new conversation
case "new":
messages = messages[:0]
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "OK, we already start a new conversation")
_, err := bot.Send(msg)
if err != nil {
log.Panic(err)
}
default:
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Unknown command. Please try again.")
_, err := bot.Send(msg)
if err != nil {
log.Panic(err)
}
}
continue
}
if update.Message == nil {
continue
}
// Handle text messages
if update.Message.Text != "" {
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: update.Message.Text,
})
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: messages,
},
)
if err != nil {
msg := tgbotapi.NewMessage(update.Message.Chat.ID, err.Error())
msg.ParseMode = tgbotapi.ModeHTML
_, err = bot.Send(msg)
continue
}
content := resp.Choices[0].Message.Content
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: content,
})
// Send the generated text as a reply to the user
msg := tgbotapi.NewMessage(update.Message.Chat.ID, content)
msg.ParseMode = tgbotapi.ModeHTML
_, err = bot.Send(msg)
if err != nil {
log.Panic(err)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment