@uvins

Как создать кнопки в ТГ боте Golang (telegram-bot-api)?

Привет, я создаю телеграмм бота на Go, вот встала такая задача сделать кнопки в нём. Сколько я в интернете не смотрел, везде либо пайтон, либо не понятные ответы на вопросы. Вот мой код:
package main

import (
	"log"
	"main/projects/db"

	api "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

func main() {
	bot, err := api.NewBotAPI("Токен")
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	u := api.NewUpdate(0)
	u.Timeout = 150

	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message != nil { // If we got a message
			msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text)
			msg.ReplyToMessageID = update.Message.MessageID

			if msg.Text == "/start" {
				name := update.Message.From.FirstName

				bot.Send(api.NewMessage(update.Message.Chat.ID, "Привет, "+name+", я бот от 100 идей для Беларуси. Автор: Астахов В.В\nБот создан на Go"))

				db.InsertUserInfo(update.Message.From.ID, update.Message.From.UserName)
			}
			if msg.Text == "привет" || msg.Text == "Привет" {
				bot.Send(api.NewMessage(update.Message.Chat.ID, "Привет!"))
			}
		}
	}
}


Из других файлов только файл работы с БД. Вопрос, как добавить сюда кнопки?
  • Вопрос задан
  • 1089 просмотров
Пригласить эксперта
Ответы на вопрос 3
RimMirK
@RimMirK
Вроде человек. Вроде учусь. Вроде пайтону
кнопка под сообщением
Инлайн кнопка, ее вставить в инлайн маркап. Инлайн маркап передать функции отправляющей сообщение.

кнопа внизу
Репли кнопку (кейборд батн) вставить в репли маркап. Маркап в функцию отправки.
Ответ написан
Комментировать
@falconandy
Просто нагуглил, может подойдет для примера
TutorialBot
Ответ написан
Комментировать
memrook
@memrook
Пример есть в репозитории telegram-bot-api

package main

import (
	"log"
	"os"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)

var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup(
	tgbotapi.NewInlineKeyboardRow(
		tgbotapi.NewInlineKeyboardButtonURL("1.com", "http://1.com"),
		tgbotapi.NewInlineKeyboardButtonData("2", "2"),
		tgbotapi.NewInlineKeyboardButtonData("3", "3"),
	),
	tgbotapi.NewInlineKeyboardRow(
		tgbotapi.NewInlineKeyboardButtonData("4", "4"),
		tgbotapi.NewInlineKeyboardButtonData("5", "5"),
		tgbotapi.NewInlineKeyboardButtonData("6", "6"),
	),
)

func main() {
	bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)

	// Loop through each update.
	for update := range updates {
		// Check if we've gotten a message update.
		if update.Message != nil {
			// Construct a new message from the given chat ID and containing
			// the text that we received.
			msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)

			// If the message was open, add a copy of our numeric keyboard.
			switch update.Message.Text {
			case "open":
				msg.ReplyMarkup = numericKeyboard

			}

			// Send the message.
			if _, err = bot.Send(msg); err != nil {
				panic(err)
			}
		} else if update.CallbackQuery != nil {
			// Respond to the callback query, telling Telegram to show the user
			// a message with the data received.
			callback := tgbotapi.NewCallback(update.CallbackQuery.ID, update.CallbackQuery.Data)
			if _, err := bot.Request(callback); err != nil {
				panic(err)
			}

			// And finally, send a message containing the data received.
			msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Data)
			if _, err := bot.Send(msg); err != nil {
				panic(err)
			}
		}
	}
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы