Certainly! Let's restructure your Go project to make it more modular, idiomatic, and maintainable. We'll organize the code into packages, use interfaces where appropriate, and implement structured logging using logrus. Here's how we can approach this:
Project Structure
We'll reorganize your project into the following structure:
.
├── cmd
│ └── bot
│ └── main.go
├── internal
│ ├── ai
│ │ └── client.go
│ ├── audio
│ │ └── converter.go
│ ├── handler
│ │ └── handler.go
│ ├── logging
│ │ └── logging.go
│ └── storage
│ └── storage.go
├── go.mod
└── go.sum
Detailed Implementation
1. Logging Package
Create a logging package to initialize and configure structured logging using logrus.
// internal/logging/logging.go
package logging
import (
"os"
log "github.com/sirupsen/logrus"
)
func Init() {
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
}
2. AI Package
Create an ai package with an AIClient interface and an OpenAIClient implementation.
// internal/ai/client.go
package ai
import (
"context"
"os"
log "github.com/sirupsen/logrus"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/googleai"
)
type AIClient interface {
GenerateResponse(ctx context.Context, audioData []byte) (string, error)
}
type OpenAIClient struct {
llm llms.LLM
}
func NewAIClient() (AIClient, error) {
ctx := context.Background()
apiKey := os.Getenv("GOOGLE_API_KEY")
llm, err := googleai.New(ctx, googleai.WithAPIKey(apiKey))
if err != nil {
return nil, err
}
return &OpenAIClient{llm: llm}, nil
}
func (c *OpenAIClient) GenerateResponse(ctx context.Context, audioData []byte) (string, error) {
systemPrompt := `
You will be sent audio files and they may be in variety of languages.
Try to classify what the user means, you have 3 options:
[NEW_REMINDER]
User wants to create a new reminder. Extract info what they need to be reminded of and when.
[NEW_TODO]
User wants to create some sort of TODO LIST. Extract all todos into array of strings [todo1,todo2]. don't translate it to English, keep language of the user.
[UNKNOWN]
Can't classify. Respond with what you understood from the user."`
answer, err := c.llm.GenerateContent(
ctx,
[]llms.MessageContent{
{
Role: llms.ChatMessageTypeHuman,
Parts: []llms.ContentPart{
llms.TextPart(systemPrompt),
llms.BinaryPart("audio/wav", audioData),
},
},
},
llms.WithMaxTokens(4000),
llms.WithTemperature(0.1),
llms.WithModel("gemini-1.5-pro"),
)
if err != nil {
return "", err
}
return answer.Choices[0].Content, nil
}
3. Audio Package
Create an audio package to handle audio conversion.
// internal/audio/converter.go
package audio
import (
"fmt"
"os"
"os/exec"
log "github.com/sirupsen/logrus"
)
type AudioConverter interface {
Convert(inputPath, outputPath string) error
}
type FFmpegConverter struct{}
func NewFFmpegConverter() AudioConverter {
return &FFmpegConverter{}
}
func (c *FFmpegConverter) Convert(inputPath, outputPath string) error {
cmd := exec.Command("ffmpeg", "-y", "-i", inputPath, outputPath)
output, err := cmd.CombinedOutput()
if err != nil {
log.Errorf("FFmpeg conversion error: %v", string(output))
return fmt.Errorf("FFmpeg conversion error: %v", err)
}
return nil
}
4. Storage Package
Create a storage package to handle data persistence.
// internal/storage/storage.go
package storage
type Storage interface {
SaveReminder(userID int64, reminder string, time string) error
SaveTodoList(userID int64, todos []string) error
}
type InMemoryStorage struct {
reminders map[int64][]Reminder
todos map[int64][]string
}
type Reminder struct {
Text string
Time string
}
func NewInMemoryStorage() Storage {
return &InMemoryStorage{
reminders: make(map[int64][]Reminder),
todos: make(map[int64][]string),
}
}
func (s *InMemoryStorage) SaveReminder(userID int64, reminder string, time string) error {
s.reminders[userID] = append(s.reminders[userID], Reminder{Text: reminder, Time: time})
return nil
}
func (s *InMemoryStorage) SaveTodoList(userID int64, todos []string) error {
s.todos[userID] = append(s.todos[userID], todos...)
return nil
}
5. Handler Package
Create a handler package to manage Telegram bot interactions.
// internal/handler/handler.go
package handler
import (
"context"
"fmt"
"io"
"net/http"
"os"
"strings"
log "github.com/sirupsen/logrus"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"myproject/internal/ai"
"myproject/internal/audio"
"myproject/internal/storage"
)
type BotHandler struct {
Bot *bot.Bot
AIClient ai.AIClient
Storage storage.Storage
AudioConverter audio.AudioConverter
}
func NewBotHandler(botToken string, aiClient ai.AIClient, storage storage.Storage, converter audio.AudioConverter) (*BotHandler, error) {
bot, err := bot.New(botToken)
if err != nil {
return nil, err
}
handler := &BotHandler{
Bot: bot,
AIClient: aiClient,
Storage: storage,
AudioConverter: converter,
}
bot.RegisterHandler(handler.HandleUpdate)
return handler, nil
}
func (h *BotHandler) HandleUpdate(ctx context.Context, update *models.Update) {
if update.Message == nil {
return
}
if update.Message.Voice != nil {
h.handleVoiceMessage(ctx, update.Message)
} else {
h.handleTextMessage(ctx, update.Message)
}
}
func (h *BotHandler) handleVoiceMessage(ctx context.Context, message *models.Message) {
// Download the voice message
file, err := h.Bot.GetFile(ctx, &bot.GetFileParams{
FileID: message.Voice.FileID,
})
if err != nil {
log.Errorf("Error getting file: %v", err)
return
}
downloadURL := h.Bot.FileDownloadLink(file)
resp, err := http.Get(downloadURL)
if err != nil {
log.Errorf("Error downloading file: %v", err)
return
}
defer resp.Body.Close()
fileData, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("Error reading file: %v", err)
return
}
inputFileName := fmt.Sprintf("%s.oga", file.FileUniqueID)
err = os.WriteFile(inputFileName, fileData, 0644)
if err != nil {
log.Errorf("Error writing file: %v", err)
return
}
defer os.Remove(inputFileName)
outputFileName := fmt.Sprintf("%s.wav", file.FileUniqueID)
err = h.AudioConverter.Convert(inputFileName, outputFileName)
if err != nil {
log.Errorf("Error converting audio: %v", err)
return
}
defer os.Remove(outputFileName)
audioData, err := os.ReadFile(outputFileName)
if err != nil {
log.Errorf("Error reading converted audio file: %v", err)
return
}
responseText, err := h.AIClient.GenerateResponse(ctx, audioData)
if err != nil {
log.Errorf("Error generating AI response: %v", err)
return
}
h.processAIResponse(ctx, message.Chat.ID, responseText)
}
func (h *BotHandler) handleTextMessage(ctx context.Context, message *models.Message) {
// Handle text messages here
}
func (h *BotHandler) processAIResponse(ctx context.Context, chatID int64, aiResponse string) {
// Process the AI response, extract intents, and store data
// For simplicity, just send the response back to the user
_, err := h.Bot.SendMessage(ctx, &bot.SendMessageParams{
ChatID: chatID,
Text: aiResponse,
})
if err != nil {
log.Errorf("Error sending message: %v", err)
}
}
6. Main Package
Finally, update your main.go to initialize and run the bot.
// cmd/bot/main.go
package main
import (
"context"
"os"
"os/signal"
log "github.com/sirupsen/logrus"
"github.com/joho/godotenv"
"myproject/internal/ai"
"myproject/internal/audio"
"myproject/internal/handler"
"myproject/internal/logging"
"myproject/internal/storage"
)
func main() {
logging.Init()
if err := godotenv.Load(); err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
botToken := os.Getenv("TELEGRAM_API_KEY")
if botToken == "" {
log.Fatal("TELEGRAM_API_KEY is not set in the environment")
}
aiClient, err := ai.NewAIClient()
if err != nil {
log.Fatalf("Error initializing AI client: %v", err)
}
storage := storage.NewInMemoryStorage()
converter := audio.NewFFmpegConverter()
botHandler, err := handler.NewBotHandler(botToken, aiClient, storage, converter)
if err != nil {
log.Fatalf("Error initializing bot: %v", err)
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
botHandler.Bot.Start(ctx)
}
Additional Notes
-
Interfaces and Abstraction: We've used interfaces (AIClient, AudioConverter, Storage) to decouple implementations from their usage, making it easier to swap out implementations (e.g., using a different AI provider or storage backend).
-
Error Handling: Errors are properly checked and logged using logrus. Fatal errors are reported using log.Fatalf, and other errors are logged with appropriate severity levels.
-
Idiomatic Go Practices:
- Avoid global variables; dependencies are passed through function parameters or struct fields.
- Use proper package naming conventions.
- Keep functions small and focused on a single task.
-
Modularity: Each package has a clear responsibility, making the codebase easier to navigate and maintain.
-
Logging: Using logrus provides structured logging with severity levels, which is more flexible and powerful than the standard log package.
Future Enhancements
-
Persistent Storage: Implement a persistent storage backend (e.g., a database) instead of an in-memory storage to persist todos and reminders across restarts.
-
Configuration Management: Use a configuration package to manage environment variables and configuration files.
-
Testing: Add unit tests for each package, mocking external dependencies where appropriate.
-
CI/CD Pipeline: Set up a continuous integration and deployment pipeline to automate testing and deployment.
-
Containerization: Dockerize the application for easier deployment.
Conclusion
This restructuring provides a solid foundation for your Telegram productivity bot, adhering to Go best practices. Each component is modular, testable, and maintainable, allowing you to expand functionality with ease. Remember to replace "myproject" with your actual module name in the import paths.