Update it to store ToDos into database. Lets use sqlite. Find best way to add this to current structure. Associate a todo with userid( we can get it from update.Message.From.ID which is int64)
Assistant
To update your current codebase to store ToDos into a SQLite database and associate them with user IDs, you can follow these steps:
Add a Database Package:
Create a new database package to handle all database operations.
Use GORM, a popular ORM library for Go, to interact with the SQLite database.
Initialize the SQLite Database:
Set up the database connection and perform automatic migrations for the ToDo and ToDoItem models.
Update Models to Include Database Fields:
Modify your existing ToDo and ToDoItem structs to include GORM model fields.
Add a UserID field to associate ToDos with specific users.
Modify the LLM Processor to Store ToDos in the Database:
Adjust the createToDo function to save the ToDo directly into the database.
Pass the userID to the function to associate the ToDo with the correct user.
Update Handlers and Interfaces to Pass User ID:
Modify the handler functions and the LLMProcessor interface to include userID parameters.
Initialize the Database at Application Startup:
Ensure the database is initialized when your application starts.
Below are the detailed steps and code modifications.
1. Add a Database Package
Create a new file internal/database/database.go:
go
package database
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"asdf/tg_assistant_bot/internal/models"
"asdf/tg_assistant_bot/pkg/logger"
)
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)
}
// Automatically migrate the schema
err = DB.AutoMigrate(&models.ToDo{}, &models.ToDoItem{})
if err != nil {
logger.Log.Fatalf("Failed to migrate database schema: %v", err)
}
logger.Log.Info("Database initialized successfully")
}
Explanation:
Initializes a SQLite database named bot.db.
Uses GORM's AutoMigrate to create or update the database schema based on your models.
2. Initialize the Database at Startup
In your main.go or wherever your application starts, initialize the database:
go
package main
import (
// ... other imports ...
"asdf/tg_assistant_bot/internal/database"
"asdf/tg_assistant_bot/pkg/logger"
)
func main() {
// Setup logger
logger.Setup()
// Load configuration
config.LoadConfig()
// Initialize the database
database.InitDB()
// ... rest of your application code ...
}
3. Update Models to Include Database Fields
Modify internal/models/todo.go:
go
package models
import (
"gorm.io/gorm"
)
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"`
}
type ToDoItem struct {
ID int64 `gorm:"primaryKey" json:"id"`
ToDoID int64 `json:"todo_id"`
Name string `json:"name"`
Completed bool `json:"completed"`
}
Explanation:
Added gorm:"primaryKey" to designate primary keys.
Added UserID to the ToDo struct to associate it with a user.
Specified foreign key relationships with gorm:"foreignKey:ToDoID".
4. Modify the LLM Processor to Store ToDos in the Database
Update llm/util.go:
go
package llm
import (
"encoding/json"
"strings"
"asdf/tg_assistant_bot/internal/models"
"asdf/tg_assistant_bot/pkg/logger"
"asdf/tg_assistant_bot/internal/database"
)
func createToDo(s string, userID int64) (*models.ToDo, error) {
var rawArgs struct {
Name string `json:"name"`
Todos string `json:"todos"`
}
if err := json.Unmarshal([]byte(s), &rawArgs); err != nil {
logger.Log.Errorf("Error parsing arguments: %v", err)
return nil, err
}
todos := strings.Split(rawArgs.Todos, ",")
for i := range todos {
todos[i] = strings.TrimSpace(todos[i])
}
var items []models.ToDoItem
for _, todoName := range todos {
items = append(items, models.ToDoItem{
Name: todoName,
Completed: false,
})
}
todo := &models.ToDo{
UserID: userID,
Name: rawArgs.Name,
Items: items,
}
if err := database.DB.Create(todo).Error; err != nil {
logger.Log.Errorf("Error saving ToDo to database: %v", err)
return nil, err
}
logger.Log.Infof("ToDo created and saved to database: %v", todo)
return todo, nil
}
Explanation:
Modified createToDo to accept userID and save the ToDo to the database.
Used database.DB.Create(todo) to insert the ToDo and its items into the database.
Update llm/googleai_processor.go:
go
func (p *GoogleAIProcessor) ProcessAudio(ctx context.Context, audioData []byte, userID int64) (*models.GenericResponse, error) {
// ... existing code ...
if answer.Choices[0].ToolCalls != nil {
switch answer.Choices[0].ToolCalls[0].FunctionCall.Name {
case "createNewToDo":
args := answer.Choices[0].ToolCalls[0].FunctionCall.Arguments
logger.Log.Infof("createNewToDo function call with args: %v", args)
todo, err := createToDo(args, userID)
if err != nil {
return nil, err
}
return &models.GenericResponse{
Type: models.ResponseToDo,
ToDo: todo,
}, nil
}
}
// ... existing code ...
}
Retrieves all ToDos and their items for a specific user.
Uses Preload("Items") to load associated ToDo items.
9. Update the ToDo Keyboard if Necessary
If your ToDo keyboard needs to reflect the latest data from the database, you may need to modify it accordingly.
Example in internal/keyboard/todo.go:
go
func GenerateToDoKeyboard(todo models.ToDo) *tgmodels.InlineKeyboardMarkup {
// ... existing code ...
// Optionally, refresh the todo items from the database before generating the keyboard
}
10. Test the Implementation
Run the Application: Start your application and ensure it initializes the database without errors.
Create ToDos: Use the bot to create new ToDos via voice messages.
Verify Database Entries: Check the bot.db file using a SQLite browser or command-line tool to verify that ToDos are being stored correctly with the associated userID.
Retrieve and Display ToDos: Implement features to retrieve and display the user's ToDos, ensuring they are fetched from the database.
Complete Code Examples
internal/database/database.go:
go
package database
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"asdf/tg_assistant_bot/internal/models"
"asdf/tg_assistant_bot/pkg/logger"
)
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)
}
// Automatically migrate the schema
err = DB.AutoMigrate(&models.ToDo{}, &models.ToDoItem{})
if err != nil {
logger.Log.Fatalf("Failed to migrate database schema: %v", err)
}
logger.Log.Info("Database initialized successfully")
}
internal/models/todo.go:
go
package models
import (
"gorm.io/gorm"
)
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"`
gorm.Model
}
type ToDoItem struct {
ID int64 `gorm:"primaryKey" json:"id"`
ToDoID int64 `json:"todo_id"`
Name string `json:"name"`
Completed bool `json:"completed"`
gorm.Model
}
Note:gorm.Model includes fields like CreatedAt, UpdatedAt, etc. Include it if you need those fields.
internal/llm/util.go:
go
func createToDo(s string, userID int64) (*models.ToDo, error) {
// ... code as shown in step 4 ...
}
By incorporating these changes, your application will now store ToDos into a SQLite database and associate them with user IDs. This setup provides persistent storage, allowing users to access their ToDos even after the bot restarts.
Let me know if you need any further assistance or clarification.