Sure!
Below is a Go implementation of the persistentconversationbot.py example from the python-telegram-bot library. This bot uses Redis for persistence to store user conversation states across restarts. Included are unit tests and a Dockerfile for containerization.
Go Implementation (main.go):
package main
import (
"context"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/go-redis/redis/v8"
tb "gopkg.in/tucnak/telebot.v2" // Telegram Bot API for Go
)
// Define conversation states
const (
StateSTART = "START"
StateNAME = "NAME"
StateAGE = "AGE"
StateGENDER = "GENDER"
StateSUMMARY = "SUMMARY"
StateEND = "END"
)
// User struct to store user information
type User struct {
Name string
Age int
Gender string
}
var redisClient *redis.Client
// Helper functions for Redis keys
func getUserKey(chatID int64) string {
return "user:" + strconv.FormatInt(chatID, 10)
}
func getUserStateKey(chatID int64) string {
return "user_state:" + strconv.FormatInt(chatID, 10)
}
// Functions to save and load user state
func saveUserState(chatID int64, state string) error {
ctx := context.Background()
return redisClient.Set(ctx, getUserStateKey(chatID), state, 0).Err()
}
func loadUserState(chatID int64) (string, error) {
ctx := context.Background()
state, err := redisClient.Get(ctx, getUserStateKey(chatID)).Result()
if err == redis.Nil {
return StateSTART, nil
}
return state, err
}
// Functions to save and load user data
func saveUserData(chatID int64, user *User) error {
ctx := context.Background()
data := map[string]interface{}{
"Name": user.Name,
"Age": user.Age,
"Gender": user.Gender,
}
return redisClient.HMSet(ctx, getUserKey(chatID), data).Err()
}
func loadUserData(chatID int64) (*User, error) {
ctx := context.Background()
data, err := redisClient.HGetAll(ctx, getUserKey(chatID)).Result()
if err != nil {
return nil, err
}
if len(data) == 0 {
return &User{}, nil
}
age, _ := strconv.Atoi(data["Age"])
return &User{
Name: data["Name"],
Age: age,
Gender: data["Gender"],
}, nil
}
// Function to clear user data
func clearUserData(chatID int64) {
ctx := context.Background()
redisClient.Del(ctx, getUserKey(chatID))
redisClient.Del(ctx, getUserStateKey(chatID))
}
// Main function
func main() {
token := os.Getenv("TELEGRAM_TOKEN")
if token == "" {
log.Fatal("TELEGRAM_TOKEN environment variable not set")
}
// Initialize Redis client
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" {
redisAddr = "localhost:6379"
}
redisClient = redis.NewClient(&redis.Options{
Addr: redisAddr,
})
ctx := context.Background()
if err := redisClient.Ping(ctx).Err(); err != nil {
log.Fatalf("Failed to connect to Redis: %v", err)
}
// Initialize Telegram bot
b, err := tb.NewBot(tb.Settings{
Token: token,
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Fatal(err)
return
}
// Handle /start command
b.Handle("/start", func(m *tb.Message) {
chatID := m.Chat.ID
clearUserData(chatID)
b.Send(m.Chat, "Hi! What's your name?")
saveUserState(chatID, StateNAME)
})
// Handle text messages
b.Handle(tb.OnText, func(m *tb.Message) {
if m.Text == "/start" {
return
}
handleMessage(b, m)
})
log.Println("Bot is running...")
b.Start()
}
// Function to handle messages based on user state
func handleMessage(b *tb.Bot, m *tb.Message) {
chatID := m.Chat.ID
state, err := loadUserState(chatID)
if err != nil {
log.Println("Error loading user state:", err)
b.Send(m.Chat, "An error occurred. Please try again later.")
return
}
user, err := loadUserData(chatID)
if err != nil {
log.Println("Error loading user data:", err)
b.Send(m.Chat, "An error occurred. Please try again later.")
return
}
switch state {
case StateNAME:
user.Name = m.Text
b.Send(m.Chat, "Nice to meet you, "+user.Name+"! How old are you?")
saveUserData(chatID, user)
saveUserState(chatID, StateAGE)
case StateAGE:
age, err := strconv.Atoi(m.Text)
if err != nil {
b.Send(m.Chat, "Please enter a valid number for your age.")
return
}
user.Age = age
b.Send(m.Chat, "Got it! What's your gender?")
saveUserData(chatID, user)
saveUserState(chatID, StateGENDER)
case StateGENDER:
user.Gender = m.Text
summary := strings.Builder{}
summary.WriteString("Thank you for the information.\n")
summary.WriteString("Name: " + user.Name + "\n")
summary.WriteString("Age: " + strconv.Itoa(user.Age) + "\n")
summary.WriteString("Gender: " + user.Gender + "\n")
b.Send(m.Chat, summary.String())
saveUserData(chatID, user)
saveUserState(chatID, StateEND)
case StateEND:
b.Send(m.Chat, "Thank you! If you want to start over, send /start.")
default:
b.Send(m.Chat, "Please type /start to begin.")
}
}
Unit Tests (main_test.go):
package main
import (
"context"
"testing"
"github.com/go-redis/redis/v8"
)
// Test saving and loading user state
func TestUserStatePersistence(t *testing.T) {
// Initialize Redis client for testing
redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 1, // Use a separate DB for testing
})
defer redisClient.FlushDB(context.Background())
chatID := int64(12345)
state := StateAGE
err := saveUserState(chatID, state)
if err != nil {
t.Fatalf("Failed to save state: %v", err)
}
loadedState, err := loadUserState(chatID)
if err != nil {
t.Fatalf("Failed to load state: %v", err)
}
if loadedState != state {
t.Errorf("Expected state %s, got %s", state, loadedState)
}
}
// Test saving and loading user data
func TestUserDataPersistence(t *testing.T) {
// Initialize Redis client for testing
redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 1, // Use a separate DB for testing
})
defer redisClient.FlushDB(context.Background())
chatID := int64(12345)
user := &User{
Name: "Alice",
Age: 30,
Gender: "Female",
}
err := saveUserData(chatID, user)
if err != nil {
t.Fatalf("Failed to save user data: %v", err)
}
loadedUser, err := loadUserData(chatID)
if err != nil {
t.Fatalf("Failed to load user data: %v", err)
}
if loadedUser.Name != user.Name {
t.Errorf("Expected Name %s, got %s", user.Name, loadedUser.Name)
}
if loadedUser.Age != user.Age {
t.Errorf("Expected Age %d, got %d", user.Age, loadedUser.Age)
}
if loadedUser.Gender != user.Gender {
t.Errorf("Expected Gender %s, got %s", user.Gender, loadedUser.Gender)
}
}
// Test clearing user data
func TestClearUserData(t *testing.T) {
// Initialize Redis client for testing
redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
DB: 1, // Use a separate DB for testing
})
defer redisClient.FlushDB(context.Background())
chatID := int64(12345)
user := &User{
Name: "Bob",
Age: 28,
Gender: "Male",
}
saveUserData(chatID, user)
saveUserState(chatID, StateEND)
clearUserData(chatID)
loadedUser, err := loadUserData(chatID)
if err != nil {
t.Fatalf("Failed to load user data: %v", err)
}
if loadedUser.Name != "" || loadedUser.Age != 0 || loadedUser.Gender != "" {
t.Errorf("Expected user data to be cleared, got %+v", loadedUser)
}
loadedState, err := loadUserState(chatID)
if err != nil {
t.Fatalf("Failed to load state: %v", err)
}
if loadedState != StateSTART {
t.Errorf("Expected state to be START, got %s", loadedState)
}
}
Dockerfile:
# Build stage
FROM golang:1.20-alpine AS builder
# Install dependencies
RUN apk update && apk add --no-cache git
# Set up working directory
WORKDIR /app
# Copy go.mod and go.sum
COPY go.mod go.sum ./
# Download dependencies
RUN go mod download
# Copy the source code
COPY . .
# Build the binary
RUN CGO_ENABLED=0 GOOS=linux go build -o app .
# Final stage
FROM alpine:latest
# Install CA certificates
RUN apk --no-cache add ca-certificates
# Set working directory
WORKDIR /root/
# Copy the binary from the builder stage
COPY --from=builder /app/app .
# Expose the necessary port (if any)
# EXPOSE 8080
# Entry point
CMD ["./app"]
Instructions:
-
Environment Variables:
TELEGRAM_TOKEN: Your Telegram bot's API token.
REDIS_ADDR (optional): Address of the Redis server (default is localhost:6379).
-
Running the Bot Locally:
- Ensure you have Redis running on your machine.
- Set the
TELEGRAM_TOKEN environment variable.
- Run the bot using
go run main.go.
-
Running Tests:
- Make sure Redis is running.
- Run tests using
go test.
-
Building the Docker Image:
-
Running the Docker Container:
-
Notes:
- The bot uses Redis for persistence. Ensure that Redis is accessible to the bot.
- The bot handles a simple conversation by asking the user's name, age, and gender, and then summarizing the information.
- The conversation state is stored in Redis, allowing the bot to resume conversations after restarts.
Dependencies:
Feel free to customize the code and add more features as needed!