Lets add here a state of user action, i.e when we do /timezone or we hit it due to registermiddleware, we record state in a map with userid and based on that we know what the user response means and can act accordingly
Assistant
Certainly! To implement a user state management system in your Telegram bot, we can use a map to keep track of each user's current state. This will help the bot understand the context of the user's messages, especially after prompting for input like the timezone. Here's how you can modify your code to include this functionality.
1. Define a User State Map
First, create a global variable to store the user states. You can define this in a new package or in one of your existing packages.
go
package state
import "sync"
// Define possible user states
type UserState int
const (
StateNone UserState = iota
StateWaitingForTimezone
StateWaitingForReminder
// Add more states as needed
)
// Use a thread-safe map to store user states
var (
userStates = make(map[int64]UserState)
mutex sync.RWMutex
)
// SetUserState sets the state for a user
func SetUserState(userID int64, state UserState) {
mutex.Lock()
defer mutex.Unlock()
userStates[userID] = state
}
// GetUserState retrieves the state for a user
func GetUserState(userID int64) UserState {
mutex.RLock()
defer mutex.RUnlock()
return userStates[userID]
}
// ClearUserState removes the state for a user
func ClearUserState(userID int64) {
mutex.Lock()
defer mutex.Unlock()
delete(userStates, userID)
}
2. Modify the Middleware to Update User State
In your RegisterUserMiddleware, after prompting the user for their timezone, set the user's state to indicate that the bot is waiting for their timezone.
go
// handler/middleware.go
func RegisterUserMiddleware(next bot.HandlerFunc) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
// Check if user exists in the database
var user models.User
result := database.DB.First(&user, userID)
if result.Error != nil {
// Create new user if not exists
user = models.User{
ID: userID,
UserName: update.Message.From.Username,
}
database.DB.Create(&user)
}
// If timezone is not set, ask for it
if user.Timezone == "" {
// Set user state to waiting for timezone
state.SetUserState(userID, state.StateWaitingForTimezone)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Please send me your timezone in 'Area/City' format (e.g., 'Europe/London').",
})
return // Return early to wait for user response
}
next(ctx, b, update)
}
}
3. Handle User Responses Based on State
In your main handler or a new update handler, check the user's state and act accordingly.
go
// handler/response_handler.go
func ResponseHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
userID := update.Message.From.ID
userState := state.GetUserState(userID)
switch userState {
case state.StateWaitingForTimezone:
timezone := update.Message.Text
// Validate the timezone
if !isValidTimezone(timezone) {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Invalid timezone format. Please try again (e.g., 'Europe/London').",
})
return
}
// Update user's timezone in the database
database.DB.Model(&models.User{}).Where("id = ?", userID).Update("timezone", timezone)
// Clear user state
state.ClearUserState(userID)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Your timezone has been set successfully!",
})
case state.StateWaitingForReminder:
// Handle reminder creation
reminderText := update.Message.Text
// ... process reminderText and save reminder
state.ClearUserState(userID)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Your reminder has been created!",
})
default:
// If no specific state, process default commands or messages
DefaultHandler(ctx, b, update)
}
}
Don't forget to implement the isValidTimezone function to validate user input.
4. Update the Bot Initialization to Use the New Handler
Modify your main.go to include the new ResponseHandler.
go
// main.go
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
opts := []bot.Option{
bot.WithDefaultHandler(handler.ResponseHandler), // Use the new response handler
bot.WithMiddlewares(
handler.OnlyAdminMiddleware,
handler.RegisterUserMiddleware,
),
}
b, err := bot.New(config.AppConfig.TelegramAPIKey, opts...)
if err != nil {
logger.Log.Fatalf("Failed to create bot: %v", err)
}
b.Start(ctx)
}
5. Implement Commands to Change State
For commands like /timezone or /newreminder, set the user state accordingly.
go
// handler/commands.go
func TimezoneCommandHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
userID := update.Message.From.ID
// Set user state to waiting for timezone
state.SetUserState(userID, state.StateWaitingForTimezone)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Please enter your timezone in 'Area/City' format (e.g., 'Europe/London').",
})
}
func NewReminderCommandHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
userID := update.Message.From.ID
// Set user state to waiting for reminder text
state.SetUserState(userID, state.StateWaitingForReminder)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Please enter the reminder text.",
})
}
6. Register Command Handlers
Ensure that you register these command handlers with the bot.
Note: The registration of handlers and middlewares may vary depending on the Telegram bot library you are using. Adjust the code accordingly to fit the library's API.
7. Update the Default Handler
Adjust your DefaultHandler to act only when no specific state is set.
go
// handler/handler.go
func DefaultHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
userID := update.Message.From.ID
userState := state.GetUserState(userID)
if userState != state.StateNone {
// Let the ResponseHandler handle this message
return
}
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Unknown command. Please use /help to see available commands.",
ParseMode: models.ParseModeHTML,
})
}
8. Thread Safety Considerations
Since Telegram bots can handle multiple updates concurrently, make sure that your state management is thread-safe. The use of sync.RWMutex in the state package ensures that concurrent access to the userStates map is safe.
9. Testing
After implementing the above changes, test your bot thoroughly:
Send the /timezone command and check if the bot prompts for the timezone.
Provide the timezone and see if it gets updated in the database.
Try sending messages without any state to ensure the default handler works.
Test concurrent interactions from multiple users to verify thread safety.
10. Additional Improvements
Expiration of States: Implement a mechanism to expire user states after a certain period of inactivity.
Persistent Storage: If you expect the bot to crash or restart, consider persisting the user states to a database.
State Machine Library: For more complex bots, you might want to use a state machine library to handle user states elegantly.
By adding these modifications, your bot will now be able to keep track of user actions and respond appropriately based on the user's current state. This approach enhances the user experience by making interactions with the bot more context-aware.