Sure! Let's continue implementing the timezone feature for your Telegram bot. We'll tackle this in two main steps:
- Track user state to handle setting the timezone.
- Handle timezones when setting timed reminders.
1. Tracking User State for Timezone Setting
To keep track of what the user is doing (e.g., adding their timezone), we need a way to store the user's current state or expected next action. Here's how we can implement this:
Modify the User Model
Add a new field PendingAction to the User model to track what action the user is currently performing.
// internal/models/user.go
package models
type User struct {
ID int64 `gorm:"primaryKey" json:"id"`
UserName string `json:"username"`
Timezone string `json:"timezone"`
PendingAction string `json:"pending_action"` // New field to track pending action
}
Update Database Schema
Since we've modified the User model, we need to migrate the database schema.
// internal/database/database.go
func InitDB() {
var err error
DB, err = gorm.Open(sqlite.Open("bot.db"), &gorm.Config{})
if err != nil {
logger.Log.Fatalf("Failed to connect to database: %v", err)
}
err = DB.AutoMigrate(&models.ToDo{}, &models.ToDoItem{}, &models.User{})
if err != nil {
logger.Log.Fatalf("Failed to migrate database schema: %v", err)
}
logger.Log.Info("Database initialized successfully")
}
GORM's AutoMigrate method will handle the addition of the new field.
Update the /start Handler
Modify the StartHandler to set the PendingAction to SetTimezone when a new user starts the bot.
// internal/handler/handler.go
func StartHandler(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID != int64(adminID) {
return
}
var user models.User
result := database.DB.First(&user, userID)
if result.Error != nil {
// New user
user = models.User{
ID: userID,
UserName: update.Message.From.Username,
PendingAction: "SetTimezone", // Set pending action
}
database.DB.Create(&user)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Welcome! Please send me your timezone in 'Area/City' format (e.g., 'Europe/London').",
})
} else if user.Timezone == "" {
// User exists but timezone is not set
user.PendingAction = "SetTimezone"
database.DB.Save(&user)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Please send me your timezone in 'Area/City' format (e.g., 'Europe/London').",
})
} else {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Welcome back!",
})
}
}
Handle Incoming Messages for Timezone
Update the DefaultHandler to check if the user has a pending action and handle it accordingly.
// internal/handler/handler.go
func DefaultHandler(ctx context.Context, b *bot.Bot, update *tgmodels.Update, processor llm.LLMProcessor) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID != int64(adminID) {
return
}
if update.Message == nil {
return
}
// Fetch the user from the database
var user models.User
result := database.DB.First(&user, userID)
if result.Error != nil {
logger.Log.Errorf("User not found: %v", result.Error)
return
}
// Check if the user has a pending action
if user.PendingAction == "SetTimezone" {
// User is expected to send timezone
timezone := update.Message.Text
if validTimezone(timezone) {
user.Timezone = timezone
user.PendingAction = "" // Clear pending action
database.DB.Save(&user)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Timezone set successfully!",
})
} else {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Invalid timezone format. Please send in 'Area/City' format (e.g., 'Europe/London').",
})
}
return
}
// ... Existing code for handling voice messages
if update.Message.Text != "" {
return
}
if update.Message.Voice != nil {
// Handle voice message
// ... existing code ...
}
}
Implement Timezone Validation
Create a function to validate the timezone string.
// internal/handler/handler.go
import (
"time"
// ... other imports ...
)
// Add this function to validate timezone
func validTimezone(tz string) bool {
_, err := time.LoadLocation(tz)
return err == nil
}
Handling Timezone Updates Later
Allow users to update their timezone later if needed. Add a /settimezone command.
// cmd/bot/main.go
func main() {
// ... existing code ...
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, handler.StartHandler)
b.RegisterHandler(bot.HandlerTypeMessageText, "/settimezone", bot.MatchTypeExact, handler.SetTimezoneHandler)
b.Start(ctx)
}
Create the SetTimezoneHandler:
// internal/handler/handler.go
func SetTimezoneHandler(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID != int64(adminID) {
return
}
var user models.User
result := database.DB.First(&user, userID)
if result.Error != nil {
logger.Log.Errorf("User not found: %v", result.Error)
return
}
user.PendingAction = "SetTimezone"
database.DB.Save(&user)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Please send me your new timezone in 'Area/City' format (e.g., 'Europe/London').",
})
}
2. Handling Timezones for Timed Reminders
When setting timed reminders, we need to consider the user's timezone to ensure that reminders are sent at the correct local time.
Approach to Handling Timezones
- Store User's Timezone: We've already stored the user's timezone in the
User model.
- Parse Datetimes with Timezone: When scheduling reminders, parse the user's specified datetime with their timezone.
- Use a Scheduler: Implement a scheduler that can handle jobs to be executed at specific times.
Implementing Reminder Functionality
Let's assume that your bot allows users to create reminders via voice messages. We'll need to:
- Extract Reminder Information: Use the LLM to parse the voice message and extract the reminder text and time.
- Convert Reminder Time to UTC: Convert the reminder time from the user's timezone to UTC for consistent scheduling.
- Schedule the Reminder: Use a job scheduler to send the reminder at the specified time.
Modify LLM Processor to Handle Reminders
Update the LLM prompts and processing to handle reminders.
Update availableTools
Add a new function createReminder.
// internal/llm/tool.go
var availableTools = []llms.Tool{
// ... existing tools ...
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "createReminder",
Description: "Create a new reminder.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"reminder_time": map[string]any{
"type": "string",
"description": "Time of the reminder in user's local time (e.g., '2023-10-15 14:30').",
},
"message": map[string]any{
"type": "string",
"description": "Reminder message.",
},
},
"required": []string{"reminder_time", "message"},
},
},
},
}
Update System Prompt
Adjust the system prompt to instruct the LLM to handle reminders.
// internal/llm/prompt.go
const SPEECH_TO_TEXT_SYSTEN_PROMPT = `
You are an AI assistant helping the user to create new To-Do lists and set reminders.
You are provided with some tools. Do your best to figure out the user's intent
and then return the tool call. If the user speaks to you in another language, keep the name and content in the original language.
If you cannot understand the user's intention, reply with "I do not understand you."
Available tools:
1. createNewToDo - Create a new To-Do List.
2. createReminder - Create a new reminder.
After transcribing the voice, do your best to figure out if there are typos and fix them before making the function call.
`
Handle Function Calls for Reminders
Update the ProcessAudio method to handle createReminder calls.
// internal/llm/googleai_processor.go
func (p *GoogleAIProcessor) ProcessAudio(ctx context.Context, audioData []byte, userID int64) (*models.GenericResponse, error) {
// ... existing code ...
if answer.Choices[0].ToolCalls != nil {
functionCall := answer.Choices[0].ToolCalls[0].FunctionCall
switch functionCall.Name {
case "createNewToDo":
args := functionCall.Arguments
logger.Log.Infof("createNewToDo function call with args: %v", args)
todo, _ := createToDo(args, userID)
return &models.GenericResponse{
Type: models.ResponseToDo,
ToDo: todo,
}, nil
case "createReminder":
args := functionCall.Arguments
logger.Log.Infof("createReminder function call with args: %v", args)
reminder, _ := createReminder(args, userID)
return &models.GenericResponse{
Type: models.ResponseReminder,
Reminder: reminder,
}, nil
}
}
// ... existing code ...
}
Implement createReminder Function
// internal/llm/util.go
import (
// ... existing imports ...
"time"
)
func createReminder(s string, userID int64) (*models.Reminder, error) {
var rawArgs struct {
ReminderTime string `json:"reminder_time"`
Message string `json:"message"`
}
if err := json.Unmarshal([]byte(s), &rawArgs); err != nil {
logger.Log.Errorf("Error parsing arguments: %v", err)
return nil, err
}
// Fetch user to get timezone
var user models.User
result := database.DB.First(&user, userID)
if result.Error != nil {
logger.Log.Errorf("User not found: %v", result.Error)
return nil, result.Error
}
// Parse reminder time in user's timezone
loc, err := time.LoadLocation(user.Timezone)
if err != nil {
logger.Log.Errorf("Error loading timezone: %v", err)
return nil, err
}
reminderTime, err := time.ParseInLocation("2006-01-02 15:04", rawArgs.ReminderTime, loc)
if err != nil {
logger.Log.Errorf("Error parsing reminder time: %v", err)
return nil, err
}
// Convert to UTC
reminderTimeUTC := reminderTime.UTC()
reminder := &models.Reminder{
UserID: userID,
Message: rawArgs.Message,
ReminderTime: reminderTimeUTC,
}
if err := database.DB.Create(reminder).Error; err != nil {
logger.Log.Errorf("Error saving Reminder to database: %v", err)
return nil, err
}
logger.Log.Infof("Reminder created and saved to database: %v", reminder)
return reminder, nil
}
Add Reminder Model
Create a Reminder model to store reminders.
// internal/models/reminder.go
package models
import "time"
type Reminder struct {
ID int64 `gorm:"primaryKey" json:"id"`
UserID int64 `json:"user_id"`
Message string `json:"message"`
ReminderTime time.Time `json:"reminder_time"` // Stored in UTC
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Update the database migration to include the Reminder model.
// internal/database/database.go
func InitDB() {
var err error
DB, err = gorm.Open(sqlite.Open("bot.db"), &gorm.Config{})
if err != nil {
logger.Log.Fatalf("Failed to connect to database: %v", err)
}
err = DB.AutoMigrate(&models.ToDo{}, &models.ToDoItem{}, &models.User{}, &models.Reminder{})
if err != nil {
logger.Log.Fatalf("Failed to migrate database schema: %v", err)
}
logger.Log.Info("Database initialized successfully")
}
Schedule Reminders
Implement a scheduler to check for due reminders and send messages.
Install Scheduler Package
Use a scheduler like robfig/cron:
go get github.com/robfig/cron/v3
Set Up Cron Job
// cmd/bot/main.go
import (
// ... existing imports ...
"asdf/tg_assistant_bot/internal/scheduler"
)
func main() {
// ... existing code ...
// Start the reminder scheduler
go scheduler.StartReminderScheduler(ctx, b)
b.Start(ctx)
}
Create Scheduler Package
// internal/scheduler/scheduler.go
package scheduler
import (
"context"
"time"
"github.com/go-telegram/bot"
"github.com/robfig/cron/v3"
"asdf/tg_assistant_bot/internal/database"
"asdf/tg_assistant_bot/internal/models"
"asdf/tg_assistant_bot/pkg/logger"
)
func StartReminderScheduler(ctx context.Context, b *bot.Bot) {
c := cron.New()
// Schedule the job to run every minute
c.AddFunc("@every 1m", func() {
checkAndSendReminders(ctx, b)
})
c.Start()
}
func checkAndSendReminders(ctx context.Context, b *bot.Bot) {
// Get current UTC time
now := time.Now().UTC()
// Fetch reminders that are due
var reminders []models.Reminder
result := database.DB.Where("reminder_time <= ?", now).Find(&reminders)
if result.Error != nil {
logger.Log.Errorf("Error fetching reminders: %v", result.Error)
return
}
for _, reminder := range reminders {
// Send reminder message
_, err := b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: reminder.UserID,
Text: reminder.Message,
})
if err != nil {
logger.Log.Errorf("Error sending reminder: %v", err)
continue
}
// Delete the sent reminder
database.DB.Delete(&reminder)
}
}
Update Response Handling
Update the GenericResponse to include the Reminder type.
// internal/models/response.go
package models
type ResponseType int
const (
ResponseText ResponseType = iota
ResponseToDo
ResponseReminder
ResponseNote
)
type GenericResponse struct {
Type ResponseType
Text string // Used for simple text responses
ToDo *ToDo // Used for ToDo responses
Reminder *Reminder // Used for Reminder responses
}
Update the DefaultHandler to handle ResponseReminder.
// internal/handler/handler.go
func DefaultHandler(ctx context.Context, b *bot.Bot, update *tgmodels.Update, processor llm.LLMProcessor) {
// ... existing code ...
if update.Message.Voice != nil {
m, _ := b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Processing... please wait",
})
response, err := handleVoiceMessage(ctx, b, update, processor)
if err != nil {
b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: m.Chat.ID,
MessageID: m.ID,
Text: "Can't process voice message request right now",
})
return
}
switch response.Type {
case models.ResponseText:
b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: m.Chat.ID,
MessageID: m.ID,
Text: response.Text,
})
case models.ResponseToDo:
// ... existing ToDo handling ...
case models.ResponseReminder:
reminderTimeUserTZ := response.Reminder.ReminderTime.In(time.UTC) // Adjust as needed
b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: m.Chat.ID,
MessageID: m.ID,
Text: fmt.Sprintf("Reminder set for %s: %s", reminderTimeUserTZ.Format("2006-01-02 15:04"), response.Reminder.Message),
})
case models.ResponseNote:
// Handle notes if implemented
}
}
}
Summary
- Tracking User State: We've added a
PendingAction field to the User model to keep track of what the user is doing, allowing us to handle their response appropriately.
- Handling Timezones: By storing the user's timezone and converting times to UTC, we ensure reminders are scheduled correctly.
- Scheduling Reminders: We've set up a scheduler that checks for due reminders every minute and sends them to the user.
- LLM Integration: Updated the LLM prompts and processing to extract and handle reminders, using function calls and arguments.
Next Steps
- Error Handling: Improve error messages sent to the user for better clarity.
- Time Parsing: Enhance the time parsing to be more flexible (e.g., handle relative times like "in 2 hours").
- User Feedback: After setting a reminder, confirm with the user by summarizing the reminder details.
- Testing: Thoroughly test the new features to ensure reliability.
Feel free to ask if you need further assistance or adjustments!