tg/cmd/test/mutate.go

92 lines
1.9 KiB
Go

package main
import (
"surdeus.su/core/tg"
"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 {
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),
).Row(
BackButton,
).Reply(),
),
}
})
var LowerCaseWidget = 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 UpperCaseWidget = 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 EscapeWidget = 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),
}
})