all repos — telegram-bot-api @ 617735e3abc7cea89ba875ef20aef4a57a5df23a

Golang bindings for the Telegram Bot API

docs/examples/inline-keyboard.md (view raw)

 1# Inline Keyboard
 2
 3This bot waits for you to send it the message "open" before sending you an
 4inline keyboard containing a URL and some numbers. When a number is clicked, it
 5sends you a message with your selected number.
 6
 7```go
 8package main
 9
10import (
11	"log"
12	"os"
13
14	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
15)
16
17var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup(
18	tgbotapi.NewInlineKeyboardRow(
19		tgbotapi.NewInlineKeyboardButtonURL("1.com", "http://1.com"),
20		tgbotapi.NewInlineKeyboardButtonData("2", "2"),
21		tgbotapi.NewInlineKeyboardButtonData("3", "3"),
22	),
23	tgbotapi.NewInlineKeyboardRow(
24		tgbotapi.NewInlineKeyboardButtonData("4", "4"),
25		tgbotapi.NewInlineKeyboardButtonData("5", "5"),
26		tgbotapi.NewInlineKeyboardButtonData("6", "6"),
27	),
28)
29
30func main() {
31	bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
32	if err != nil {
33		log.Panic(err)
34	}
35
36	bot.Debug = true
37
38	log.Printf("Authorized on account %s", bot.Self.UserName)
39
40	u := tgbotapi.NewUpdate(0)
41	u.Timeout = 60
42
43	updates := bot.GetUpdatesChan(u)
44
45	// Loop through each update.
46	for update := range updates {
47		// Check if we've gotten a message update.
48		if update.Message != nil {
49			// Construct a new message from the given chat ID and containing
50			// the text that we received.
51			msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
52
53			// If the message was open, add a copy of our numeric keyboard.
54			switch update.Message.Text {
55			case "open":
56				msg.ReplyMarkup = numericKeyboard
57
58			}
59
60			// Send the message.
61			if _, err = bot.Send(msg); err != nil {
62				panic(err)
63			}
64		} else if update.CallbackQuery != nil {
65			// Respond to the callback query, telling Telegram to show the user
66			// a message with the data received.
67			callback := tgbotapi.NewCallback(update.CallbackQuery.ID, update.CallbackQuery.Data)
68			if _, err := bot.Request(callback); err != nil {
69				panic(err)
70			}
71
72			// And finally, send a message containing the data received.
73			msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Data)
74			if _, err := bot.Send(msg); err != nil {
75				panic(err)
76			}
77		}
78	}
79}
80```