<repo><f p="database\database.go"><![CDATA[package database import (…
- User
How come when I send voice it is not hitting the default handler?
- Assistant
How come when I send voice it is not hitting the default handler?
The reason why your DefaultHandler is not being called when you send a voice message is due to the way your OnlyAdminMiddleware is implemented. Specifically, the middleware is intercepting the update and, if the sender is not the admin, it returns early without calling next(ctx, b, update). This prevents the update from reaching any subsequent handlers, including your DefaultHandler.
Let's break down what's happening in your code:
Middleware Execution Order:
In your main.go, you have registered middleware as follows:
opts := []bot.Option{
bot.WithDefaultHandler(handler.DefaultHandler),
bot.WithMiddlewares(handler.OnlyAdminMiddleware, handler.RegisterUserMiddleware),
}
This means that every update that your bot receives will first pass through OnlyAdminMiddleware, then RegisterUserMiddleware, and finally to either a specific handler or the DefaultHandler if no specific handler is matched.
The OnlyAdminMiddleware Logic:
Your OnlyAdminMiddleware is defined as:
func OnlyAdminMiddleware(next bot.HandlerFunc) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID != int64(adminID) {
logger.Log.Warnf("Bot accessed by non-admin: %d", userID)
return
}
next(ctx, b, update)
}
}
Here, if the userID is not equal to the adminID, the middleware logs a warning and returns early without calling next(ctx, b, update).
Effect on Non-Admin Users:
For Voice Messages:
Since voice messages don't have a specific handler registered (like your TextHandler), they rely on the DefaultHandler. However, because the OnlyAdminMiddleware returns early for non-admin users, the update never reaches the DefaultHandler.
For Text Messages: You have registered a specific handler for text messages:
b.RegisterHandler(bot.HandlerTypeMessageText, "", bot.MatchTypePrefix, handler.TextHandler)
If a non-admin user sends a text message, the middleware still intercepts it and returns early, preventing the TextHandler from being called. However, if the sender is the admin, the middleware calls next(ctx, b, update), allowing the TextHandler to process the message.
Solution:
To fix this issue, you need to adjust the OnlyAdminMiddleware so that it doesn't prevent non-admin users from reaching the DefaultHandler (or other handlers you want them to access). Here's how you can do it:
Modify the Middleware to Allow DefaultHandler Execution:
If you want the bot to still respond to non-admin users with the DefaultHandler, you should ensure that next(ctx, b, update) is called regardless. You can move any admin-specific checks into the handlers that require them or modify the middleware to allow certain updates through.
Updated OnlyAdminMiddleware:
func OnlyAdminMiddleware(next bot.HandlerFunc) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID == int64(adminID) {
// Allow admin to proceed to the next handler
next(ctx, b, update)
return
}
// For non-admin users, you might want to allow certain updates
// For example, allow them to reach the DefaultHandler
// Here, we can check if the update is a voice message
if update.Message.Voice != nil {
// Allow voice messages to proceed to DefaultHandler
next(ctx, b, update)
return
}
// Optionally, send a message to the user indicating they are not authorized
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "You are not authorized to use this bot.",
})
}
}
In this updated middleware, we are:
Summary:
OnlyAdminMiddleware is preventing non-admin users from reaching the DefaultHandler by returning early without calling next(ctx, b, update).DefaultHandler, or move the admin check into specific handlers that require it.Example of Adjusted Code:
Here's a full example of how you might adjust your middleware and main function:
// handler/middleware.go
func OnlyAdminMiddleware(next bot.HandlerFunc) bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *tgmodels.Update) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID == int64(adminID) {
// Allow admin to proceed
next(ctx, b, update)
return
}
// Allow non-admin users to proceed to DefaultHandler
// but restrict access to certain handlers if needed
next(ctx, b, update)
}
}
// main.go
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
opts := []bot.Option{
bot.WithDefaultHandler(handler.DefaultHandler),
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)
}
// Register handlers that should be admin-only
adminHandlers := bot.NewMiddlewareGroup(b)
adminHandlers.Use(handler.OnlyAdminMiddleware)
adminHandlers.RegisterHandler(bot.HandlerTypeMessageText, "", bot.MatchTypePrefix, handler.TextHandler)
// Start the bot
b.Start(ctx)
}
In this setup, only the adminHandlers group uses the OnlyAdminMiddleware, ensuring that non-admin users can interact with the DefaultHandler and any other handlers not restricted to admins.
Not yet included in a published release.
Restrict Access Within Specific Handlers:
Alternatively, you can remove the OnlyAdminMiddleware from the global middleware and instead check for admin privileges within specific handlers that require it.
Remove OnlyAdminMiddleware from the global middleware:
opts := []bot.Option{
bot.WithDefaultHandler(handler.DefaultHandler),
bot.WithMiddlewares(handler.RegisterUserMiddleware),
}
Modify TextHandler to include admin check:
func TextHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
userID := update.Message.From.ID
adminID, _ := strconv.Atoi(config.AppConfig.TelegramUserID)
if userID != int64(adminID) {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "You are not authorized to use this command.",
})
return
}
// Proceed with handler logic for admin
// ...
}
By doing this, you limit the admin check to the handlers that require admin access and allow other handlers (like DefaultHandler) to process messages from non-admin users.