tg/cmd/test/mutate.go

100 lines
2.1 KiB
Go
Raw Normal View History

2024-03-29 14:30:48 +03:00
package main
import (
"surdeus.su/core/tg"
2024-03-29 14:30:48 +03:00
"strings"
)
// The component to get incoming messages and
// send back mutated version.
type MutateMessageCompo struct {
Mutate func(string) string
}
func NewMutateMessageCompo(fn func(string) string) *MutateMessageCompo {
ret := &MutateMessageCompo{}
ret.Mutate = fn
return ret
}
func (w *MutateMessageCompo) Serve(c tg.Context) {
args, ok := c.Arg().([]any)
if ok {
for _, arg := range args {
c.Sendf("%v", arg)
}
}
for u := range c.Input() {
text := u.Message.Text
_, err := c.Sendf2("%s", w.Mutate(text))
if err != nil {
c.Sendf("debug: %q", err)
}
}
}
// Implementing the Filter interface making
// possible to give the updates away for
// the underlying components.
func (w *MutateMessageCompo) Filter(u tg.Update) bool {
if u.Message == nil {
return true
}
return false
}
const (
UpperCasePath tg.Path = "upper-case"
LowerCasePath = "lower-case"
EscapePath = "escape"
MutateMessagesPath = "mutate-messages"
2024-03-29 14:30:48 +03:00
)
var MutateMessagesWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
return tg.UI{
tg.Messagef(
"Choose widget to mutate strings",
).Reply(
tg.NewKeyboard().Row(
tg.Buttonf("Upper case").Go(UpperCasePath),
tg.Buttonf("Lower case").Go(LowerCasePath),
tg.Buttonf("Escape chars").Go(EscapePath),
).Row(
BackButton,
).Reply(),
),
}
})
var MutateMessagesToLowerCaseWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
return tg.UI{
tg.Messagef(
"Type a string and the bot will convert it to lower case",
).Reply(
BackKeyboard.Reply(),
),
NewMutateMessageCompo(strings.ToLower),
}
})
var MutateMessagesToUpperCaseWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
return tg.UI{
tg.Messagef(
"Type a string and the bot will convert it to upper case",
).Reply(
BackKeyboard.Reply(),
),
NewMutateMessageCompo(strings.ToUpper),
}
})
var MutateMessagesEscapeWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
return tg.UI{
tg.Messagef(
"Type a string and the bot will escape characters in it",
).Reply(
BackKeyboard.Reply(),
),
NewMutateMessageCompo(tg.Escape2),
}
})