123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- package tg
- import (
- tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
- )
- // The type represents reply keyboards.
- type Reply struct {
- Keyboard
- // If true will be removed after one press.
- OneTime bool
- // If true will remove the keyboard on send.
- Remove bool
- }
- // Set if we should remove current keyboard on the user side
- // when sending the keyboard.
- func (kbd Reply) WithRemove(remove bool) Reply {
- kbd.Remove = remove
- return kbd
- }
- // Set if the keyboard should be hidden after
- // one of buttons is pressede.
- func (kbd Reply) WithOneTime(oneTime bool) Reply{
- kbd.OneTime = oneTime
- return kbd
- }
- // Convert the Keyboard to the Telegram API type of reply keyboard.
- func (kbd Reply) ToApi() any {
- // Shades everything.
- if kbd.Remove {
- return tgbotapi.NewRemoveKeyboard(true)
- }
- rows := [][]tgbotapi.KeyboardButton{}
- for _, row := range kbd.Rows {
- if row == nil {
- continue
- }
- buttons := []tgbotapi.KeyboardButton{}
- for _, button := range row {
- if !button.Valid {
- continue
- }
- buttons = append(buttons, button.ToTelegram())
- }
- rows = append(rows, buttons)
- }
- if kbd.OneTime {
- return tgbotapi.NewOneTimeReplyKeyboard(rows...)
- }
- return tgbotapi.NewReplyKeyboard(rows...)
- }
- // The type implements reply keyboard widget.
- type ReplyCompo struct {
- MessageCompo
- Reply
- }
- // Implementing the sendable interface.
- func (compo *ReplyCompo) SendConfig(
- sid SessionID, bot *Bot,
- ) (SendConfig) {
- sendConfig := compo.MessageCompo.SendConfig(sid, bot)
- msg := sendConfig.Chattable.(tgbotapi.MessageConfig)
- msg.ReplyMarkup = compo.Reply.ToApi()
- sendConfig.Chattable = msg
- return sendConfig
- }
- // Implementing the Server interface.
- func (compo *ReplyCompo) Filter(
- u Update,
- ) bool {
- if compo == nil || u.Message == nil {
- return true
- }
- _, ok := compo.ButtonMap()[u.Message.Text]
- if !ok {
- if u.Message.Location != nil {
- _, hasLocBtn := compo.ButtonMap().LocationButton()
- if !hasLocBtn {
- return true
- }
- } else {
- return true
- }
- }
- return false
- }
- // Implementing the UI interface.
- func (compo *ReplyCompo) Serve(c Context) {
- for u := range c.Input() {
- var btn Button
- text := u.Message.Text
- btns := compo.ButtonMap()
- btn, ok := btns[text]
- if !ok {
- if u.Message.Location != nil {
- locBtn, hasLocBtn := btns.LocationButton()
- if hasLocBtn {
- btn = locBtn
- }
- }
- }
- if !btn.Valid {
- continue
- }
- c.WithUpdate(u).Run(btn.Action)
- }
- }
|