2022-04-26 00:02:51 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
|
|
|
|
"github.com/go-telegram/bot"
|
|
|
|
"github.com/go-telegram/bot/models"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Send any text message to the bot after the bot has been started
|
|
|
|
|
|
|
|
func main() {
|
2022-05-03 00:39:04 +08:00
|
|
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
|
|
|
defer cancel()
|
|
|
|
|
2022-04-26 00:02:51 +08:00
|
|
|
opts := []bot.Option{
|
|
|
|
bot.WithDefaultHandler(defaultHandler),
|
|
|
|
bot.WithCallbackQueryDataHandler("button", bot.MatchTypePrefix, callbackHandler),
|
|
|
|
}
|
|
|
|
|
2023-04-26 17:00:17 +08:00
|
|
|
b, err := bot.New(os.Getenv("EXAMPLE_TELEGRAM_BOT_TOKEN"), opts...)
|
|
|
|
if nil != err {
|
|
|
|
// panics for the sake of simplicity.
|
|
|
|
// you should handle this error properly in your code.
|
|
|
|
panic(err)
|
|
|
|
}
|
2022-04-26 00:02:51 +08:00
|
|
|
|
2022-05-06 17:47:43 +08:00
|
|
|
b.Start(ctx)
|
2022-04-26 00:02:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func callbackHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
|
2023-04-26 17:00:17 +08:00
|
|
|
// answering callback query first to let Telegram know that we received the callback query,
|
|
|
|
// and we're handling it. Otherwise, Telegram might retry sending the update repetitively
|
|
|
|
// as it thinks the callback query doesn't reach to our application. learn more by
|
|
|
|
// reading the footnote of the https://core.telegram.org/bots/api#callbackquery type.
|
|
|
|
b.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{
|
|
|
|
CallbackQueryID: update.CallbackQuery.ID,
|
|
|
|
ShowAlert: false,
|
|
|
|
})
|
2022-05-06 17:47:43 +08:00
|
|
|
b.SendMessage(ctx, &bot.SendMessageParams{
|
2024-02-27 16:10:23 +08:00
|
|
|
ChatID: update.CallbackQuery.Message.Message.Chat.ID,
|
2022-04-26 00:02:51 +08:00
|
|
|
Text: "You selected the button: " + update.CallbackQuery.Data,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func defaultHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
|
|
|
|
kb := &models.InlineKeyboardMarkup{
|
|
|
|
InlineKeyboard: [][]models.InlineKeyboardButton{
|
|
|
|
{
|
|
|
|
{Text: "Button 1", CallbackData: "button_1"},
|
|
|
|
{Text: "Button 2", CallbackData: "button_2"},
|
|
|
|
}, {
|
|
|
|
{Text: "Button 3", CallbackData: "button_3"},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2022-05-06 17:47:43 +08:00
|
|
|
b.SendMessage(ctx, &bot.SendMessageParams{
|
2022-04-29 17:21:42 +08:00
|
|
|
ChatID: update.Message.Chat.ID,
|
|
|
|
Text: "Click by button",
|
2022-04-26 00:02:51 +08:00
|
|
|
ReplyMarkup: kb,
|
|
|
|
})
|
|
|
|
}
|