Sure! I'll help you rewrite the persistentconversationbot.py example from Python to Go, add tests, and generate a Dockerfile for it. We'll create a Telegram bot using Go that maintains conversation states with users, ensuring persistence across interactions.
Overview
We'll use the following Go packages:
telegram-bot-api: A Go library for interacting with the Telegram Bot API.
badger: A fast, embeddable, persistent key-value store written in pure Go, suitable for storing conversation states.
go get github.com/go-telegram-bot-api/telegram-bot-api/v5
go get github.com/dgraph-io/badger/v4
2. Main Bot Code (main.go)
go
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"sync"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
badger "github.com/dgraph-io/badger/v4"
)
type BotHandler struct {
bot *tgbotapi.BotAPI
db *badger.DB
mu sync.Mutex
ctx context.Context
states map[int64]string
}
func NewBotHandler(bot *tgbotapi.BotAPI, db *badger.DB) *BotHandler {
return &BotHandler{
bot: bot,
db: db,
ctx: context.Background(),
states: make(map[int64]string),
}
}
func (h *BotHandler) getState(chatID int64) (string, error) {
var state string
err := h.db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte(fmt.Sprintf("state_%d", chatID)))
if err != nil {
if err == badger.ErrKeyNotFound {
state = "START"
return nil
}
return err
}
return item.Value(func(val []byte) error {
state = string(val)
return nil
})
})
return state, err
}
func (h *BotHandler) setState(chatID int64, state string) error {
return h.db.Update(func(txn *badger.Txn) error {
return txn.Set([]byte(fmt.Sprintf("state_%d", chatID)), []byte(state))
})
}
func (h *BotHandler) clearState(chatID int64) error {
return h.db.Update(func(txn *badger.Txn) error {
return txn.Delete([]byte(fmt.Sprintf("state_%d", chatID)))
})
}
func (h *BotHandler) HandleUpdate(update tgbotapi.Update) {
if update.Message == nil {
return
}
chatID := update.Message.Chat.ID
state, err := h.getState(chatID)
if err != nil {
log.Printf("Error getting state: %v", err)
return
}
switch state {
case "START":
msg := tgbotapi.NewMessage(chatID, "Hi! What's your name?")
h.bot.Send(msg)
h.setState(chatID, "ASKED_NAME")
case "ASKED_NAME":
name := update.Message.Text
h.db.Update(func(txn *badger.Txn) error {
return txn.Set([]byte(fmt.Sprintf("name_%d", chatID)), []byte(name))
})
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("Nice to meet you, %s! How old are you?", name))
h.bot.Send(msg)
h.setState(chatID, "ASKED_AGE")
case "ASKED_AGE":
age := update.Message.Text
h.db.Update(func(txn *badger.Txn) error {
return txn.Set([]byte(fmt.Sprintf("age_%d", chatID)), []byte(age))
})
var name string
h.db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte(fmt.Sprintf("name_%d", chatID)))
if err != nil {
return err
}
return item.Value(func(val []byte) error {
name = string(val)
return nil
})
})
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("%s, age %s, got it!", name, age))
h.bot.Send(msg)
h.clearState(chatID)
default:
msg := tgbotapi.NewMessage(chatID, "I didn't understand that. Let's start over.")
h.bot.Send(msg)
h.clearState(chatID)
}
}
func main() {
token := os.Getenv("TELEGRAM_TOKEN")
if token == "" {
log.Fatal("TELEGRAM_TOKEN environment variable required")
}
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
log.Panic(err)
}
bot.Debug = false
log.Printf("Authorized on account %s", bot.Self.UserName)
// Open Badger database
db, err := badger.Open(badger.DefaultOptions("badger_db"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
handler := NewBotHandler(bot, db)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates := bot.GetUpdatesChan(u)
for update := range updates {
go handler.HandleUpdate(update)
}
}
Explanation:
State Management: We're using BadgerDB to persist user states and data between bot restarts.
Concurrency: The HandleUpdate function is called in a goroutine to handle multiple users concurrently.
Conversation Flow:
START: Ask for the user's name.
ASKED_NAME: Store the name and ask for the age.
ASKED_AGE: Store the age and confirm receipt.
Tests
3. Test Code (main_test.go)
We need to mock the Telegram Bot API and BadgerDB interactions for testing.
go
package main
import (
"fmt"
"testing"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
badger "github.com/dgraph-io/badger/v4"
)
type MockBotAPI struct {
SentMessages []tgbotapi.Chattable
}
func (m *MockBotAPI) Send(c tgbotapi.Chattable) (tgbotapi.Message, error) {
m.SentMessages = append(m.SentMessages, c)
return tgbotapi.Message{}, nil
}
func TestBotHandler(t *testing.T) {
// Initialize in-memory BadgerDB
opts := badger.DefaultOptions("").WithInMemory(true)
db, err := badger.Open(opts)
if err != nil {
t.Fatalf("Failed to open BadgerDB: %v", err)
}
defer db.Close()
mockBot := &MockBotAPI{}
handler := NewBotHandler(nil, db)
handler.bot = mockBot
chatID := int64(12345)
// Simulate /start command
updateStart := tgbotapi.Update{
Message: &tgbotapi.Message{
Chat: &tgbotapi.Chat{ID: chatID},
Text: "/start",
},
}
handler.HandleUpdate(updateStart)
// Check the response
if len(mockBot.SentMessages) != 1 {
t.Errorf("Expected 1 message, got %d", len(mockBot.SentMessages))
}
msg := mockBot.SentMessages[0].(tgbotapi.MessageConfig)
expectedText := "Hi! What's your name?"
if msg.Text != expectedText {
t.Errorf("Expected message '%s', got '%s'", expectedText, msg.Text)
}
// Simulate user sending name
updateName := tgbotapi.Update{
Message: &tgbotapi.Message{
Chat: &tgbotapi.Chat{ID: chatID},
Text: "Alice",
},
}
handler.HandleUpdate(updateName)
// Simulate user sending age
updateAge := tgbotapi.Update{
Message: &tgbotapi.Message{
Chat: &tgbotapi.Chat{ID: chatID},
Text: "30",
},
}
handler.HandleUpdate(updateAge)
// Verify the final response
if len(mockBot.SentMessages) != 3 {
t.Errorf("Expected 3 messages, got %d", len(mockBot.SentMessages))
}
finalMsg := mockBot.SentMessages[2].(tgbotapi.MessageConfig)
expectedFinalText := "Alice, age 30, got it!"
if finalMsg.Text != expectedFinalText {
t.Errorf("Expected message '%s', got '%s'", expectedFinalText, finalMsg.Text)
}
// Verify that the state is cleared
state, err := handler.getState(chatID)
if err != nil {
t.Errorf("Error getting state: %v", err)
}
if state != "START" {
t.Errorf("Expected state to be 'START', got '%s'", state)
}
}
Explanation:
MockBotAPI: A mock implementation of the Telegram Bot API to capture sent messages.
Test Flow: Simulate the conversation steps and verify the bot's responses and state transitions.
Dockerfile
4. Dockerfile
Create a Dockerfile to containerize the bot application.
dockerfile
# Stage 1: Build the Go application
FROM golang:1.20-alpine AS builder
# Set the working directory inside the container
WORKDIR /app
# Copy the Go Modules manifests
COPY go.mod go.sum ./
# Download the dependencies
RUN go mod download
# Copy the source code
COPY . .
# Build the application
RUN CGO_ENABLED=0 GOOS=linux go build -o bot main.go
# Stage 2: Run the application
FROM alpine:latest
# Install BadgerDB dependencies
RUN apk add --no-cache ca-certificates
# Set the working directory inside the container
WORKDIR /root/
# Copy the binary from the builder stage
COPY --from=builder /app/bot .
# Copy other necessary files (if any)
COPY --from=builder /app/badger_db ./badger_db
# Expose any ports if needed (not required for Telegram bots)
# EXPOSE 8080
# Set the environment variable for Telegram token
ENV TELEGRAM_TOKEN=your_telegram_token_here
# Command to run the executable
CMD ["./bot"]
Instructions:
Replace your_telegram_token_here with your actual bot token or provide it at runtime using environment variables.
Build the Docker image:
bash
docker build -t telegram-bot .
Run the Docker container:
bash
docker run -d --name my_telegram_bot -e TELEGRAM_TOKEN=your_telegram_token_here telegram-bot
Final Notes
Persistence: The bot uses BadgerDB for persisting conversation states and user data.
Testing: Tests simulate the interaction flow and verify state management without actual Telegram API calls.
Dockerization: The Dockerfile builds a minimal image for efficient deployment.
Feel free to let me know if you need further customization or assistance with deployment!