go-telegram-bot-api / telegram-bot-api

Golang bindings for the Telegram Bot API
https://go-telegram-bot-api.dev
MIT License
5.7k stars 879 forks source link

How to distinguish callback data from one another? #525

Open MexHigh opened 2 years ago

MexHigh commented 2 years ago

Im sending Inline Keyboards for different commands with the tgbotapi.NewInlineKeyboardButtonData function. How do I distinguish from which command the callback data comes from while handling the callback?

The only method I can think of is to prefix the InlineKeyboardButtonData with something like the command name and match this in the callback handler. But is there a more elegant solution? E.g. something that comes near to a conversation-based flow?

My example code (simplified) #### main.go ```go // ... func main() { // ... for update := range updates { if update.CallbackQuery != nil { handleCallbackQuery(bot, update) continue } if update.Message != nil && update.Message.IsCommand() { handleCommand(bot, update) continue } } } func handleCallbackQuery(bot *tgbotapi.BotAPI, update tgbotapi.Update) { // How to distinguish if the callback data comes from command "addX" or "addY"??? } func handleCommand(bot *tgbotapi.BotAPI, update tgbotapi.Update) { msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") msg.ParseMode = tgbotapi.ModeMarkdown switch update.Message.Command() { case "addX": users := getUsers() // []string with usernames msg.Text = "For which user do you want to add X?" msg.ReplyMarkup = makeUsernameKeyboard(users...) // see bot_keyboards.go case "addY": users := getUsers() // []string with usernames msg.Text = "For which user do you want to add Y?" msg.ReplyMarkup = makeUsernameKeyboard(users...) // see bot_keyboards.go } bot.Send(msg) } ``` #### bot_keyboards.go ```go // ... // makeUsernameKeyboard creates an InlineKeyboardMarkup that can be directly // assigned to msg.ReplyMarkup. Every User is listed in its own line. func makeUsernameKeyboard(usernames ...string) tgbotapi.InlineKeyboardMarkup { rows := make([][]tgbotapi.InlineKeyboardButton, 0) for _, username := range usernames { rows = append(rows, tgbotapi.NewInlineKeyboardRow( tgbotapi.NewInlineKeyboardButtonData("@"+username, username), ), ) } return tgbotapi.NewInlineKeyboardMarkup(rows...) } ```
temamagic commented 2 years ago

You need implement FSM