To accomplish your requirements, we need to update the following:
- Add
createdAt and updatedAt timestamps to the ToDo models.
- Implement a flow where the bot asks the user for their timezone upon receiving the
/start command and saves it to the database.
Below are the steps and code modifications needed to implement these features.
1. Add createdAt and updatedAt to the ToDo models
We will update the ToDo and ToDoItem structs to include CreatedAt and UpdatedAt fields. GORM automatically manages these fields if they are present in the model.
File: internal/models/todo.go
package models
import (
"time"
)
type ToDo struct {
ID int64 `gorm:"primaryKey" json:"id"`
UserID int64 `json:"user_id"`
Name string `json:"name"`
Items []ToDoItem `gorm:"foreignKey:ToDoID" json:"items"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type ToDoItem struct {
ID int64 `gorm:"primaryKey" json:"id"`
ToDoID int64 `json:"todo_id"`
Name string `json:"name"`
Completed bool `json:"completed"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Explanation:
- Imported the
time package to use time.Time.
- Added
CreatedAt and UpdatedAt fields to both ToDo and ToDoItem structs.
- GORM will automatically populate these fields with the current timestamp when creating or updating records.
2. Implement timezone collection and storage upon /start command
Overview:
- Create a
User model to store user-specific data, including the timezone.
- Update the database initialization to include the new
User model.
- Implement a
/start command handler that asks the user for their timezone.
- Save the user's timezone in the database.
- Modify the LLM processor or other relevant parts to utilize the user's timezone when creating reminders.
Step-by-Step Implementation:
a. Create the User model
File: internal/models/user.go
package models
type User struct {
ID int64 `gorm:"primaryKey" json:"id"`
UserName string `json:"username"`
Timezone string `json:"timezone"`
}
Explanation:
- Added a
User struct with fields for ID, UserName, and Timezone.
ID corresponds to the Telegram user's ID.
UserName is optional but can be helpful for logging or additional features.
Timezone will store the user's timezone information.
b. Update the database initialization
File: internal/database/database.go
package database
import (
"test/tg_assistant_bot/internal/models"
"test/tg_assistant_bot/pkg/logger"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var DB *gorm.DB
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)
}
// Auto-migrate the models
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")
}
Explanation:
- Included
&models.User{} in the AutoMigrate function to ensure the users table is created or updated in the database.
c. Implement the /start command handler
File: internal/handler/handler.go
We'll add a new handler function for the /start command and modify the default message handler to process the timezone input.
package handler
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/go-telegram/bot"
tgmodels "github.com/go-telegram/bot/models"
"test/tg_assistant_bot/internal/config"
"test/tg_assistant_bot/internal/database"
"test/tg_assistant_bot/internal/llm"
"test/tg_assistant_bot/internal/models"
"test/tg_assistant_bot/pkg/logger"
"github.com/go-telegram/bot/utils"
"github.com/jinzhu/now"
"github.com/tkuchiki/go-timezone"
)
func StartHandler(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
// Only proceed if the message is from the admin user
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID != int64(adminID) {
return
}
// Check if the user already exists
var user models.User
result := database.DB.First(&user, userID)
if result.Error != nil {
// User not found, create a new user record
user = models.User{
ID: userID,
UserName: update.Message.From.Username,
}
database.DB.Create(&user)
// Ask for timezone
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
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 {
// User exists and timezone is set
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "You have already set your timezone.",
})
}
}
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
}
if update.Message.Text != "" {
text := update.Message.Text
// Check if we're expecting a timezone from the user
var user models.User
result := database.DB.First(&user, userID)
if result.Error == nil && user.Timezone == "" {
// User exists but timezone is not set, process the timezone input
tz := strings.TrimSpace(text)
// Validate the timezone
if isValidTimezone(tz) {
user.Timezone = tz
database.DB.Save(&user)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: fmt.Sprintf("Timezone '%s' saved successfully!", tz),
})
} 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
}
// Handle other text messages or commands here if needed
return
}
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 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:
var todosText string
todosName := "<b>" + utils.EscapeHTML(response.ToDo.Name) + "</b>"
for _, todo := range response.ToDo.Items {
todosText += utils.EscapeHTML(todo.Name) + "\n"
}
b.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: m.Chat.ID,
MessageID: m.ID,
Text: fmt.Sprintf("<b>Here are your ToDo items:</b>\n\n%s\n%s", todosName, todosText),
ParseMode: tgmodels.ParseModeHTML,
})
case models.ResponseReminder:
// Handle reminders here
case models.ResponseNote:
// Handle notes here
}
}
}
func isValidTimezone(tz string) bool {
tz = strings.TrimSpace(tz)
loc, err := time.LoadLocation(tz)
if err != nil || loc == nil {
return false
}
return true
}
Explanation:
- StartHandler: Handles the
/start command.
- Checks if the user is already in the database.
- If not, creates a new
User record without a timezone and asks for the timezone.
- If the user exists but the timezone is not set, asks again for the timezone.
- If the user exists and the timezone is set, informs the user that the timezone is already saved.
- DefaultHandler: Modified to check if the user needs to provide a timezone before processing other messages.
- If the user's timezone is not set, it processes the text message as a timezone input.
- Validates the timezone using the
isValidTimezone function.
- Saves the timezone to the user's record in the database.
- isValidTimezone: Validates the timezone string using Go's
time package.
- Note: Imported
github.com/go-telegram/bot/utils for HTML escaping to prevent message formatting issues.
d. Update the LLM processor to use user's timezone for reminders
You need to update your LLM processing logic to handle reminders based on the user's timezone. Here's how you might modify the handleVoiceMessage function and related code.
File: internal/handler/handler.go
Add timezone support in handleVoiceMessage:
func handleVoiceMessage(ctx context.Context, b *bot.Bot, update *tgmodels.Update, processor llm.LLMProcessor) (*models.GenericResponse, error) {
// Existing code...
userID := update.Message.From.ID
// Retrieve user's timezone
var user models.User
result := database.DB.First(&user, userID)
userTimezone := "UTC" // Default timezone
if result.Error == nil && user.Timezone != "" {
userTimezone = user.Timezone
}
// Pass the user's timezone to the processor
response, err := processor.ProcessAudio(ctx, finalFile, userID, userTimezone)
if err != nil {
logger.Log.Errorf("Error processing audio with LLM: %v", err)
return nil, err
}
return response, nil
}
e. Modify the LLM processor interface and implementations
Update the LLMProcessor interface to accept the user's timezone.
File: internal/llm/processor.go
package llm
import (
"context"
"test/tg_assistant_bot/internal/models"
)
type LLMProcessor interface {
ProcessAudio(ctx context.Context, audioData []byte, userID int64, timezone string) (*models.GenericResponse, error)
}
Update the processors to accept the timezone parameter.
File: internal/llm/googleai_processor.go
func (p *GoogleAIProcessor) ProcessAudio(ctx context.Context, audioData []byte, userID int64, timezone string) (*models.GenericResponse, error) {
// Existing code...
// Use the timezone in your prompt or processing logic
}
Note: The actual implementation of handling reminders based on timezone would involve:
- Parsing phrases like "remind me in 5 hours to do X".
- Calculating the reminder time based on the user's timezone.
- Scheduling a job or using a cron-like system to send the reminder at the correct time.
Implementing a full scheduling system is beyond the scope of this answer but would involve integrating with a task scheduler or queuing system.
f. Update the LLM Prompt
Adjust your LLM prompt to include instructions for handling reminders and timezones.
File: internal/llm/prompt.go
package llm
const SPEECH_TO_TEXT_SYSTEN_PROMPT = `
You are an AI assistant helping the user with tasks such as creating To-Do lists and setting reminders.
You are provided with some tools to perform these tasks.
When the user asks you to create a reminder, extract the time and content of the reminder.
Take into account the user's timezone when interpreting times.
If the user speaks in another language, keep the names and content in the original language.
If you cannot understand the user, reply with "I do not understand you".
`
g. Add a tool for creating reminders
File: internal/llm/tool.go
Add a new tool definition for creating reminders.
var availableTools = []llms.Tool{
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "createNewToDo",
Description: "Create a new To-Do List.",
Parameters: map[string]any{
// Existing parameters...
},
},
},
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "createReminder",
Description: "Create a new reminder.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"time": map[string]any{
"type": "string",
"description": "Time when the reminder should trigger (in user's local time), e.g., '2023-10-20 15:04'.",
},
"content": map[string]any{
"type": "string",
"description": "Content of the reminder.",
},
},
"required": []string{"time", "content"},
},
},
},
}
h. Implement the reminder creation
You need to handle the createReminder function call in your LLM processor and schedule the reminders accordingly.
File: internal/llm/googleai_processor.go
func (p *GoogleAIProcessor) ProcessAudio(ctx context.Context, audioData []byte, userID int64, timezone string) (*models.GenericResponse, error) {
// Existing code...
if answer.Choices[0].ToolCalls != nil {
switch answer.Choices[0].ToolCalls[0].FunctionCall.Name {
case "createNewToDo":
// Existing ToDo creation code...
case "createReminder":
args := answer.Choices[0].ToolCalls[0].FunctionCall.Arguments
logger.Log.Infof("createReminder function call with args: %v", args)
reminder, _ := createReminder(args, userID, timezone)
return &models.GenericResponse{
Type: models.ResponseReminder,
Reminder: reminder,
}, nil
}
}
// Existing code...
}
File: internal/llm/util.go
Implement the createReminder function.
func createReminder(s string, userID int64, timezone string) (*models.Reminder, error) {
var rawArgs struct {
Time string `json:"time"`
Content string `json:"content"`
}
if err := json.Unmarshal([]byte(s), &rawArgs); err != nil {
logger.Log.Errorf("Error parsing arguments: %v", err)
return nil, err
}
// Parse the time using the user's timezone
loc, err := time.LoadLocation(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.Time, loc)
if err != nil {
logger.Log.Errorf("Error parsing time: %v", err)
return nil, err
}
reminder := &models.Reminder{
UserID: userID,
Time: reminderTime,
Content: rawArgs.Content,
}
// Save the reminder to the database
if err := database.DB.Create(reminder).Error; err != nil {
logger.Log.Errorf("Error saving Reminder to database: %v", err)
return nil, err
}
// Schedule the reminder (implementation depends on your scheduling system)
logger.Log.Infof("Reminder created and saved to database: %v", reminder)
return reminder, nil
}
Create the Reminder model
File: internal/models/reminder.go
package models
import (
"time"
)
type Reminder struct {
ID int64 `gorm:"primaryKey" json:"id"`
UserID int64 `json:"user_id"`
Time time.Time `json:"time"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Explanation:
- Added a
Reminder struct to store reminders.
- Includes fields for
UserID, Time, and Content.
CreatedAt and UpdatedAt will be managed by GORM.
Update the database initialization
Modify internal/database/database.go to migrate the Reminder model.
// Inside InitDB()
err = DB.AutoMigrate(&models.ToDo{}, &models.ToDoItem{}, &models.User{}, &models.Reminder{})
By following these steps, you will have:
- Added
createdAt and updatedAt fields to your ToDo models.
- Implemented a flow where the bot asks for the user's timezone on
/start and saves it.
- Set up the foundation to handle reminders based on the user's timezone.
Note:
- For production, consider handling edge cases, such as users changing their timezone, and ensure that all time calculations are accurate.
- Implementing the actual scheduling and sending of reminders will require a background worker or a scheduler like
cron.
If you need further assistance with any of these steps or additional features, feel free to ask!