tg/reply.go

125 lines
2.4 KiB
Go
Raw Normal View History

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 {
2023-12-12 19:32:30 +03:00
if row == nil {
continue
}
buttons := []tgbotapi.KeyboardButton{}
for _, button := range row {
2024-03-29 14:30:48 +03:00
if !button.Valid {
2023-12-12 19:32:30 +03:00
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.
2024-03-29 14:30:48 +03:00
func (compo *ReplyCompo) SendConfig(
sid SessionId, bot *Bot,
) (SendConfig) {
sendConfig := compo.MessageCompo.SendConfig(sid, bot)
2024-03-29 14:30:48 +03:00
msg := sendConfig.Chattable.(tgbotapi.MessageConfig)
msg.ReplyMarkup = compo.Reply.ToApi()
sendConfig.Chattable = msg
return sendConfig
}
// Implementing the Server interface.
2024-03-29 14:30:48 +03:00
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 {
2024-03-29 14:30:48 +03:00
_, hasLocBtn := compo.ButtonMap().LocationButton()
if !hasLocBtn {
return true
}
} else {
return true
}
}
return false
}
2023-09-26 17:13:31 +03:00
// Implementing the UI interface.
2024-03-29 14:30:48 +03:00
func (compo *ReplyCompo) Serve(c Context) {
for u := range c.Input() {
2024-03-29 14:30:48 +03:00
var btn Button
text := u.Message.Text
btns := compo.ButtonMap()
btn, ok := btns[text]
if !ok {
if u.Message.Location != nil {
2024-03-29 14:30:48 +03:00
locBtn, hasLocBtn := btns.LocationButton()
if hasLocBtn {
btn = locBtn
}
}
}
2024-03-29 14:30:48 +03:00
if !btn.Valid {
continue
}
2024-03-29 14:30:48 +03:00
c.WithUpdate(u).Run(btn.Action)
}
}