tg/cmd/test/mutate.go

93 lines
1.9 KiB
Go
Raw Permalink 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
}
var MutateMessagesWidget= tg.RenderFunc(func(c tg.Context) tg.UI {
2024-03-29 14:30:48 +03:00
return tg.UI{
tg.Messagef(
"Choose widget to mutate strings",
).Reply(
tg.NewKeyboard().Row(
tg.Buttonf("Upper case").Go(UpperCaseWidget),
tg.Buttonf("Lower case").Go(LowerCaseWidget),
tg.Buttonf("Escape chars").Go(EscapeWidget),
2024-03-29 14:30:48 +03:00
).Row(
BackButton,
).Reply(),
),
}
})
var LowerCaseWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
2024-03-29 14:30:48 +03:00
return tg.UI{
tg.Messagef(
"Type a string and the bot will convert it to lower case",
).Reply(
BackKeyboard.Reply(),
),
NewMutateMessageCompo(strings.ToLower),
}
})
var UpperCaseWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
2024-03-29 14:30:48 +03:00
return tg.UI{
tg.Messagef(
"Type a string and the bot will convert it to upper case",
).Reply(
BackKeyboard.Reply(),
),
NewMutateMessageCompo(strings.ToUpper),
}
})
var EscapeWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
2024-03-29 14:30:48 +03:00
return tg.UI{
tg.Messagef(
"Type a string and the bot will escape characters in it",
).Reply(
BackKeyboard.Reply(),
),
NewMutateMessageCompo(tg.Escape2),
}
})