Compare commits
No commits in common. "main" and "refact" have entirely different histories.
35 changed files with 941 additions and 1143 deletions
46
beh.go
46
beh.go
|
@ -1,46 +1,65 @@
|
|||
package tg
|
||||
|
||||
// The package implements
|
||||
// behaviour for the Telegram bots.
|
||||
|
||||
// The type describes behaviour for the bot in personal chats.
|
||||
type Behaviour struct {
|
||||
Root Component
|
||||
Init Action
|
||||
//Screens ScreenMap
|
||||
Init Action
|
||||
Screens ScreenMap
|
||||
}
|
||||
|
||||
// Returns new empty behaviour.
|
||||
func NewBehaviour() *Behaviour {
|
||||
return &Behaviour{
|
||||
Screens: make(ScreenMap),
|
||||
}
|
||||
}
|
||||
|
||||
// The Action will be called on session creation,
|
||||
// not when starting or restarting the bot with the Start Action.
|
||||
func (b *Behaviour) SetInit(a Action) *Behaviour {
|
||||
func (b *Behaviour) WithInit(a Action) *Behaviour {
|
||||
b.Init = a
|
||||
return b
|
||||
}
|
||||
|
||||
/*func (b *Behaviour) SetScreens(screens ScreenMap) *Behaviour {
|
||||
b.Screens = screens
|
||||
return b
|
||||
// Alias to WithInit to simplify behaviour definitions.
|
||||
func (b *Behaviour) WithInitFunc(
|
||||
fn ActionFunc,
|
||||
) *Behaviour {
|
||||
return b.WithInit(fn)
|
||||
}
|
||||
|
||||
// Sets the root node of the Behaviour.
|
||||
// Mostly used for commands and such stuff.
|
||||
func (b *Behaviour) SetRootNode(node *RootNode) *Behaviour {
|
||||
func (b *Behaviour) WithRootNode(node *RootNode) *Behaviour {
|
||||
b.Screens = node.ScreenMap()
|
||||
return b
|
||||
}
|
||||
|
||||
*/
|
||||
// The function sets screens.
|
||||
/*func (b *Behaviour) WithScreens(
|
||||
screens ...*Screen,
|
||||
) *Behaviour {
|
||||
for _, screen := range screens {
|
||||
if screen.Id == "" {
|
||||
panic("empty screen ID")
|
||||
}
|
||||
_, ok := b.Screens[screen.Id]
|
||||
if ok {
|
||||
panic("duplicate keyboard IDs")
|
||||
}
|
||||
b.Screens[screen.Id] = screen
|
||||
}
|
||||
return b
|
||||
}*/
|
||||
|
||||
// The function sets as the standard root widget CommandWidget
|
||||
// and its commands..
|
||||
func (b *Behaviour) SetRootWidget(root Component) *Behaviour {
|
||||
func (b *Behaviour) WithRoot(root Component) *Behaviour {
|
||||
b.Root = root
|
||||
return b
|
||||
}
|
||||
|
||||
/*
|
||||
// Check whether the screen exists in the behaviour.
|
||||
func (beh *Behaviour) PathExist(pth Path) bool {
|
||||
_, ok := beh.Screens[pth]
|
||||
|
@ -49,6 +68,7 @@ func (beh *Behaviour) PathExist(pth Path) bool {
|
|||
|
||||
// Returns the screen by it's ID.
|
||||
func (beh *Behaviour) GetScreen(pth Path) *Screen {
|
||||
pth = pth.Clean()
|
||||
if !beh.PathExist(pth) {
|
||||
panic(ScreenNotExistErr)
|
||||
}
|
||||
|
@ -56,4 +76,4 @@ func (beh *Behaviour) GetScreen(pth Path) *Screen {
|
|||
screen := beh.Screens[pth]
|
||||
return screen
|
||||
}
|
||||
*/
|
||||
|
||||
|
|
124
bot.go
124
bot.go
|
@ -38,12 +38,12 @@ func NewBot(token string) (*Bot, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
func (bot *Bot) SetDebug(debug bool) *Bot {
|
||||
func (bot *Bot) Debug(debug bool) *Bot {
|
||||
bot.api.Debug = debug
|
||||
return bot
|
||||
}
|
||||
|
||||
func (bot *Bot) API() *tgbotapi.BotAPI {
|
||||
func (bot *Bot) Api() *tgbotapi.BotAPI {
|
||||
return bot.api
|
||||
}
|
||||
|
||||
|
@ -53,35 +53,36 @@ func (bot *Bot) Me() User {
|
|||
|
||||
// Send the Renderable to the specified session client side.
|
||||
// Can be used for both group and private sessions because
|
||||
// SessionID represents both for chat IDs.
|
||||
// SessionId represents both for chat IDs.
|
||||
func (bot *Bot) Send(
|
||||
sid SessionID, v Sendable,
|
||||
) (*Message, error) {
|
||||
sid SessionId, v Sendable,
|
||||
) (Message, error) {
|
||||
config := v.SendConfig(sid, bot)
|
||||
if config.Error != nil {
|
||||
return nil, config.Error
|
||||
return Message{}, config.Error
|
||||
}
|
||||
|
||||
msg, err := bot.api.Send(config.ToAPI())
|
||||
msg, err := bot.api.Send(config.ToApi())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return Message{}, err
|
||||
}
|
||||
v.SetMessage(&msg)
|
||||
return &msg, nil
|
||||
v.SetMessage(msg)
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (bot *Bot) Sendf(
|
||||
sid SessionID, format string, v ...any,
|
||||
) (*Message, error){
|
||||
sid SessionId, format string, v ...any,
|
||||
) (Message, error){
|
||||
msg := Messagef(format, v...)
|
||||
return bot.Send(
|
||||
sid,
|
||||
Messagef(format, v...),
|
||||
&msg,
|
||||
)
|
||||
}
|
||||
|
||||
// Send to the session specified its ID raw chattable from the tgbotapi.
|
||||
func (bot *Bot) SendRaw(
|
||||
sid SessionID, v tgbotapi.Chattable,
|
||||
sid SessionId, v tgbotapi.Chattable,
|
||||
) (*Message, error) {
|
||||
msg, err := bot.api.Send(v)
|
||||
if err != nil {
|
||||
|
@ -92,29 +93,20 @@ func (bot *Bot) SendRaw(
|
|||
|
||||
// Get session by its ID. Can be used for any scope
|
||||
// including private, group and channel.
|
||||
func (bot *Bot) GotSession(
|
||||
sid SessionID,
|
||||
func (bot *Bot) GetSession(
|
||||
sid SessionId,
|
||||
) (*Session, bool) {
|
||||
session, ok := bot.sessions[sid]
|
||||
return session, ok
|
||||
}
|
||||
|
||||
func (bot *Bot) SetData(v any) *Bot {
|
||||
bot.data = v
|
||||
return bot
|
||||
}
|
||||
|
||||
func (bot *Bot) Data() any {
|
||||
return bot.data
|
||||
}
|
||||
|
||||
func (b *Bot) SetBehaviour(beh *Behaviour) *Bot {
|
||||
func (b *Bot) WithBehaviour(beh *Behaviour) *Bot {
|
||||
b.behaviour = beh
|
||||
b.sessions = make(SessionMap)
|
||||
return b
|
||||
}
|
||||
|
||||
func (b *Bot) SetSessions(sessions SessionMap) *Bot {
|
||||
func (b *Bot) WithSessions(sessions SessionMap) *Bot {
|
||||
b.sessions = sessions
|
||||
return b
|
||||
}
|
||||
|
@ -148,7 +140,7 @@ func (bot *Bot) SetCommands(
|
|||
}
|
||||
sort.Strings(names)
|
||||
|
||||
cmds := []Command{}
|
||||
cmds := []*Command{}
|
||||
for _, name := range names {
|
||||
cmds = append(
|
||||
cmds,
|
||||
|
@ -158,7 +150,7 @@ func (bot *Bot) SetCommands(
|
|||
|
||||
botCmds := []tgbotapi.BotCommand{}
|
||||
for _, cmd := range cmds {
|
||||
botCmds = append(botCmds, cmd.ToAPI())
|
||||
botCmds = append(botCmds, cmd.ToApi())
|
||||
}
|
||||
|
||||
//tgbotapi.NewBotCommandScopeAllPrivateChats(),
|
||||
|
@ -210,7 +202,7 @@ func (bot *Bot) Run() error {
|
|||
go bot.handleGroup(chn)
|
||||
}*/
|
||||
|
||||
me, _ := bot.API().GetMe()
|
||||
me, _ := bot.Api.GetMe()
|
||||
bot.me = me
|
||||
for up := range updates {
|
||||
u := Update{
|
||||
|
@ -224,7 +216,6 @@ func (bot *Bot) Run() error {
|
|||
}
|
||||
|
||||
chn, ok := handles[fromChat.Type]
|
||||
// Skipping non existent scope.
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
@ -238,32 +229,67 @@ func (bot *Bot) Run() error {
|
|||
// The function handles updates supposed for the private
|
||||
// chat with the bot.
|
||||
func (bot *Bot) handlePrivate(updates chan Update) {
|
||||
var sid SessionID
|
||||
var sid SessionId
|
||||
for u := range updates {
|
||||
sid = SessionID(u.FromChat().ID)
|
||||
session, sessionOk := bot.sessions[sid]
|
||||
if u.Message != nil && !sessionOk {
|
||||
// Creating session if we have none
|
||||
// but only on text messages.
|
||||
session = bot.sessions.Add(bot, sid, PrivateSessionScope)
|
||||
sid = SessionId(u.FromChat().ID)
|
||||
ctx, ctxOk := bot.contexts[sid]
|
||||
if u.Message != nil && !ctxOk {
|
||||
|
||||
// Creating the root context
|
||||
// that takes updates directly from
|
||||
// the session.
|
||||
rootContext := Context{
|
||||
session: session,
|
||||
update: u,
|
||||
input: session.updates,
|
||||
session, sessionOk := bot.sessions[sid]
|
||||
if !sessionOk {
|
||||
// Creating session if we have none.
|
||||
session = bot.sessions.Add(sid, PrivateSessionScope)
|
||||
}
|
||||
go rootContext.serve()
|
||||
rootContext.input.Send(u)
|
||||
session = bot.sessions[sid]
|
||||
|
||||
// Create context on any message
|
||||
// if we have no one.
|
||||
ctx = &context{
|
||||
Bot: bot,
|
||||
Session: session,
|
||||
updates: NewUpdateChan(),
|
||||
}
|
||||
if !ctxOk {
|
||||
bot.contexts[sid] = ctx
|
||||
}
|
||||
|
||||
go Context{
|
||||
session: session,
|
||||
bot: bot,
|
||||
Update: u,
|
||||
input: ctx.updates,
|
||||
}.serve()
|
||||
ctx.session.updates.Send(u)
|
||||
continue
|
||||
}
|
||||
|
||||
if sessionOk {
|
||||
session.updates.Send(u)
|
||||
if ctxOk {
|
||||
ctx.updates.Send(u)
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
func (bot *Bot) handleGroup(updates chan *Update) {
|
||||
var sid SessionId
|
||||
chans := make(map[SessionId]chan *Update)
|
||||
for u := range updates {
|
||||
sid = SessionId(u.FromChat().ID)
|
||||
// If no session add new.
|
||||
if _, ok := bot.groupSessions[sid]; !ok {
|
||||
bot.groupSessions.Add(sid)
|
||||
session := bot.groupSessions[sid]
|
||||
ctx := &groupContext{
|
||||
Bot: bot,
|
||||
Session: session,
|
||||
updates: make(chan *Update),
|
||||
}
|
||||
chn := make(chan *Update)
|
||||
chans[sid] = chn
|
||||
go ctx.handleUpdateChan(chn)
|
||||
}
|
||||
|
||||
chn := chans[sid]
|
||||
chn <- u
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
|
3
btest
3
btest
|
@ -1,3 +0,0 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
go build -o ./exe/test ./cmd/test
|
54
button.go
54
button.go
|
@ -11,40 +11,34 @@ import (
|
|||
type Button struct {
|
||||
Text string
|
||||
Data string
|
||||
URL string
|
||||
Url string
|
||||
SendLocation bool
|
||||
Action Action
|
||||
// Used to skip buttons in generating by functions.
|
||||
Valid bool
|
||||
}
|
||||
|
||||
type ButtonMap map[string]Button
|
||||
|
||||
// Returns the only location button in the map and if it is there at all.
|
||||
// The location map must be the ONLY one.
|
||||
|
||||
func (btnMap ButtonMap) LocationButton() (Button, bool) {
|
||||
// Returns the only location button in the map.
|
||||
func (btnMap ButtonMap) LocationButton() *Button {
|
||||
for _, btn := range btnMap {
|
||||
if btn.SendLocation {
|
||||
return btn, true
|
||||
return btn
|
||||
}
|
||||
}
|
||||
return Button{}, false
|
||||
return nil
|
||||
}
|
||||
|
||||
// Represents the reply button row.
|
||||
type ButtonRow []Button
|
||||
type ButtonRow []*Button
|
||||
|
||||
// Returns new button with the specified text and no action.
|
||||
func Buttonf(format string, v ...any) Button {
|
||||
return Button{
|
||||
return &Button{
|
||||
Text: fmt.Sprintf(format, v...),
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
|
||||
// Randomize buttons data to make the key unique.
|
||||
// No guaranties about collisions though.
|
||||
func (btn Button) Rand() Button {
|
||||
rData := make([]byte, 8)
|
||||
rand.Read(rData)
|
||||
|
@ -55,8 +49,8 @@ func (btn Button) Rand() Button {
|
|||
}
|
||||
|
||||
// Set the URL for the button. Only for inline buttons.
|
||||
func (btn Button) WithURL(format string, v ...any) Button {
|
||||
btn.URL = fmt.Sprintf(format, v...)
|
||||
func (btn Button) WithUrl(format string, v ...any) Button {
|
||||
btn.Url = fmt.Sprintf(format, v...)
|
||||
return btn
|
||||
}
|
||||
|
||||
|
@ -78,16 +72,10 @@ func (btn Button) WithSendLocation(ok bool) Button {
|
|||
return btn
|
||||
}
|
||||
|
||||
func (btn Button) Go(pth Widget) Button {
|
||||
return btn.WithAction(WidgetGo{
|
||||
func (btn Button) Go(pth Path, args ...any) Button {
|
||||
return btn.WithAction(ScreenGo{
|
||||
Path: pth,
|
||||
})
|
||||
}
|
||||
|
||||
func (btn Button) GoWithArg(pth Widget, arg any) Button {
|
||||
return btn.WithAction(WidgetGo{
|
||||
Path: pth,
|
||||
Arg: arg,
|
||||
Args: args,
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -101,17 +89,11 @@ func (btn Button) ToTelegram() apix.KeyboardButton {
|
|||
|
||||
func (btn Button) ToTelegramInline() apix.InlineKeyboardButton {
|
||||
if btn.Data != "" {
|
||||
return apix.NewInlineKeyboardButtonData(
|
||||
btn.Text,
|
||||
btn.Data,
|
||||
)
|
||||
return apix.NewInlineKeyboardButtonData(btn.Text, btn.Data)
|
||||
}
|
||||
|
||||
if btn.URL != "" {
|
||||
return apix.NewInlineKeyboardButtonURL(
|
||||
btn.Text,
|
||||
btn.URL,
|
||||
)
|
||||
if btn.Url != "" {
|
||||
return apix.NewInlineKeyboardButtonURL(btn.Text, btn.Url)
|
||||
}
|
||||
|
||||
// If no match then return the data one with data the same as the text.
|
||||
|
@ -120,6 +102,9 @@ func (btn Button) ToTelegramInline() apix.InlineKeyboardButton {
|
|||
|
||||
// Return the key of the button to identify it by messages and callbacks.
|
||||
func (btn Button) Key() string {
|
||||
if btn == nil {
|
||||
return ""
|
||||
}
|
||||
if btn.Data != "" {
|
||||
return btn.Data
|
||||
}
|
||||
|
@ -128,7 +113,6 @@ func (btn Button) Key() string {
|
|||
return btn.Text
|
||||
}
|
||||
|
||||
func NewButtonRow(btns ...Button) ButtonRow {
|
||||
func NewButtonRow(btns ...*Button) ButtonRow {
|
||||
return btns
|
||||
}
|
||||
|
||||
|
|
|
@ -1,86 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"surdeus.su/core/tg"
|
||||
"os"
|
||||
)
|
||||
|
||||
var UsageAction = tg.Func(func(c tg.Context) {
|
||||
c.Sendf(
|
||||
"There is no such command %q",
|
||||
c.CallbackUpdate().Message.Command(),
|
||||
)
|
||||
})
|
||||
|
||||
var PreStartAction = tg.Func(func(c tg.Context) {
|
||||
c.Sendf("Please, use /start ")
|
||||
})
|
||||
|
||||
var BotCommands = []tg.Command{
|
||||
tg.NewCommand(
|
||||
"start",
|
||||
"start or restart the bot or move to the start screen",
|
||||
).Go(StartWidget),
|
||||
tg.NewCommand(
|
||||
"info",
|
||||
"info desc",
|
||||
).WithAction(tg.Func(func(c tg.Context) {
|
||||
c.SendfHTML(`<a href="https://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg">cock</a><strong>cock</strong> die`)
|
||||
})),
|
||||
tg.NewCommand("hello", "sends the 'Hello, World!' message back").
|
||||
WithAction(tg.Func(func(c tg.Context) {
|
||||
c.Sendf("Hello, World!")
|
||||
})),
|
||||
tg.NewCommand("read", "reads a string and sends it back").
|
||||
WithWidget(
|
||||
tg.Func(func(c tg.Context) {
|
||||
str := c.ReadString("Type a string and I will send it back")
|
||||
if str == "" {
|
||||
return
|
||||
}
|
||||
c.Sendf2("You typed `%s`", str)
|
||||
}),
|
||||
),
|
||||
tg.NewCommand("cat", "sends a sample image of cat from the server storage").
|
||||
WithAction(tg.Func(func(c tg.Context) {
|
||||
f, err := os.Open("media/cat.jpg")
|
||||
if err != nil {
|
||||
c.Sendf("err: %s", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
photo := tg.NewFile(f).Photo().Name("cat.jpg").Caption("A cat!")
|
||||
c.Send(photo)
|
||||
})),
|
||||
tg.NewCommand("document", "sends a sample text document").
|
||||
WithAction(tg.Func(func(c tg.Context) {
|
||||
f, err := os.Open("media/hello.txt")
|
||||
if err != nil {
|
||||
c.Sendf("err: %s", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
doc := tg.NewFile(f).Document().Name("hello.txt").Caption("The document")
|
||||
c.Send(doc)
|
||||
})),
|
||||
tg.NewCommand("botname", "get the bot name").
|
||||
WithAction(tg.Func(func(c tg.Context) {
|
||||
bd := c.Bot().Data().(*BotData)
|
||||
c.Sendf("My name is %q", bd.Name)
|
||||
})),
|
||||
tg.NewCommand("history", "print go history").
|
||||
WithAction(tg.Func(func(c tg.Context) {
|
||||
c.Sendf("%q", c.PathHistory())
|
||||
})),
|
||||
tg.NewCommand(
|
||||
"washington",
|
||||
"send location of the Washington",
|
||||
).WithAction(tg.Func(func(c tg.Context) {
|
||||
c.Sendf("Washington location")
|
||||
c.Send(
|
||||
tg.Messagef("").Location(
|
||||
47.751076, -120.740135,
|
||||
),
|
||||
)
|
||||
})),
|
||||
}
|
|
@ -1,57 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"surdeus.su/core/tg"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// A simple example widget to show
|
||||
// how to store and get session data values
|
||||
// and working with dynamic panels.
|
||||
var IncDecWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
|
||||
const format = "Press the buttons" +
|
||||
"to increment and decrement.\n" +
|
||||
"Current counter value = %d"
|
||||
d := ExtractSessionData(c)
|
||||
return tg.UI{
|
||||
tg.Messagef(format, d.Counter).Panel(
|
||||
c,
|
||||
tg.PanelFunc(func(
|
||||
panel *tg.PanelCompo,
|
||||
c tg.Context,
|
||||
) []tg.ButtonRow {
|
||||
d := ExtractSessionData(c)
|
||||
row := tg.ButtonRow{}
|
||||
if d.Counter != -5 {
|
||||
row = append(
|
||||
row,
|
||||
tg.Buttonf(
|
||||
"-",
|
||||
).WithAction(tg.Func(func(c tg.Context){
|
||||
d.Counter--
|
||||
panel.Text = fmt.Sprintf(format, d.Counter)
|
||||
c.Update(panel)
|
||||
})),
|
||||
)
|
||||
}
|
||||
if d.Counter != +5 {
|
||||
row = append(
|
||||
row,
|
||||
tg.Buttonf(
|
||||
"+",
|
||||
).WithAction(tg.Func(func(c tg.Context){
|
||||
d.Counter++
|
||||
panel.Text = fmt.Sprintf(format, d.Counter)
|
||||
c.Update(panel)
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
return []tg.ButtonRow{row}
|
||||
}),
|
||||
),
|
||||
tg.Messagef("Use the reply keyboard to get back").Reply(
|
||||
BackKeyboard.Reply(),
|
||||
),
|
||||
}
|
||||
})
|
|
@ -1,30 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"surdeus.su/core/tg"
|
||||
)
|
||||
|
||||
var HomeButton = tg.Buttonf("Home").Go(StartWidget)
|
||||
var BackButton = tg.Buttonf("Back").Go(tg.Back)
|
||||
var BackKeyboard = tg.NewKeyboard().Row(
|
||||
BackButton,
|
||||
)
|
||||
|
||||
var SendLocationKeyboard = tg.NewKeyboard().Row(
|
||||
tg.Buttonf("Send location").
|
||||
WithSendLocation(true).
|
||||
WithAction(tg.Func(func(c tg.Context) {
|
||||
l := c.CallbackUpdate().Message.Location
|
||||
c.Sendf(
|
||||
"Longitude: %f\n"+
|
||||
"Latitude: %f\n"+
|
||||
"Heading: %d"+
|
||||
"",
|
||||
l.Longitude,
|
||||
l.Latitude,
|
||||
l.Heading,
|
||||
)
|
||||
})),
|
||||
).Row(
|
||||
BackButton,
|
||||
).Reply()
|
|
@ -1,30 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"surdeus.su/core/tg"
|
||||
)
|
||||
|
||||
var LocationWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.Messagef(
|
||||
"Press the button to display your counter",
|
||||
).Inline(
|
||||
tg.NewKeyboard().Row(
|
||||
tg.Buttonf(
|
||||
"Check",
|
||||
).WithData(
|
||||
"check",
|
||||
).WithAction(tg.Func(func(c tg.Context) {
|
||||
d := ExtractSessionData(c)
|
||||
c.Sendf("Counter = %d", d.Counter)
|
||||
})),
|
||||
).Inline(),
|
||||
),
|
||||
|
||||
tg.Messagef(
|
||||
"Press the button to send your location!",
|
||||
).Reply(
|
||||
SendLocationKeyboard,
|
||||
),
|
||||
}
|
||||
})
|
402
cmd/test/main.go
402
cmd/test/main.go
|
@ -3,8 +3,10 @@ package main
|
|||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"fmt"
|
||||
|
||||
"surdeus.su/core/tg"
|
||||
"vultras.su/core/tg"
|
||||
)
|
||||
|
||||
type BotData struct {
|
||||
|
@ -15,47 +17,393 @@ type SessionData struct {
|
|||
Counter int
|
||||
}
|
||||
|
||||
func ExtractSessionData(c tg.Context) *SessionData {
|
||||
return c.SessionData().(*SessionData)
|
||||
type MutateMessageWidget struct {
|
||||
Mutate func(string) string
|
||||
}
|
||||
|
||||
var BackWidget = tg.RenderFunc(func(c tg.Context) tg.UI{
|
||||
return c.GoRet(tg.Back)
|
||||
})
|
||||
func NewMutateMessageWidget(fn func(string) string) *MutateMessageWidget {
|
||||
ret := &MutateMessageWidget{}
|
||||
ret.Mutate = fn
|
||||
return ret
|
||||
}
|
||||
|
||||
var beh = tg.NewBehaviour().SetInit(tg.Func(func(c tg.Context) {
|
||||
// The session initialization.
|
||||
c.SetSessionData(&SessionData{})
|
||||
})).SetRootWidget(
|
||||
// Setting as the most top
|
||||
// widget command handling
|
||||
// so we can call them at any screen.
|
||||
tg.NewCommandCompo().SetUsage(
|
||||
UsageAction,
|
||||
).SetPreStart(
|
||||
PreStartAction,
|
||||
).SetCommands(
|
||||
BotCommands...,
|
||||
),
|
||||
func (w *MutateMessageWidget) 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *MutateMessageWidget) Filter(u *tg.Update) bool {
|
||||
if u.Message == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ExtractSessionData(c *tg.Context) *SessionData {
|
||||
return c.Session.Data.(*SessionData)
|
||||
}
|
||||
|
||||
var (
|
||||
homeButton = tg.NewButton("Home").Go("/")
|
||||
backButton = tg.NewButton("Back").Go("-")
|
||||
backKeyboard = tg.NewKeyboard().Row(
|
||||
backButton,
|
||||
)
|
||||
|
||||
sendLocationKeyboard = tg.NewKeyboard().Row(
|
||||
tg.NewButton("Send location").
|
||||
WithSendLocation(true).
|
||||
ActionFunc(func(c *tg.Context) {
|
||||
l := c.Message.Location
|
||||
c.Sendf(
|
||||
"Longitude: %f\n"+
|
||||
"Latitude: %f\n"+
|
||||
"Heading: %d"+
|
||||
"",
|
||||
l.Longitude,
|
||||
l.Latitude,
|
||||
l.Heading,
|
||||
)
|
||||
}),
|
||||
).Row(
|
||||
backButton,
|
||||
).Reply()
|
||||
)
|
||||
|
||||
var beh = tg.NewBehaviour().
|
||||
WithInitFunc(func(c *tg.Context) {
|
||||
// The session initialization.
|
||||
c.Session.Data = &SessionData{}
|
||||
}).WithRootNode(tg.NewRootNode(
|
||||
// The "/" widget.
|
||||
tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.NewMessage(fmt.Sprintf(
|
||||
fmt.Sprint(
|
||||
"Hello, %s!\n",
|
||||
"The testing bot started!\n",
|
||||
"You can see the basics of usage in the ",
|
||||
"cmd/test/main.go file!",
|
||||
),
|
||||
c.SentFrom().UserName,
|
||||
)).Inline(
|
||||
tg.NewKeyboard().Row(
|
||||
tg.NewButton("GoT Github page").
|
||||
WithUrl("https://github.com/mojosa-software/got"),
|
||||
).Inline(),
|
||||
),
|
||||
|
||||
tg.NewMessage("Choose your interest").Reply(
|
||||
tg.NewKeyboard().Row(
|
||||
tg.NewButton("Inc/Dec").Go("/inc-dec"),
|
||||
).Row(
|
||||
tg.NewButton("Mutate messages").Go("/mutate-messages"),
|
||||
).Row(
|
||||
tg.NewButton("Send location").Go("/send-location"),
|
||||
).Row(
|
||||
tg.NewButton("Dynamic panel").Go("panel"),
|
||||
).Reply(),
|
||||
),
|
||||
|
||||
tg.Func(func(c *tg.Context) {
|
||||
for u := range c.Input() {
|
||||
if u.EditedMessage != nil {
|
||||
c.Sendf2("The new message is `%s`", u.EditedMessage.Text)
|
||||
}
|
||||
}
|
||||
}),
|
||||
}
|
||||
}),
|
||||
|
||||
tg.NewNode(
|
||||
"panel",
|
||||
tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
var (
|
||||
n = 0
|
||||
ln = 4
|
||||
panel *tg.PanelCompo
|
||||
)
|
||||
|
||||
panel = tg.NewMessage(
|
||||
"Some panel",
|
||||
).Panel(c, tg.RowserFunc(func(c *tg.Context) []tg.ButtonRow {
|
||||
btns := []tg.ButtonRow{
|
||||
tg.ButtonRow{tg.NewButton("Static shit")},
|
||||
}
|
||||
for i := 0; i < ln; i++ {
|
||||
num := 1 + n*ln + i
|
||||
btns = append(btns, tg.ButtonRow{
|
||||
tg.NewButton("%d", num).WithAction(tg.Func(func(c *tg.Context) {
|
||||
c.Sendf("%d", num*num)
|
||||
})),
|
||||
tg.NewButton("%d", num*num),
|
||||
})
|
||||
}
|
||||
btns = append(btns, tg.ButtonRow{
|
||||
tg.NewButton("Prev").WithAction(tg.ActionFunc(func(c *tg.Context) {
|
||||
n--
|
||||
panel.Update(c)
|
||||
})),
|
||||
tg.NewButton("Next").WithAction(tg.ActionFunc(func(c *tg.Context) {
|
||||
n++
|
||||
panel.Update(c)
|
||||
})),
|
||||
})
|
||||
|
||||
return btns
|
||||
}))
|
||||
|
||||
return tg.UI{
|
||||
panel,
|
||||
tg.NewMessage("").Reply(
|
||||
backKeyboard.Reply(),
|
||||
),
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
tg.NewNode(
|
||||
"mutate-messages", tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.NewMessage(
|
||||
"Choose the function to mutate string",
|
||||
).Reply(
|
||||
tg.NewKeyboard().Row(
|
||||
tg.NewButton("Upper case").Go("upper-case"),
|
||||
tg.NewButton("Lower case").Go("lower-case"),
|
||||
tg.NewButton("Escape chars").Go("escape"),
|
||||
).Row(
|
||||
backButton,
|
||||
).Reply(),
|
||||
),
|
||||
}
|
||||
}),
|
||||
tg.NewNode(
|
||||
"upper-case", tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.NewMessage(
|
||||
"Type a string and the bot will convert it to upper case",
|
||||
).Reply(
|
||||
backKeyboard.Reply(),
|
||||
),
|
||||
NewMutateMessageWidget(strings.ToUpper),
|
||||
}
|
||||
}),
|
||||
),
|
||||
tg.NewNode(
|
||||
"lower-case", tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.NewMessage(
|
||||
"Type a string and the bot will convert it to lower case",
|
||||
).Reply(
|
||||
backKeyboard.Reply(),
|
||||
),
|
||||
NewMutateMessageWidget(strings.ToLower),
|
||||
}
|
||||
}),
|
||||
),
|
||||
tg.NewNode(
|
||||
"escape", tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.NewMessage(
|
||||
"Type a string and the bot will escape characters in it",
|
||||
).Reply(
|
||||
backKeyboard.Reply(),
|
||||
),
|
||||
NewMutateMessageWidget(tg.Escape2),
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
tg.NewNode(
|
||||
"inc-dec", tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
var (
|
||||
kbd *tg.InlineCompo
|
||||
//cntMsg *tg.MessageCompo
|
||||
inline, std, onlyInc, onlyDec *tg.Inline
|
||||
)
|
||||
|
||||
d := ExtractSessionData(c)
|
||||
format := "Press the buttons to increment and decrement.\n" +
|
||||
"Current counter value = %d"
|
||||
|
||||
incBtn := tg.NewButton("+").ActionFunc(func(c *tg.Context) {
|
||||
d.Counter++
|
||||
kbd.Text = fmt.Sprintf(format, d.Counter)
|
||||
if d.Counter == 5 {
|
||||
kbd.Inline = onlyDec
|
||||
} else {
|
||||
kbd.Inline = std
|
||||
}
|
||||
kbd.Update(c)
|
||||
})
|
||||
decBtn := tg.NewButton("-").ActionFunc(func(c *tg.Context) {
|
||||
d.Counter--
|
||||
kbd.Text = fmt.Sprintf(format, d.Counter)
|
||||
if d.Counter == -5 {
|
||||
kbd.Inline = onlyInc
|
||||
} else {
|
||||
kbd.Inline = std
|
||||
}
|
||||
kbd.Update(c)
|
||||
//c.Sendf("%d", d.Counter)
|
||||
})
|
||||
|
||||
onlyInc = tg.NewKeyboard().Row(incBtn).Inline()
|
||||
onlyDec = tg.NewKeyboard().Row(decBtn).Inline()
|
||||
std = tg.NewKeyboard().Row(incBtn, decBtn).Inline()
|
||||
|
||||
if d.Counter == 5 {
|
||||
inline = onlyDec
|
||||
} else if d.Counter == -5 {
|
||||
inline = onlyInc
|
||||
} else {
|
||||
inline = std
|
||||
}
|
||||
|
||||
kbd = tg.NewMessage(
|
||||
fmt.Sprintf(format, d.Counter),
|
||||
).Inline(inline)
|
||||
|
||||
return tg.UI{
|
||||
kbd,
|
||||
tg.NewMessage("Use the reply keyboard to get back").Reply(
|
||||
backKeyboard.Reply(),
|
||||
),
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
tg.NewNode(
|
||||
"send-location", tg.RenderFunc(func(c *tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.NewMessage(
|
||||
"Press the button to display your counter",
|
||||
).Inline(
|
||||
tg.NewKeyboard().Row(
|
||||
tg.NewButton(
|
||||
"Check",
|
||||
).WithData(
|
||||
"check",
|
||||
).WithAction(tg.Func(func(c *tg.Context) {
|
||||
d := ExtractSessionData(c)
|
||||
c.Sendf("Counter = %d", d.Counter)
|
||||
})),
|
||||
).Inline(),
|
||||
),
|
||||
|
||||
tg.NewMessage(
|
||||
"Press the button to send your location!",
|
||||
).Reply(
|
||||
sendLocationKeyboard,
|
||||
),
|
||||
}
|
||||
}),
|
||||
),
|
||||
)).WithRoot(tg.NewCommandCompo().
|
||||
WithUsage(tg.Func(func(c *tg.Context) {
|
||||
c.Sendf("There is no such command %q", c.Message.Command())
|
||||
})).WithPreStart(tg.Func(func(c *tg.Context) {
|
||||
c.Sendf("Please, use /start ")
|
||||
})).WithCommands(
|
||||
tg.NewCommand("info", "info desc").
|
||||
ActionFunc(func(c *tg.Context) {
|
||||
c.SendfHTML(`<a href="https://res.cloudinary.com/demo/image/upload/v1312461204/sample.jpg">cock</a><strong>cock</strong> die`)
|
||||
}),
|
||||
tg.NewCommand(
|
||||
"start",
|
||||
"start or restart the bot or move to the start screen",
|
||||
).Go("/"),
|
||||
tg.NewCommand("hello", "sends the 'Hello, World!' message back").
|
||||
ActionFunc(func(c *tg.Context) {
|
||||
c.Sendf("Hello, World!")
|
||||
}),
|
||||
tg.NewCommand("read", "reads a string and sends it back").
|
||||
WithWidget(
|
||||
tg.Func(func(c *tg.Context) {
|
||||
str := c.ReadString("Type a string and I will send it back")
|
||||
c.Sendf2("You typed `%s`", str)
|
||||
}),
|
||||
),
|
||||
tg.NewCommand("cat", "sends a sample image of cat").
|
||||
ActionFunc(func(c *tg.Context) {
|
||||
f, err := os.Open("media/cat.jpg")
|
||||
if err != nil {
|
||||
c.Sendf("err: %s", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
photo := tg.NewFile(f).Photo().Name("cat.jpg").Caption("A cat!")
|
||||
c.Send(photo)
|
||||
}),
|
||||
tg.NewCommand("document", "sends a sample text document").
|
||||
ActionFunc(func(c *tg.Context) {
|
||||
f, err := os.Open("media/hello.txt")
|
||||
if err != nil {
|
||||
c.Sendf("err: %s", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
doc := tg.NewFile(f).Document().Name("hello.txt").Caption("The document")
|
||||
c.Send(doc)
|
||||
}),
|
||||
tg.NewCommand("botname", "get the bot name").
|
||||
WithAction(tg.Func(func(c *tg.Context) {
|
||||
bd := c.Bot.Data.(*BotData)
|
||||
c.Sendf("My name is %q", bd.Name)
|
||||
})),
|
||||
tg.NewCommand("dynamic", "check of the dynamic work").
|
||||
WithWidget(tg.Func(func(c *tg.Context) {
|
||||
})),
|
||||
tg.NewCommand("history", "print go history").
|
||||
WithAction(tg.Func(func(c *tg.Context) {
|
||||
c.Sendf("%q", c.History())
|
||||
})),
|
||||
tg.NewCommand("washington", "send location of the Washington").
|
||||
WithAction(tg.Func(func(c *tg.Context) {
|
||||
c.Sendf("Washington location")
|
||||
c.Send(
|
||||
tg.NewMessage("").Location(
|
||||
47.751076, -120.740135,
|
||||
),
|
||||
)
|
||||
})),
|
||||
tg.NewCommand("invoice", "invoice check").
|
||||
WithAction(tg.Func(func(c *tg.Context) {
|
||||
})),
|
||||
))
|
||||
|
||||
func main() {
|
||||
log.Println(beh.Screens)
|
||||
token := os.Getenv("BOT_TOKEN")
|
||||
|
||||
bot, err := tg.NewBot(token)
|
||||
if err != nil {
|
||||
log.Fatalf("tg.NewBot(...): %s", err)
|
||||
log.Panic(err)
|
||||
}
|
||||
bot = bot.SetBehaviour(beh)
|
||||
//bot.API().Debug = true
|
||||
bot = bot.
|
||||
WithBehaviour(beh).
|
||||
Debug(true)
|
||||
|
||||
bot.SetData(&BotData{
|
||||
bot.Data = &BotData{
|
||||
Name: "Jay",
|
||||
})
|
||||
}
|
||||
|
||||
log.Printf("Authorized on account %s", bot.API().Self.UserName)
|
||||
log.Printf("Authorized on account %s", bot.Api.Self.UserName)
|
||||
err = bot.Run()
|
||||
if err != nil {
|
||||
log.Fatalf("bot.Run(...): %s", err)
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,92 +0,0 @@
|
|||
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),
|
||||
}
|
||||
})
|
|
@ -1,38 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"surdeus.su/core/tg"
|
||||
)
|
||||
|
||||
var DynamicPanelWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.Messagef("Paged panel").PanelPager(
|
||||
c, 0, 5,
|
||||
tg.PanelPagerFunc(func(
|
||||
panel *tg.PanelPagerCompo,
|
||||
c tg.Context, page, size int,
|
||||
) tg.PanelPage {
|
||||
rows := []tg.ButtonRow{}
|
||||
for i := 0; i < size; i++ {
|
||||
num := 1 + page*size + i
|
||||
rows = append(rows, tg.ButtonRow{
|
||||
tg.Buttonf("%d", num).Rand().WithAction(tg.Func(func(c tg.Context) {
|
||||
_, err := c.Sendf("%d", num*num)
|
||||
if err != nil {
|
||||
}
|
||||
})),
|
||||
tg.Buttonf("%d", num*num),
|
||||
})
|
||||
}
|
||||
return tg.PanelPage{
|
||||
Rows: rows,
|
||||
Next: page < 3,
|
||||
Prev: page != 0,
|
||||
}
|
||||
}),
|
||||
),
|
||||
tg.Messagef("").Reply(
|
||||
BackKeyboard.Reply(),
|
||||
),
|
||||
}
|
||||
})
|
|
@ -1,45 +0,0 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"surdeus.su/core/tg"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var StartWidget = tg.RenderFunc(func(c tg.Context) tg.UI {
|
||||
return tg.UI{
|
||||
tg.Messagef(
|
||||
fmt.Sprint(
|
||||
"Hello, %s!",
|
||||
"The testing bot started!",
|
||||
"You can see the basics of usage in the ",
|
||||
"cmd/test/main.go file and other files in the cmd/test!",
|
||||
),
|
||||
c.CallbackUpdate().SentFrom().UserName,
|
||||
).Inline(
|
||||
tg.NewKeyboard().Row(
|
||||
tg.Buttonf("TeleGopher surdeus.su page").
|
||||
WithURL("https://surdeus.su/core/tg"),
|
||||
).Inline(),
|
||||
),
|
||||
|
||||
tg.Messagef("Choose your interest").Reply(
|
||||
tg.NewKeyboard().List(
|
||||
tg.Buttonf("Back").Go(BackWidget),
|
||||
tg.Buttonf("Inc/Dec").Go(IncDecWidget),
|
||||
tg.Buttonf("Mutate messages").Go(MutateMessagesWidget),
|
||||
tg.Buttonf("Send location").Go(LocationWidget),
|
||||
tg.Buttonf("Dynamic panel").Go(DynamicPanelWidget),
|
||||
tg.Buttonf("Check panic").Go(nil),
|
||||
).Reply(),
|
||||
),
|
||||
|
||||
// Testing reaction to editing messages.
|
||||
tg.Func(func(c tg.Context) {
|
||||
for u := range c.Input() {
|
||||
if u.EditedMessage != nil {
|
||||
c.Sendf2("The new message is `%s`", u.EditedMessage.Text)
|
||||
}
|
||||
}
|
||||
}),
|
||||
}
|
||||
})
|
73
command.go
73
command.go
|
@ -4,7 +4,6 @@ import (
|
|||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
)
|
||||
|
||||
|
||||
type CommandType uint8
|
||||
const (
|
||||
PrivateCommandType CommandType = iota
|
||||
|
@ -19,22 +18,21 @@ type Command struct {
|
|||
Description string
|
||||
Action Action
|
||||
Widget Widget
|
||||
WidgetArg any
|
||||
}
|
||||
|
||||
type CommandMap map[CommandName]Command
|
||||
type CommandMap map[CommandName]*Command
|
||||
|
||||
func NewCommand(name CommandName, desc string) Command {
|
||||
if name == "" || desc == "" {
|
||||
panic("name and description cannot be an empty string")
|
||||
}
|
||||
return Command{
|
||||
return &Command{
|
||||
Name: name,
|
||||
Description: desc,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Command) WithAction(a Action) Command {
|
||||
func (c *Command) WithAction(a Action) *Command {
|
||||
c.Action = a
|
||||
return c
|
||||
}
|
||||
|
@ -44,25 +42,21 @@ func (c Command) WithWidget(w Widget) Command {
|
|||
return c
|
||||
}
|
||||
|
||||
// Convert command into the tgbotapi.BotCommand
|
||||
func (c Command) ToAPI() tgbotapi.BotCommand {
|
||||
func (c Command) WidgetFunc(fn Func) Command {
|
||||
return c.WithWidget(fn)
|
||||
}
|
||||
|
||||
func (c Command) ToApi() tgbotapi.BotCommand {
|
||||
ret := tgbotapi.BotCommand{}
|
||||
ret.Command = string(c.Name)
|
||||
ret.Description = c.Description
|
||||
return ret
|
||||
}
|
||||
|
||||
// Simple command to go to another screen.
|
||||
func (c Command) Go(pth Widget) Command {
|
||||
return c.WithAction(WidgetGo{
|
||||
func (c Command) Go(pth Path, args ...any) Command {
|
||||
return c.WithAction(ScreenGo{
|
||||
Path: pth,
|
||||
})
|
||||
}
|
||||
|
||||
func (c Command) GoWithArg(pth Widget, arg any) Command {
|
||||
return c.WithAction(WidgetGo{
|
||||
Path: pth,
|
||||
Arg: arg,
|
||||
Args: args,
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -75,13 +69,13 @@ type CommandCompo struct {
|
|||
}
|
||||
|
||||
// Returns new empty CommandCompo.
|
||||
func NewCommandCompo(cmds ...Command) *CommandCompo {
|
||||
ret := (&CommandCompo{}).SetCommands(cmds...)
|
||||
func NewCommandCompo(cmds ...*Command) *CommandCompo {
|
||||
ret := CommandCompo{}.WithCommands(cmds...)
|
||||
return ret
|
||||
}
|
||||
|
||||
// Set the commands to handle.
|
||||
func (w *CommandCompo) SetCommands(cmds ...Command) *CommandCompo {
|
||||
func (w CommandCompo) WithCommands(cmds ...*Command) *CommandCompo {
|
||||
if w.Commands == nil {
|
||||
w.Commands = make(CommandMap)
|
||||
}
|
||||
|
@ -99,20 +93,24 @@ func (w *CommandCompo) SetCommands(cmds ...Command) *CommandCompo {
|
|||
}
|
||||
|
||||
// Set the prestart action.
|
||||
func (w *CommandCompo) SetPreStart(a Action) *CommandCompo {
|
||||
func (w *CommandCompo) WithPreStart(a Action) *CommandCompo {
|
||||
w.PreStart = a
|
||||
return w
|
||||
}
|
||||
|
||||
// Set the usage action.
|
||||
func (w *CommandCompo) SetUsage(a Action) *CommandCompo {
|
||||
func (w CommandCompo) WithUsage(a Action) *CommandCompo {
|
||||
w.Usage = a
|
||||
return w
|
||||
}
|
||||
|
||||
// Filtering all the non commands.
|
||||
func (widget *CommandCompo) Filter(
|
||||
u Update,
|
||||
// Set the usage action with function.
|
||||
func (w CommandCompo) WithUsageFunc(fn ActionFunc) *CommandCompo {
|
||||
return w.WithUsage(fn)
|
||||
}
|
||||
|
||||
func (widget CommandCompo) Filter(
|
||||
u *Update,
|
||||
) bool {
|
||||
if u.Message == nil || !u.Message.IsCommand() {
|
||||
return false
|
||||
|
@ -122,26 +120,27 @@ func (widget *CommandCompo) Filter(
|
|||
}
|
||||
|
||||
// Implementing server.
|
||||
func (compo *CommandCompo) Serve(c Context) {
|
||||
// First should bring the new command into the action.
|
||||
c.Bot().DeleteCommands()
|
||||
err := c.Bot().SetCommands(
|
||||
tgbotapi.NewBotCommandScopeChat(c.SessionID().ToAPI()),
|
||||
func (compo CommandCompo) Serve(c Context) {
|
||||
/*commanders := make(map[CommandName] BotCommander)
|
||||
for k, v := range compo.Commands {
|
||||
commanders[k] = v
|
||||
}*/
|
||||
c.bot.DeleteCommands()
|
||||
err := c.bot.SetCommands(
|
||||
tgbotapi.NewBotCommandScopeChat(c.Session.Id.ToApi()),
|
||||
compo.Commands,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
c.Sendf("error: %q", err)
|
||||
}
|
||||
|
||||
var cmdUpdates *UpdateChan
|
||||
for u := range c.Input() {
|
||||
if c.Path() == nil && u.Message != nil {
|
||||
if c.Path() == "" && u.Message != nil {
|
||||
// Skipping and executing the preinit action
|
||||
// while we have the empty screen.
|
||||
// E. g. the session did not start.
|
||||
if !u.Message.IsCommand() ||
|
||||
u.Message.Command() != "start" {
|
||||
if !(u.Message.IsCommand() && u.Message.Command() == "start") {
|
||||
c.WithUpdate(u).Run(compo.PreStart)
|
||||
continue
|
||||
}
|
||||
|
@ -158,10 +157,8 @@ func (compo *CommandCompo) Serve(c Context) {
|
|||
|
||||
c.WithUpdate(u).Run(cmd.Action)
|
||||
if cmd.Widget != nil {
|
||||
// Closing current widget
|
||||
cmdUpdates.Close()
|
||||
// And running the other one.
|
||||
cmdUpdates, _ = c.WithArg(cmd.WidgetArg).RunWidget(cmd.Widget)
|
||||
cmdUpdates, _ = c.WithUpdate(u).RunWidget(cmd.Widget)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
@ -171,7 +168,7 @@ func (compo *CommandCompo) Serve(c Context) {
|
|||
// executing one.
|
||||
cmdUpdates.Send(u)
|
||||
} else {
|
||||
c.SkipUpdate(u)
|
||||
c.Skip(u)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
288
context.go
288
context.go
|
@ -6,14 +6,11 @@ import (
|
|||
"net/http"
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
//"path"
|
||||
//"log"
|
||||
)
|
||||
|
||||
|
||||
// Interface to interact with the user.
|
||||
type Context struct {
|
||||
// The session contains all
|
||||
// the information between the contexts.
|
||||
session *Session
|
||||
// The update that called the Context usage.
|
||||
update Update
|
||||
|
@ -30,15 +27,15 @@ type Context struct {
|
|||
// make other user to leave the bot at first but
|
||||
// maybe you will find another usage for this.
|
||||
// Returns users context by specified session ID
|
||||
// or false if the user is not logged in.
|
||||
func (c Context) As(sid SessionID) (Context, bool) {
|
||||
s, ok := c.Bot().GotSession(sid)
|
||||
// or nil if the user is not logged in.
|
||||
func (c Context) As(sid SessionId) Context {
|
||||
n, ok := c.Bot.contexts[sid]
|
||||
if !ok {
|
||||
return Context{}, false
|
||||
return nil
|
||||
}
|
||||
return &Context{
|
||||
context: n,
|
||||
}
|
||||
|
||||
c.session = s
|
||||
return c, true
|
||||
}
|
||||
|
||||
// General type function to define actions, single component widgets
|
||||
|
@ -50,18 +47,15 @@ func (f Func) Act(c Context) {
|
|||
func (f Func) Serve(c Context) {
|
||||
f(c)
|
||||
}
|
||||
func(f Func) Filter(_ Update) bool {
|
||||
func(f Func) Filter(_ *Update) bool {
|
||||
return false
|
||||
}
|
||||
func (f Func) Render(_ Context) UI {
|
||||
func (f Func) Render(_ *Context) UI {
|
||||
return UI{
|
||||
f,
|
||||
}
|
||||
}
|
||||
|
||||
// The type represents type
|
||||
// of current context the processing is happening
|
||||
// in.
|
||||
type ContextType uint8
|
||||
const (
|
||||
NoContextType ContextType = iota
|
||||
|
@ -71,16 +65,17 @@ const (
|
|||
|
||||
// Goroutie function to handle each user.
|
||||
func (c Context) serve() {
|
||||
beh := c.Bot().behaviour
|
||||
beh := c.Bot.behaviour
|
||||
c.Run(beh.Init)
|
||||
for {
|
||||
defer func(){
|
||||
if err := recover() ; err != nil {
|
||||
// Need to add some handling later.
|
||||
}
|
||||
}()
|
||||
beh.Root.Serve(c)
|
||||
beh.Root.Serve(c)
|
||||
}
|
||||
|
||||
func (c Context) Path() Path {
|
||||
ln := len(c.pathHistory)
|
||||
if ln == 0 {
|
||||
return ""
|
||||
}
|
||||
return c.pathHistory[ln-1]
|
||||
}
|
||||
|
||||
func (c Context) Arg() any {
|
||||
|
@ -93,15 +88,21 @@ func (c Context) Run(a Action) {
|
|||
}
|
||||
}
|
||||
|
||||
// Only for the root widget usage.
|
||||
// Skip the update sending it down to
|
||||
// the underlying widget.
|
||||
func (c Context) Skip(u Update) {
|
||||
c.skippedUpdates.Send(u)
|
||||
}
|
||||
|
||||
// Sends to the Sendable object to the session user.
|
||||
func (c Context) Send(v Sendable) (*Message, error) {
|
||||
config := v.SendConfig(c.SessionID(), c.Bot())
|
||||
// Sends to the Sendable object.
|
||||
func (c Context) Send(v Sendable) (Message, error) {
|
||||
config := v.SendConfig(c.Session.Id, c.Bot)
|
||||
if config.Error != nil {
|
||||
return nil, config.Error
|
||||
}
|
||||
|
||||
msg, err := c.Bot().API().Send(config.ToAPI())
|
||||
msg, err := c.Bot.Api.Send(config.ToApi())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -110,23 +111,23 @@ func (c Context) Send(v Sendable) (*Message, error) {
|
|||
|
||||
// Sends the formatted with fmt.Sprintf message to the user
|
||||
// using default Markdown parsing format.
|
||||
func (c Context) Sendf(format string, v ...any) (*Message, error) {
|
||||
return c.Send(Messagef(format, v...))
|
||||
func (c Context) Sendf(format string, v ...any) (Message, error) {
|
||||
return c.Send(NewMessage(format, v...))
|
||||
}
|
||||
|
||||
// Same as Sendf but uses Markdown 2 format for parsing.
|
||||
func (c Context) Sendf2(format string, v ...any) (*Message, error) {
|
||||
return c.Send(Messagef(format, v...).MD2())
|
||||
func (c Context) Sendf2(format string, v ...any) (Message, error) {
|
||||
return c.Send(NewMessage(fmt.Sprintf(format, v...)).MD2())
|
||||
}
|
||||
|
||||
// Same as Sendf but uses HTML format for parsing.
|
||||
func (c Context) SendfHTML(format string, v ...any) (*Message, error) {
|
||||
return c.Send(Messagef(format, v...).HTML())
|
||||
func (c Context) SendfHTML(format string, v ...any) (Message, error) {
|
||||
return c.Send(NewMessage(fmt.Sprintf(format, v...)).HTML())
|
||||
}
|
||||
|
||||
// Send the message in raw format escaping all the special characters.
|
||||
func (c Context) SendfR(format string, v ...any) (*Message, error) {
|
||||
return c.Send(Messagef("%s", Escape2(fmt.Sprintf(format, v...))).MD2())
|
||||
func (c Context) SendfR(format string, v ...any) (Message, error) {
|
||||
return c.Send(NewMessage(Escape2(fmt.Sprintf(format, v...))).MD2())
|
||||
}
|
||||
|
||||
// Get the input for current widget.
|
||||
|
@ -140,8 +141,8 @@ func (c Context) WithArg(v any) Context {
|
|||
return c
|
||||
}
|
||||
|
||||
func (c Context) WithUpdate(u Update) Context {
|
||||
c.update = u
|
||||
func (c Context) WithUpdate(u *Update) Context {
|
||||
c.Update = u
|
||||
return c
|
||||
}
|
||||
|
||||
|
@ -150,6 +151,14 @@ func (c Context) WithInput(input *UpdateChan) Context {
|
|||
return c
|
||||
}
|
||||
|
||||
func (c Context) Go(pth Path) error {
|
||||
return c.session.go_(pth, nil)
|
||||
}
|
||||
|
||||
func (c Context) GoWithArg(pth Path, arg any) error {
|
||||
return c.session.go_(pth, arg)
|
||||
}
|
||||
|
||||
// Customized actions for the bot.
|
||||
type Action interface {
|
||||
Act(Context)
|
||||
|
@ -157,18 +166,29 @@ type Action interface {
|
|||
|
||||
type ActionFunc func(Context)
|
||||
|
||||
func (af ActionFunc) Act(c Context) {
|
||||
func (af ActionFunc) Act(c *Context) {
|
||||
af(c)
|
||||
}
|
||||
|
||||
func (c Context) History() []Path {
|
||||
return c.session.pathHistory
|
||||
}
|
||||
|
||||
func (c Context) PathExist(pth Path) bool {
|
||||
return c.bot.behaviour.PathExist(pth)
|
||||
}
|
||||
|
||||
// Simple way to read strings for widgets with
|
||||
// the specified prompt.
|
||||
func (c Context) ReadString(promptf string, args ...any) string {
|
||||
var text string
|
||||
if promptf != "" {
|
||||
if pref != "" {
|
||||
c.Sendf(promptf, args...)
|
||||
}
|
||||
for u := range c.Input() {
|
||||
if u == nil {
|
||||
break
|
||||
}
|
||||
if u.Message == nil {
|
||||
continue
|
||||
}
|
||||
|
@ -178,25 +198,19 @@ func (c Context) ReadString(promptf string, args ...any) string {
|
|||
return text
|
||||
}
|
||||
|
||||
func (c Context) Update(updater Updater) error {
|
||||
return updater.Update(c)
|
||||
}
|
||||
|
||||
func (c Context) CallbackUpdate() *Update {
|
||||
return &c.update
|
||||
func (c Context) Update() Update {
|
||||
return c.update
|
||||
}
|
||||
|
||||
// Returns the reader for specified file ID and path.
|
||||
func (c Context) GetFile(fileID FileID) (io.ReadCloser, string, error) {
|
||||
file, err := c.Bot().API().GetFile(tgbotapi.FileConfig{
|
||||
FileID: string(fileID),
|
||||
})
|
||||
func (c *Context) GetFile(fileId FileId) (io.ReadCloser, string, error) {
|
||||
file, err := c.Bot.Api.GetFile(tgbotapi.FileConfig{FileID:string(fileId)})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
r, err := http.Get(fmt.Sprintf(
|
||||
"https://api.telegram.org/file/bot%s/%s",
|
||||
c.Bot().API().Token,
|
||||
c.Bot.Api.Token,
|
||||
file.FilePath,
|
||||
))
|
||||
if err != nil {
|
||||
|
@ -209,9 +223,8 @@ func (c Context) GetFile(fileID FileID) (io.ReadCloser, string, error) {
|
|||
return r.Body, file.FilePath, nil
|
||||
}
|
||||
|
||||
// Reads all the content from the specified file.
|
||||
func (c Context) ReadFile(fileID FileID) ([]byte, string, error) {
|
||||
file, pth, err := c.GetFile(fileID)
|
||||
func (c *Context) ReadFile(fileId FileId) ([]byte, string, error) {
|
||||
file, pth, err := c.GetFile(fileId)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
@ -225,172 +238,3 @@ func (c Context) ReadFile(fileID FileID) ([]byte, string, error) {
|
|||
return bts, pth, nil
|
||||
}
|
||||
|
||||
func (c Context) RunCompo(compo Component) (*UpdateChan, error) {
|
||||
if compo == nil {
|
||||
return nil, nil
|
||||
}
|
||||
sendable, canSend := compo.(Sendable)
|
||||
if canSend {
|
||||
msg, err := c.Send(sendable)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sendable.SetMessage(msg)
|
||||
}
|
||||
updates := NewUpdateChan()
|
||||
go func() {
|
||||
compo.Serve(
|
||||
c.WithInput(updates),
|
||||
)
|
||||
// To let widgets finish themselves before
|
||||
// the channel is closed and close it by themselves.
|
||||
updates.Close()
|
||||
}()
|
||||
return updates, nil
|
||||
}
|
||||
|
||||
// Run widget in background returning the new input channel for it.
|
||||
func (c Context) RunWidget(widget Widget) (*UpdateChan, error) {
|
||||
var err error
|
||||
if widget == nil {
|
||||
return nil, EmptyWidgetErr
|
||||
}
|
||||
|
||||
compos := widget.Render(c)
|
||||
// Leave if changed path or components are empty.
|
||||
if compos == nil {
|
||||
return nil, EmptyCompoErr
|
||||
}
|
||||
chns := make([]*UpdateChan, len(compos))
|
||||
for i, compo := range compos {
|
||||
chns[i], err = c.RunCompo(compo)
|
||||
if err != nil {
|
||||
for _, chn := range chns {
|
||||
chn.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
ret := NewUpdateChan()
|
||||
go func() {
|
||||
ln := len(compos)
|
||||
//ation: u != nil (mismatchedtypes Update and untyped nil)
|
||||
UPDATE:
|
||||
for u := range ret.Chan() {
|
||||
cnt := 0
|
||||
for i, compo := range compos {
|
||||
chn := chns[i]
|
||||
if chn.Closed() {
|
||||
cnt++
|
||||
continue
|
||||
}
|
||||
if !compo.Filter(u) {
|
||||
chn.Send(u)
|
||||
continue UPDATE
|
||||
}
|
||||
}
|
||||
if cnt == ln {
|
||||
break
|
||||
}
|
||||
}
|
||||
ret.Close()
|
||||
for _, chn := range chns {
|
||||
chn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (c Context) GoRet(pth Widget) UI {
|
||||
return UI{WidgetGo{
|
||||
Path: pth,
|
||||
Arg: c.Arg(),
|
||||
}}
|
||||
}
|
||||
|
||||
// Go to the specified widget
|
||||
// using context values.
|
||||
func (c Context) Go(pth Widget) error {
|
||||
var err error
|
||||
if pth == nil {
|
||||
c.session.pathHistory = []Widget{}
|
||||
return nil
|
||||
}
|
||||
|
||||
var back bool
|
||||
if pth == Back {
|
||||
if len(c.session.pathHistory) <= 1 {
|
||||
return c.Go(nil)
|
||||
}
|
||||
pth = c.session.pathHistory[len(c.session.pathHistory)-2]
|
||||
c.session.pathHistory =
|
||||
c.session.pathHistory[:len(c.session.pathHistory)-1]
|
||||
back = true
|
||||
}
|
||||
|
||||
if !back {
|
||||
c.session.pathHistory = append(c.session.pathHistory, pth)
|
||||
}
|
||||
|
||||
// Stopping the current widget.
|
||||
c.session.skippedUpdates.Close()
|
||||
|
||||
// Running the new one.
|
||||
c.session.skippedUpdates, err = c.RunWidget(pth)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Context) Session() Session {
|
||||
return *c.session
|
||||
}
|
||||
|
||||
func (c Context) SetSessionData(v any) {
|
||||
c.session.Data = v
|
||||
}
|
||||
|
||||
func (c Context) SessionData() any {
|
||||
return c.session.Data
|
||||
}
|
||||
|
||||
func (c Context) SessionID() SessionID {
|
||||
return c.session.ID
|
||||
}
|
||||
|
||||
func (c Context) SessionScope() SessionScope {
|
||||
return c.session.Scope
|
||||
}
|
||||
|
||||
// Only for the root widget usage.
|
||||
// Skip the update sending it down to
|
||||
// the underlying widget.
|
||||
func (c Context) SkipUpdate(u Update) {
|
||||
c.session.skippedUpdates.Send(u)
|
||||
}
|
||||
|
||||
// Return the session related bot.
|
||||
func (c Context) Bot() *Bot {
|
||||
return c.session.bot
|
||||
}
|
||||
|
||||
// Return context's session's path history.
|
||||
func (c Context) PathHistory() []Widget {
|
||||
return c.session.pathHistory
|
||||
}
|
||||
|
||||
func (c Context) SetPathHistory(hist []Widget) {
|
||||
c.session.pathHistory = hist
|
||||
}
|
||||
|
||||
func (c Context) Path() Widget {
|
||||
ln := len(c.session.pathHistory)
|
||||
if ln == 0 {
|
||||
return nil
|
||||
}
|
||||
return c.session.pathHistory[ln-1]
|
||||
}
|
||||
|
|
|
@ -1,4 +0,0 @@
|
|||
#!/bin/sh
|
||||
|
||||
wgo sh -c './btest && ./exe/test'
|
||||
|
13
file.go
13
file.go
|
@ -10,7 +10,6 @@ import (
|
|||
"github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
)
|
||||
|
||||
type FileID string
|
||||
type FileConfig = tgbotapi.FileConfig
|
||||
type PhotoConfig = tgbotapi.PhotoConfig
|
||||
type FileType int
|
||||
|
@ -41,7 +40,7 @@ type File struct {
|
|||
func NewFile(reader io.Reader) *File {
|
||||
ret := &File{}
|
||||
|
||||
ret.MessageCompo = *Messagef("")
|
||||
ret.MessageCompo = NewMessage("")
|
||||
ret.reader = reader
|
||||
ret.upload = true
|
||||
|
||||
|
@ -108,21 +107,21 @@ func (f *File) SendData() string {
|
|||
}
|
||||
|
||||
func (f *File) SendConfig(
|
||||
sid SessionID, bot *Bot,
|
||||
sid SessionId, bot *Bot,
|
||||
) (SendConfig) {
|
||||
var config SendConfig
|
||||
cid := sid.ToAPI()
|
||||
cid := sid.ToApi()
|
||||
|
||||
switch f.Type() {
|
||||
case PhotoFileType:
|
||||
photo := tgbotapi.NewPhoto(cid, f)
|
||||
photo.Caption = f.caption
|
||||
|
||||
config.Chattable = photo
|
||||
config.Photo = &photo
|
||||
case DocumentFileType:
|
||||
doc := tgbotapi.NewDocument(sid.ToAPI(), f)
|
||||
doc := tgbotapi.NewDocument(sid.ToApi(), f)
|
||||
doc.Caption = f.caption
|
||||
config.Chattable = doc
|
||||
config.Document = &doc
|
||||
default:
|
||||
panic(UnknownFileTypeErr)
|
||||
}
|
||||
|
|
|
@ -7,12 +7,12 @@ package tg
|
|||
type Filterer interface {
|
||||
// Return true if should filter the update
|
||||
// and not send it inside the widget.
|
||||
Filter(Update) bool
|
||||
Filter(*Update) bool
|
||||
}
|
||||
|
||||
type FilterFunc func(Update) bool
|
||||
type FilterFunc func(*Update) bool
|
||||
func (f FilterFunc) Filter(
|
||||
u Update,
|
||||
u *Update,
|
||||
) bool {
|
||||
return f(u)
|
||||
}
|
||||
|
|
25
go.go
25
go.go
|
@ -1,33 +1,22 @@
|
|||
package tg
|
||||
|
||||
func Go(pth Widget) UI {
|
||||
func Go(pth Path) UI {
|
||||
return UI{
|
||||
WidgetGo{
|
||||
Path: pth,
|
||||
},
|
||||
GoWidget(pth),
|
||||
}
|
||||
}
|
||||
|
||||
// The type implements changing current path to the widget.
|
||||
type WidgetGo struct {
|
||||
Path Widget
|
||||
Arg any
|
||||
}
|
||||
|
||||
func (w WidgetGo) Act(c Context) {
|
||||
c.WithArg(w.Arg).Go(w.Path)
|
||||
}
|
||||
|
||||
type GoWidget string
|
||||
// Implementing the Server interface.
|
||||
func (widget WidgetGo) Serve(c Context) {
|
||||
func (widget GoWidget) Serve(c Context) {
|
||||
c.input.Close()
|
||||
c.WithArg(widget.Path).Go(widget.Path)
|
||||
c.Go(Path(widget))
|
||||
}
|
||||
|
||||
func (widget WidgetGo) Render(c Context) UI {
|
||||
func (widget GoWidget) Render(c Context) UI {
|
||||
return UI{widget}
|
||||
}
|
||||
|
||||
func (widget WidgetGo) Filter(u Update) bool {
|
||||
func (widget GoWidget) Filter(u Update) bool {
|
||||
return true
|
||||
}
|
||||
|
|
2
go.mod
2
go.mod
|
@ -1,4 +1,4 @@
|
|||
module surdeus.su/core/tg
|
||||
module vultras.su/core/tg
|
||||
|
||||
go 1.20
|
||||
|
||||
|
|
46
inline.go
46
inline.go
|
@ -11,7 +11,7 @@ type Inline struct {
|
|||
}
|
||||
|
||||
// Convert the inline keyboard to markup for the tgbotapi.
|
||||
func (kbd Inline) ToAPI() tgbotapi.InlineKeyboardMarkup {
|
||||
func (kbd Inline) ToApi() tgbotapi.InlineKeyboardMarkup {
|
||||
rows := [][]tgbotapi.InlineKeyboardButton{}
|
||||
for _, row := range kbd.Rows {
|
||||
if row == nil {
|
||||
|
@ -19,7 +19,7 @@ func (kbd Inline) ToAPI() tgbotapi.InlineKeyboardMarkup {
|
|||
}
|
||||
buttons := []tgbotapi.InlineKeyboardButton{}
|
||||
for _, button := range row {
|
||||
if !button.Valid {
|
||||
if button == nil {
|
||||
continue
|
||||
}
|
||||
buttons = append(buttons, button.ToTelegramInline())
|
||||
|
@ -38,14 +38,12 @@ type InlineCompo struct {
|
|||
|
||||
// Implementing the Sendable interface.
|
||||
func (compo *InlineCompo) SendConfig(
|
||||
sid SessionID, bot *Bot,
|
||||
sid SessionId, bot *Bot,
|
||||
) (SendConfig) {
|
||||
sendConfig := compo.MessageCompo.SendConfig(sid, bot)
|
||||
msg := sendConfig.Chattable.(tgbotapi.MessageConfig)
|
||||
if len(compo.Inline.Rows) > 0 {
|
||||
msg.ReplyMarkup = compo.Inline.ToAPI()
|
||||
sendConfig.Message.ReplyMarkup = compo.Inline.ToApi()
|
||||
}
|
||||
sendConfig.Chattable = msg
|
||||
|
||||
return sendConfig
|
||||
}
|
||||
|
@ -53,39 +51,34 @@ func (compo *InlineCompo) SendConfig(
|
|||
// Update the component on the client side.
|
||||
// Requires exactly the pointer but not the value
|
||||
// cause it changes insides of the structure.
|
||||
func (compo *InlineCompo) Update(c Context) error {
|
||||
func (compo *InlineCompo) Update(c Context) {
|
||||
if compo.Message != nil {
|
||||
var edit tgbotapi.Chattable
|
||||
markup := compo.Inline.ToAPI()
|
||||
markup := compo.Inline.ToApi()
|
||||
ln := len(markup.InlineKeyboard)
|
||||
if ln == 0 || compo.Inline.Rows == nil {
|
||||
edit = tgbotapi.NewEditMessageText(
|
||||
c.SessionID().ToAPI(),
|
||||
c.Session.Id.ToApi(),
|
||||
compo.Message.MessageID,
|
||||
compo.Text,
|
||||
)
|
||||
} else {
|
||||
edit = tgbotapi.NewEditMessageTextAndMarkup(
|
||||
c.SessionID().ToAPI(),
|
||||
c.Session.Id.ToApi(),
|
||||
compo.Message.MessageID,
|
||||
compo.Text,
|
||||
markup,
|
||||
)
|
||||
}
|
||||
msg, err := c.Bot().API().Send(edit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
msg, _ := c.Bot.Api.Send(edit)
|
||||
compo.Message = &msg
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
compo.buttonMap = compo.MakeButtonMap()
|
||||
}
|
||||
|
||||
// Implementing the Filterer interface.
|
||||
func (compo *InlineCompo) Filter(u Update) bool {
|
||||
if u.CallbackQuery == nil {
|
||||
func (compo InlineCompo) Filter(u Update) bool {
|
||||
if compo == nil || u.CallbackQuery == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
|
@ -98,13 +91,13 @@ func (compo *InlineCompo) Filter(u Update) bool {
|
|||
}
|
||||
|
||||
// Implementing the Server interface.
|
||||
func (compo *InlineCompo) Serve(c Context) {
|
||||
func (compo InlineCompo) Serve(c Context) {
|
||||
for u := range c.Input() {
|
||||
compo.OnOneUpdate(c, u)
|
||||
}
|
||||
}
|
||||
|
||||
func (compo *InlineCompo) OnOneUpdate(c Context, u Update) error {
|
||||
func (compo *InlineCompo) OnOneUpdate(c Context, u Update) {
|
||||
var act Action
|
||||
btns := compo.ButtonMap()
|
||||
cb := tgbotapi.NewCallback(
|
||||
|
@ -113,23 +106,20 @@ func (compo *InlineCompo) OnOneUpdate(c Context, u Update) error {
|
|||
)
|
||||
data := u.CallbackQuery.Data
|
||||
|
||||
_, err := c.Bot().API().Request(cb)
|
||||
_, err := c.Bot.Api.Request(cb)
|
||||
if err != nil {
|
||||
return err
|
||||
return
|
||||
}
|
||||
|
||||
btn, ok := btns[data]
|
||||
if !ok {
|
||||
return nil
|
||||
return
|
||||
}
|
||||
|
||||
if btn.Action != nil {
|
||||
if btn != nil {
|
||||
act = btn.Action
|
||||
} else if compo.Action != nil {
|
||||
act = compo.Action
|
||||
}
|
||||
c.WithUpdate(u).Run(act)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ type InvoiceCompo struct {
|
|||
}
|
||||
|
||||
func (compo *InvoiceCompo) SendConfig(
|
||||
sid SessionID, bot *Bot,
|
||||
sid SessionId, bot *Bot,
|
||||
) (*SendConfig) {
|
||||
return nil
|
||||
}
|
||||
|
|
19
keyboard.go
19
keyboard.go
|
@ -10,11 +10,12 @@ type Keyboard struct {
|
|||
// defined action for the button.
|
||||
Action Action
|
||||
Rows []ButtonRow
|
||||
buttonMap ButtonMap
|
||||
}
|
||||
|
||||
// Returns the new keyboard with specified rows.
|
||||
func NewKeyboard(rows ...ButtonRow) Keyboard {
|
||||
ret := Keyboard{}
|
||||
ret := &Keyboard{}
|
||||
for _, row := range rows {
|
||||
if row != nil && len(row) > 0 {
|
||||
ret.Rows = append(ret.Rows, row)
|
||||
|
@ -40,10 +41,9 @@ func (kbd Keyboard) Row(btns ...Button) Keyboard {
|
|||
if len(btns) < 1 {
|
||||
return kbd
|
||||
}
|
||||
|
||||
retBtns := make([]Button, 0, len(btns))
|
||||
retBtns := []*Button{}
|
||||
for _, btn := range btns {
|
||||
if !btn.Valid {
|
||||
if btn == nil {
|
||||
continue
|
||||
}
|
||||
retBtns = append(retBtns, btn)
|
||||
|
@ -58,7 +58,7 @@ func (kbd Keyboard) Row(btns ...Button) Keyboard {
|
|||
// Adds buttons as one column list.
|
||||
func (kbd Keyboard) List(btns ...Button) Keyboard {
|
||||
for _, btn := range btns {
|
||||
if !btn.Valid {
|
||||
if btn == nil {
|
||||
continue
|
||||
}
|
||||
kbd.Rows = append(kbd.Rows, ButtonRow{btn})
|
||||
|
@ -76,7 +76,10 @@ func (kbd Keyboard) WithAction(a Action) Keyboard {
|
|||
// Returns the map of buttons. Where the key
|
||||
// is button data and the value is Action.
|
||||
func (kbd Keyboard) ButtonMap() ButtonMap {
|
||||
return kbd.MakeButtonMap()
|
||||
if kbd.buttonMap == nil {
|
||||
kbd.buttonMap = kbd.MakeButtonMap()
|
||||
}
|
||||
return kbd.buttonMap
|
||||
}
|
||||
|
||||
// Returns the map of buttons on the most fresh version of the keyboard.
|
||||
|
@ -87,6 +90,7 @@ func (kbd Keyboard) MakeButtonMap() ButtonMap {
|
|||
ret[vj.Key()] = vj
|
||||
}
|
||||
}
|
||||
kbd.buttonMap = ret
|
||||
|
||||
return ret
|
||||
}
|
||||
|
@ -99,9 +103,8 @@ func (kbd Keyboard) Inline() Inline {
|
|||
}
|
||||
|
||||
// Convert the keyboard to the more specific reply one.
|
||||
// By default OneTime = true.
|
||||
func (kbd Keyboard) Reply() Reply {
|
||||
ret := Reply{}
|
||||
ret := &Reply{}
|
||||
ret.Keyboard = kbd
|
||||
// it is used more often than not once.
|
||||
ret.OneTime = true
|
||||
|
|
16
location.go
16
location.go
|
@ -7,22 +7,22 @@ import (
|
|||
type Location = tgbotapi.Location
|
||||
|
||||
type LocationCompo struct {
|
||||
MessageCompo
|
||||
*MessageCompo
|
||||
Location
|
||||
}
|
||||
|
||||
func (compo *LocationCompo) SendConfig(
|
||||
sid SessionID, bot *Bot,
|
||||
) (SendConfig) {
|
||||
cid := sid.ToAPI()
|
||||
location := tgbotapi.NewLocation(
|
||||
sid SessionId, bot *Bot,
|
||||
) (*SendConfig) {
|
||||
cid := sid.ToApi()
|
||||
loc := tgbotapi.NewLocation(
|
||||
cid,
|
||||
compo.Latitude,
|
||||
compo.Longitude,
|
||||
)
|
||||
|
||||
ret := SendConfig{}
|
||||
ret.Chattable = location
|
||||
ret := &SendConfig{
|
||||
Location: &loc,
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
|
109
message.go
109
message.go
|
@ -10,13 +10,8 @@ type Message = tgbotapi.Message
|
|||
|
||||
// Simple text message component type.
|
||||
type MessageCompo struct {
|
||||
// Low level Message represents
|
||||
// the already sent to the client message.
|
||||
// Will be nil if the message is not rendered to the client.
|
||||
Message *Message
|
||||
// Parsing mode for the text: HTML, MD, MD2...
|
||||
Message Message
|
||||
ParseMode string
|
||||
// The text to display.
|
||||
Text string
|
||||
}
|
||||
|
||||
|
@ -34,121 +29,111 @@ func Escape2(str string) string {
|
|||
// Call the function after the message was sent.
|
||||
func (compo *MessageCompo) Update(c Context) error {
|
||||
edit := tgbotapi.NewEditMessageText(
|
||||
c.Session().ID.ToAPI(),
|
||||
c.Session.Id.ToApi(),
|
||||
compo.Message.MessageID,
|
||||
compo.Text,
|
||||
)
|
||||
msg, err := c.Bot().API().Send(edit)
|
||||
msg, err := c.bot.api.Send(edit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
compo.Message = &msg
|
||||
compo.Message = msg
|
||||
return nil
|
||||
}
|
||||
|
||||
// Calling the method removes the message on the client side
|
||||
// and sets the Message in the component to nil.
|
||||
func (compo *MessageCompo) Delete(c Context) error {
|
||||
cfg := tgbotapi.NewDeleteMessage(c.session.ID.ToAPI(), compo.Message.MessageID)
|
||||
_, err := c.Bot().API().Send(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Empty the message if success.
|
||||
compo.Message = nil
|
||||
|
||||
return nil
|
||||
func (compo *MessageCompo) Delete(c *Context) {
|
||||
cfg := tgbotapi.NewDeleteMessage(c.Session.Id.ToApi(), compo.Message.MessageID)
|
||||
c.Bot.Api.Send(cfg)
|
||||
//c.Sendf("%q", err)
|
||||
}
|
||||
|
||||
// Return new message with the specified text
|
||||
// formatted with the fmt.Sprintf function.
|
||||
func Messagef(format string, v ...any) *MessageCompo {
|
||||
ret := &MessageCompo{}
|
||||
// Is only implemented to make it sendable and so we can put it
|
||||
// return of rendering functions.
|
||||
func (compo *MessageCompo) SetMessage(msg Message) {
|
||||
compo.Message = msg
|
||||
}
|
||||
|
||||
// Return new message with the specified text.
|
||||
func Messagef(format string, v ...any) MessageCompo {
|
||||
ret := MessageCompo{}
|
||||
ret.Text = fmt.Sprintf(format, v...)
|
||||
ret.ParseMode = tgbotapi.ModeMarkdown
|
||||
return ret
|
||||
}
|
||||
|
||||
// Return message with the specified parse mode.
|
||||
func (compo *MessageCompo) setParseMode(mode string) *MessageCompo {
|
||||
compo.ParseMode = mode
|
||||
return compo
|
||||
func (msg MessageCompo) withParseMode(mode string) MessageCompo {
|
||||
msg.ParseMode = mode
|
||||
return msg
|
||||
}
|
||||
|
||||
// Set the default Markdown parsing mode.
|
||||
func (compo *MessageCompo) MD() *MessageCompo {
|
||||
return compo.setParseMode(tgbotapi.ModeMarkdown)
|
||||
func (msg MessageCompo) MD() MessageCompo {
|
||||
return msg.withParseMode(tgbotapi.ModeMarkdown)
|
||||
}
|
||||
|
||||
// Set the Markdown 2 parsing mode.
|
||||
func (compo *MessageCompo) MD2() *MessageCompo {
|
||||
return compo.setParseMode(tgbotapi.ModeMarkdownV2)
|
||||
func (msg MessageCompo) MD2() MessageCompo {
|
||||
return msg.withParseMode(tgbotapi.ModeMarkdownV2)
|
||||
}
|
||||
|
||||
// Set the HTML parsing mode.
|
||||
func (compo *MessageCompo) HTML() *MessageCompo {
|
||||
return compo.setParseMode(tgbotapi.ModeHTML)
|
||||
func (msg MessageCompo) HTML() MessageCompo {
|
||||
return msg.withParseMode(tgbotapi.ModeHTML)
|
||||
}
|
||||
|
||||
// Transform the message component into one with reply keyboard.
|
||||
func (compo *MessageCompo) Inline(inline Inline) *InlineCompo {
|
||||
return &InlineCompo{
|
||||
func (msg MessageCompo) Inline(inline Inline) InlineCompo {
|
||||
return InlineCompo{
|
||||
Inline: inline,
|
||||
MessageCompo: *compo,
|
||||
MessageCompo: msg,
|
||||
}
|
||||
}
|
||||
|
||||
// Transform the message component into one with reply keyboard.
|
||||
func (msg *MessageCompo) Reply(reply Reply) *ReplyCompo {
|
||||
return &ReplyCompo{
|
||||
func (msg MessageCompo) Reply(reply Reply) ReplyCompo {
|
||||
return ReplyCompo{
|
||||
Reply: reply,
|
||||
MessageCompo: *msg,
|
||||
MessageCompo: msg,
|
||||
}
|
||||
}
|
||||
|
||||
// Transform the message component into the location one.
|
||||
func (msg *MessageCompo) Location(
|
||||
func (msg MessageCompo) Location(
|
||||
lat, long float64,
|
||||
) *LocationCompo {
|
||||
ret := &LocationCompo{}
|
||||
ret.MessageCompo = *msg
|
||||
ret.Latitude = lat
|
||||
ret.Longitude = long
|
||||
|
||||
) LocationCompo {
|
||||
ret := &LocationCompo{
|
||||
MessageCompo: msg,
|
||||
Location: Location{
|
||||
Latitude: lat,
|
||||
Longitude: long,
|
||||
},
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
// Implementing the Sendable interface.
|
||||
func (compo *MessageCompo) SendConfig(
|
||||
sid SessionID, bot *Bot,
|
||||
func (config MessageCompo) SendConfig(
|
||||
sid SessionId, bot *Bot,
|
||||
) (SendConfig) {
|
||||
var (
|
||||
ret SendConfig
|
||||
text string
|
||||
)
|
||||
|
||||
// Protection against empty text,
|
||||
// since it breaks the Telegram bot API.
|
||||
if compo.Text == "" {
|
||||
if config.Text == "" {
|
||||
text = ">"
|
||||
} else {
|
||||
text = compo.Text
|
||||
text = config.Text
|
||||
}
|
||||
|
||||
msg := tgbotapi.NewMessage(sid.ToAPI(), text)
|
||||
msg.ParseMode = compo.ParseMode
|
||||
msg := tgbotapi.NewMessage(sid.ToApi(), text)
|
||||
msg.ParseMode = config.ParseMode
|
||||
ret.Chattable = msg
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
// Implementing the Sendable interface.
|
||||
// Also used for embedding for things like InlineCompo etc.
|
||||
func (compo *MessageCompo) SetMessage(msg *Message) {
|
||||
compo.Message = msg
|
||||
}
|
||||
|
||||
// Empty serving to use messages in rendering.
|
||||
func (compo *MessageCompo) Serve(c Context) {}
|
||||
|
||||
|
|
113
paged-panel.go
113
paged-panel.go
|
@ -1,113 +0,0 @@
|
|||
package tg
|
||||
|
||||
type PanelPager interface {
|
||||
GetPanelPage(
|
||||
panel *PanelPagerCompo,
|
||||
c Context, page, size int,
|
||||
) PanelPage
|
||||
}
|
||||
|
||||
type PanelPage struct {
|
||||
Next, Prev bool
|
||||
Rows []ButtonRow
|
||||
}
|
||||
|
||||
type PanelPagerFunc func(
|
||||
panel *PanelPagerCompo,
|
||||
c Context, page, size int,
|
||||
) PanelPage
|
||||
func (fn PanelPagerFunc) GetPanelPage(
|
||||
panel *PanelPagerCompo, c Context, page, size int,
|
||||
) PanelPage {
|
||||
return fn(panel, c, page, size)
|
||||
}
|
||||
|
||||
type PanelPagerCompo struct {
|
||||
PanelCompo
|
||||
page int
|
||||
size int
|
||||
nextFormat, prevFormat, delFormat string
|
||||
pager PanelPager
|
||||
}
|
||||
|
||||
func (compo *MessageCompo) PanelPager(
|
||||
c Context,
|
||||
startPage, size int,
|
||||
pager PanelPager,
|
||||
) (*PanelPagerCompo) {
|
||||
ret := &PanelPagerCompo{}
|
||||
ret.page = startPage
|
||||
ret.size = size
|
||||
ret.pager = pager
|
||||
ret.prevFormat = "<<<"
|
||||
ret.nextFormat = ">>>"
|
||||
ret.delFormat = "..."
|
||||
|
||||
ret.PanelCompo = (*compo.Panel(
|
||||
c, ret,
|
||||
))
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (panel *PanelPagerCompo) GetPanelRows(
|
||||
pcompo *PanelCompo, c Context,
|
||||
) []ButtonRow {
|
||||
page := panel.pager.GetPanelPage(
|
||||
panel, c, panel.page, panel.size,
|
||||
)
|
||||
|
||||
controlRow := ButtonRow{}
|
||||
|
||||
rows := page.Rows
|
||||
next := func(c Context){
|
||||
panel.page++
|
||||
panel.Update(c)
|
||||
}
|
||||
prev := func(c Context){
|
||||
panel.page--
|
||||
panel.Update(c)
|
||||
}
|
||||
|
||||
if page.Prev {
|
||||
if panel.delFormat != "" {
|
||||
rows = append(
|
||||
[]ButtonRow{
|
||||
ButtonRow{
|
||||
Buttonf(panel.delFormat).Rand().
|
||||
WithAction(Func(prev)),
|
||||
},
|
||||
},
|
||||
rows...,
|
||||
)
|
||||
}
|
||||
controlRow = append(
|
||||
controlRow,
|
||||
Buttonf(panel.prevFormat).Rand().
|
||||
WithAction(Func(prev)),
|
||||
)
|
||||
}
|
||||
|
||||
if page.Next {
|
||||
if panel.delFormat != "" {
|
||||
rows = append(
|
||||
rows,
|
||||
ButtonRow{
|
||||
Buttonf(panel.delFormat).Rand().
|
||||
WithAction(Func(next)),
|
||||
},
|
||||
)
|
||||
}
|
||||
controlRow = append(
|
||||
controlRow,
|
||||
Buttonf(panel.nextFormat).Rand().
|
||||
WithAction(Func(next)),
|
||||
)
|
||||
}
|
||||
|
||||
return append(
|
||||
rows,
|
||||
controlRow,
|
||||
)
|
||||
}
|
||||
|
43
panel.go
43
panel.go
|
@ -1,55 +1,40 @@
|
|||
package tg
|
||||
|
||||
// Using the interface and all related is
|
||||
// deprecated. Use the Paneler interface and function.
|
||||
type Rowser interface {
|
||||
MakeRows(c Context) []ButtonRow
|
||||
MakeRows(c *Context) []ButtonRow
|
||||
}
|
||||
|
||||
type RowserFunc func(c Context) []ButtonRow
|
||||
func (fn RowserFunc) MakeRows(c Context) []ButtonRow {
|
||||
type RowserFunc func(c *Context) []ButtonRow
|
||||
func (fn RowserFunc) MakeRows(c *Context) []ButtonRow {
|
||||
return fn(c)
|
||||
}
|
||||
|
||||
type Paneler interface {
|
||||
GetPanelRows(*PanelCompo, Context) []ButtonRow
|
||||
}
|
||||
|
||||
type PanelFunc func(*PanelCompo, Context) []ButtonRow
|
||||
func (fn PanelFunc) GetPanelRows(
|
||||
panel *PanelCompo, c Context,
|
||||
) []ButtonRow {
|
||||
return fn(panel, c)
|
||||
}
|
||||
|
||||
// The type represents the inline panel with
|
||||
// scrollable via buttons content.
|
||||
// Can be used for example to show users via SQL and offset
|
||||
// or something like that.
|
||||
type PanelCompo struct {
|
||||
InlineCompo
|
||||
Paneler Paneler
|
||||
*InlineCompo
|
||||
Rowser Rowser
|
||||
}
|
||||
|
||||
// Transform to the panel with dynamic rows.
|
||||
func (compo *MessageCompo) Panel(
|
||||
c Context, // The context to generate the first page of buttons.
|
||||
paneler Paneler, // The rows generator.
|
||||
c *Context, // The context that all the buttons will get.
|
||||
rowser Rowser, // The rows generator.
|
||||
) *PanelCompo {
|
||||
ret := &PanelCompo{}
|
||||
ret.Paneler = paneler
|
||||
|
||||
ret.InlineCompo = (*compo.Inline(
|
||||
ret.InlineCompo = compo.Inline(
|
||||
NewKeyboard(
|
||||
ret.Paneler.GetPanelRows(ret, c)...,
|
||||
rowser.MakeRows(c)...,
|
||||
).Inline(),
|
||||
))
|
||||
)
|
||||
ret.Rowser = rowser
|
||||
return ret
|
||||
}
|
||||
|
||||
// Implementing the Updater.
|
||||
func (panel *PanelCompo) Update(c Context) error {
|
||||
panel.Rows = panel.Paneler.GetPanelRows(panel, c)
|
||||
return panel.InlineCompo.Update(c)
|
||||
func (compo *PanelCompo) Update(c *Context) {
|
||||
compo.Rows = compo.Rowser.MakeRows(c)
|
||||
compo.InlineCompo.Update(c)
|
||||
}
|
||||
|
||||
|
|
35
reply.go
35
reply.go
|
@ -41,7 +41,7 @@ func (kbd Reply) ToApi() any {
|
|||
}
|
||||
buttons := []tgbotapi.KeyboardButton{}
|
||||
for _, button := range row {
|
||||
if !button.Valid {
|
||||
if button == nil {
|
||||
continue
|
||||
}
|
||||
buttons = append(buttons, button.ToTelegram())
|
||||
|
@ -63,21 +63,17 @@ type ReplyCompo struct {
|
|||
}
|
||||
|
||||
// Implementing the sendable interface.
|
||||
func (compo *ReplyCompo) SendConfig(
|
||||
sid SessionID, bot *Bot,
|
||||
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
|
||||
|
||||
sendConfig.Message.ReplyMarkup = compo.Reply.ToApi()
|
||||
return sendConfig
|
||||
}
|
||||
|
||||
// Implementing the Server interface.
|
||||
func (compo *ReplyCompo) Filter(
|
||||
u Update,
|
||||
func (compo ReplyCompo) Filter(
|
||||
u *Update,
|
||||
) bool {
|
||||
if compo == nil || u.Message == nil {
|
||||
return true
|
||||
|
@ -86,8 +82,8 @@ func (compo *ReplyCompo) Filter(
|
|||
_, ok := compo.ButtonMap()[u.Message.Text]
|
||||
if !ok {
|
||||
if u.Message.Location != nil {
|
||||
_, hasLocBtn := compo.ButtonMap().LocationButton()
|
||||
if !hasLocBtn {
|
||||
locBtn := compo.ButtonMap().LocationButton()
|
||||
if locBtn == nil {
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
|
@ -98,27 +94,22 @@ func (compo *ReplyCompo) Filter(
|
|||
}
|
||||
|
||||
// Implementing the UI interface.
|
||||
func (compo *ReplyCompo) Serve(c Context) {
|
||||
func (compo ReplyCompo) Serve(c *Context) {
|
||||
for u := range c.Input() {
|
||||
var btn Button
|
||||
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
|
||||
}
|
||||
btn = btns.LocationButton()
|
||||
}
|
||||
}
|
||||
|
||||
if !btn.Valid {
|
||||
continue
|
||||
if btn != nil {
|
||||
c.WithUpdate(u).Run(btn.Action)
|
||||
}
|
||||
|
||||
c.WithUpdate(u).Run(btn.Action)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
66
screen.go
66
screen.go
|
@ -1,32 +1,48 @@
|
|||
package tg
|
||||
|
||||
type WidgetSpecial int
|
||||
const (
|
||||
widgetEmpty WidgetSpecial = iota
|
||||
widgetBack
|
||||
import (
|
||||
"path"
|
||||
)
|
||||
|
||||
|
||||
func (w WidgetSpecial) Render(_ Context) UI {
|
||||
return nil
|
||||
// The type implements changing screen to the underlying ScreenId
|
||||
type ScreenGo struct {
|
||||
Path Path
|
||||
Args []any
|
||||
}
|
||||
|
||||
var (
|
||||
Back = Widget(widgetBack)
|
||||
)
|
||||
func (sc ScreenGo) Act(c *Context) {
|
||||
c.Go(sc.Path, sc.Args...)
|
||||
}
|
||||
|
||||
/*// Unique identifier for the screen.
|
||||
type Path int
|
||||
const (
|
||||
PathEmpty Path = 0
|
||||
// Going to the path returns
|
||||
// a context to the previous screen.
|
||||
PathBack Path = -1
|
||||
)
|
||||
// The same as Act.
|
||||
func (sc ScreenGo) Serve(c *Context) {
|
||||
sc.Act(c)
|
||||
}
|
||||
|
||||
// Unique identifier for the screen
|
||||
// and relative paths to the screen.
|
||||
type Path string
|
||||
|
||||
// Returns true if the path is empty.
|
||||
func (p Path) IsEmpty() bool {
|
||||
return p == 0
|
||||
return p == ""
|
||||
}
|
||||
|
||||
// Returns true if the path is absolute.
|
||||
func (p Path) IsAbs() bool {
|
||||
if len(p) == 0 {
|
||||
return false
|
||||
}
|
||||
return p[0] == '/'
|
||||
}
|
||||
|
||||
func (p Path) Dir() Path {
|
||||
return Path(path.Dir(string(p)))
|
||||
}
|
||||
|
||||
// Clean the path deleting exceed ., .. and / .
|
||||
func (p Path) Clean() Path {
|
||||
return Path(path.Clean(string(p)))
|
||||
}
|
||||
|
||||
// Screen statement of the bot.
|
||||
|
@ -48,10 +64,10 @@ type Node struct {
|
|||
Path Path
|
||||
Screen *Screen
|
||||
Subs []*Node
|
||||
}*/
|
||||
}
|
||||
|
||||
// Return new root node with the specified widget in the screen.
|
||||
/*func NewRootNode(widget Widget, subs ...*Node) *RootNode {
|
||||
func NewRootNode(widget Widget, subs ...*Node) *RootNode {
|
||||
ret := &RootNode{}
|
||||
ret.Screen = NewScreen(widget)
|
||||
ret.Subs = subs
|
||||
|
@ -98,13 +114,15 @@ func (n *Node) ScreenMap(root Path) ScreenMap {
|
|||
}
|
||||
}
|
||||
return m
|
||||
}*/
|
||||
}
|
||||
|
||||
// Map structure for the screens.
|
||||
type ScreenMap map[Path] *Screen
|
||||
|
||||
// Returns the new screen with specified name and widget.
|
||||
/*func NewScreen(widget Widget) *Screen {
|
||||
func NewScreen(widget Widget) *Screen {
|
||||
return &Screen{
|
||||
Widget: widget,
|
||||
}
|
||||
}*/
|
||||
}
|
||||
|
||||
|
|
6
send.go
6
send.go
|
@ -10,8 +10,8 @@ type MessageId int64
|
|||
// way to define what message will be
|
||||
// sent to the side of a user.
|
||||
type Sendable interface {
|
||||
SendConfig(SessionID, *Bot) (SendConfig)
|
||||
SetMessage(*Message)
|
||||
SendConfig(SessionId, *Bot) (SendConfig)
|
||||
SetMessage(Message)
|
||||
}
|
||||
|
||||
// The type is used as an endpoint to send messages
|
||||
|
@ -25,7 +25,7 @@ type SendConfig struct {
|
|||
type MessageMap map[string] *Message
|
||||
|
||||
// Convert to the bot.Api.Send format.
|
||||
func (config SendConfig) ToAPI() tgbotapi.Chattable {
|
||||
func (config SendConfig) ToApi() tgbotapi.Chattable {
|
||||
return config.Chattable
|
||||
}
|
||||
|
||||
|
|
|
@ -3,6 +3,6 @@ package tg
|
|||
// Implementing the interface provides
|
||||
// the way to define how to handle updates.
|
||||
type Server interface {
|
||||
Serve(Context)
|
||||
Serve(*Context)
|
||||
}
|
||||
|
||||
|
|
162
session.go
162
session.go
|
@ -2,15 +2,11 @@ package tg
|
|||
|
||||
// The type represents map of sessions using
|
||||
// as key.
|
||||
type SessionMap map[SessionID]*Session
|
||||
type SessionMap map[SessionId]*Session
|
||||
|
||||
// Add new empty session by it's ID.
|
||||
func (sm SessionMap) Add(
|
||||
bot *Bot,
|
||||
sid SessionID,
|
||||
scope SessionScope,
|
||||
) *Session {
|
||||
ret := NewSession(bot, sid, scope)
|
||||
func (sm SessionMap) Add(sid SessionId, scope SessionScope) *Session {
|
||||
ret := NewSession(sid, scope)
|
||||
sm[sid] = ret
|
||||
return ret
|
||||
}
|
||||
|
@ -27,37 +23,159 @@ const (
|
|||
|
||||
// Represents unique value to identify chats.
|
||||
// In fact is simply ID of the chat.
|
||||
type SessionID int64
|
||||
type SessionId int64
|
||||
|
||||
// Convert the SessionID to Telegram API's type.
|
||||
func (si SessionID) ToAPI() int64 {
|
||||
// Convert the SessionId to Telegram API's type.
|
||||
func (si SessionId) ToApi() int64 {
|
||||
return int64(si)
|
||||
}
|
||||
|
||||
// The type represents current state of
|
||||
// user interaction per each of them.
|
||||
type Session struct {
|
||||
// ID of the chat of the user.
|
||||
ID SessionID
|
||||
// Id of the chat of the user.
|
||||
Id SessionId
|
||||
Scope SessionScope
|
||||
// Custom value for each user.
|
||||
Data any
|
||||
|
||||
bot *Bot
|
||||
pathHistory []Widget
|
||||
pathHistory []Path
|
||||
skippedUpdates *UpdateChan
|
||||
updates *UpdateChan
|
||||
}
|
||||
|
||||
// Return new empty session.
|
||||
func NewSession(bot *Bot, id SessionID, scope SessionScope) *Session {
|
||||
ret := &Session{}
|
||||
ret.ID = id
|
||||
ret.Scope = scope
|
||||
ret.bot = bot
|
||||
ret.updates = NewUpdateChan()
|
||||
ret.skippedUpdates = NewUpdateChan()
|
||||
return ret
|
||||
// Return new empty session with specified user ID.
|
||||
func NewSession(id SessionId, scope SessionScope) *Session {
|
||||
return &Session{
|
||||
Id: id,
|
||||
Scope: scope,
|
||||
}
|
||||
}
|
||||
|
||||
// Changes screen of user to the Id one.
|
||||
func (s *Session) go_(pth Path, arg any) error {
|
||||
var err error
|
||||
if pth == "" {
|
||||
s.pathHistory = []Path{}
|
||||
return nil
|
||||
}
|
||||
var back bool
|
||||
if pth == "-" {
|
||||
if len(s.pathHistory) < 2 {
|
||||
return s.Go("")
|
||||
}
|
||||
pth = s.pathHistory[len(s.pathHistory)-2]
|
||||
s.pathHistory = s.pathHistory[:len(s.pathHistory)-1]
|
||||
}
|
||||
// Getting the screen and changing to
|
||||
// then executing its widget.
|
||||
if !pth.IsAbs() {
|
||||
pth = (s.Path() + "/" + pth).Clean()
|
||||
}
|
||||
|
||||
if !s.PathExist(pth) {
|
||||
return ScreenNotExistErr
|
||||
}
|
||||
|
||||
if !back && s.Path() != pth {
|
||||
s.pathHistory = append(s.pathHistory, pth)
|
||||
}
|
||||
|
||||
// Stopping the current widget.
|
||||
screen := s.bot.behaviour.Screens[pth]
|
||||
s.skippedUpdates.Close()
|
||||
|
||||
if screen.Widget != nil {
|
||||
s.skippedUpdates, err = s.runWidget(screen.Widget, arg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return NoWidgetForScreenErr
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Session) runCompo(compo Component, arg any) (*UpdateChan, error) {
|
||||
if compo == nil {
|
||||
return nil, nil
|
||||
}
|
||||
s, ok := compo.(Sendable)
|
||||
if ok {
|
||||
msg, err := c.Send(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.SetMessage(msg)
|
||||
}
|
||||
updates := NewUpdateChan()
|
||||
go func() {
|
||||
compo.Serve(
|
||||
c.WithInput(updates).
|
||||
WithArg(arg),
|
||||
)
|
||||
// To let widgets finish themselves before
|
||||
// the channel is closed and close it by themselves.
|
||||
updates.Close()
|
||||
}()
|
||||
return updates, nil
|
||||
}
|
||||
|
||||
// Run widget in background returning the new input channel for it.
|
||||
func (c *Context) runWidget(widget Widget, arg any) (*UpdateChan, error) {
|
||||
var err error
|
||||
if widget == nil {
|
||||
return nil, EmptyWidgetErr
|
||||
}
|
||||
|
||||
pth := c.Path()
|
||||
compos := widget.Render(c.WithArg(c.makeArg(args)))
|
||||
// Leave if changed path or components are empty.
|
||||
if compos == nil || pth != c.Path() {
|
||||
return nil, EmptyCompoErr
|
||||
}
|
||||
chns := make([]*UpdateChan, len(compos))
|
||||
for i, compo := range compos {
|
||||
chns[i], err = c.runCompo(compo, arg)
|
||||
if err != nil {
|
||||
for _, chn := range chns {
|
||||
chn.Close()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
ret := NewUpdateChan()
|
||||
go func() {
|
||||
ln := len(compos)
|
||||
UPDATE:
|
||||
for u := range ret.Chan() {
|
||||
if u == nil {
|
||||
break
|
||||
}
|
||||
cnt := 0
|
||||
for i, compo := range compos {
|
||||
chn := chns[i]
|
||||
if chn.Closed() {
|
||||
cnt++
|
||||
continue
|
||||
}
|
||||
if !compo.Filter(u) {
|
||||
chn.Send(u)
|
||||
continue UPDATE
|
||||
}
|
||||
}
|
||||
if cnt == ln {
|
||||
break
|
||||
}
|
||||
}
|
||||
ret.Close()
|
||||
for _, chn := range chns {
|
||||
chn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
|
6
taskfile.yml
Normal file
6
taskfile.yml
Normal file
|
@ -0,0 +1,6 @@
|
|||
version: 3
|
||||
|
||||
tasks:
|
||||
build:
|
||||
cmds:
|
||||
- go build -o testbot ./cmd/test/
|
6
ui.go
6
ui.go
|
@ -3,12 +3,12 @@ package tg
|
|||
// The type describes dynamic screen widget
|
||||
// That can have multiple UI components.
|
||||
type Widget interface {
|
||||
Render(Context) UI
|
||||
Render(*Context) UI
|
||||
}
|
||||
|
||||
// The way to describe custom function based Widgets.
|
||||
type RenderFunc func(c Context) UI
|
||||
func (fn RenderFunc) Render(c Context) UI {
|
||||
type RenderFunc func(c *Context) UI
|
||||
func (fn RenderFunc) Render(c *Context) UI {
|
||||
return fn(c)
|
||||
}
|
||||
|
||||
|
|
26
update.go
26
update.go
|
@ -2,6 +2,7 @@ package tg
|
|||
|
||||
import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
|
||||
type FileId string
|
||||
|
||||
type Update struct {
|
||||
tgbotapi.Update
|
||||
|
@ -15,18 +16,18 @@ type UpdateChan struct {
|
|||
// Return new update channel.
|
||||
func NewUpdateChan() *UpdateChan {
|
||||
ret := &UpdateChan{}
|
||||
ret.chn = make(chan Update)
|
||||
ret.chn = make(chan *Update)
|
||||
return ret
|
||||
}
|
||||
|
||||
|
||||
func (updates *UpdateChan) Chan() chan Update {
|
||||
func (updates *UpdateChan) Chan() chan *Update {
|
||||
return updates.chn
|
||||
}
|
||||
|
||||
// Send an update to the channel.
|
||||
// Returns true if the update was sent.
|
||||
func (updates *UpdateChan) Send(u Update) bool {
|
||||
func (updates *UpdateChan) Send(u *Update) bool {
|
||||
defer recover()
|
||||
if updates == nil || updates.chn == nil {
|
||||
return false
|
||||
|
@ -36,11 +37,11 @@ func (updates *UpdateChan) Send(u Update) bool {
|
|||
}
|
||||
|
||||
// Read an update from the channel.
|
||||
func (updates *UpdateChan) Read() (Update, bool) {
|
||||
func (updates *UpdateChan) Read() *Update {
|
||||
if updates == nil || updates.chn == nil {
|
||||
return Update{}, false
|
||||
return nil
|
||||
}
|
||||
return <-updates.chn, true
|
||||
return <-updates.chn
|
||||
}
|
||||
|
||||
// Returns true if the channel is closed.
|
||||
|
@ -59,12 +60,13 @@ func (updates *UpdateChan) Close() {
|
|||
}
|
||||
|
||||
func (u Update) HasDocument() bool {
|
||||
return u.Message != nil &&
|
||||
return u != nil &&
|
||||
u.Message != nil &&
|
||||
u.Message.Document != nil
|
||||
}
|
||||
|
||||
func (u Update) DocumentID() FileID {
|
||||
return FileID(u.Update.Message.Document.FileID)
|
||||
func (u Update) DocumentId() FileId {
|
||||
return FileId(u.Update.Message.Document.FileID)
|
||||
}
|
||||
|
||||
func (u *Update) DocumentName() string {
|
||||
|
@ -84,10 +86,10 @@ func (u Update) HasPhotos() bool {
|
|||
len(u.Message.Photo) != 0
|
||||
}
|
||||
|
||||
func (u Update) PhotoIDs() []FileID {
|
||||
ret := make([]FileID, len(u.Message.Photo))
|
||||
func (u Update) PhotoIds() []FileId {
|
||||
ret := make([]FileId, len(u.Message.Photo))
|
||||
for i, photo := range u.Message.Photo {
|
||||
ret[i] = FileID(photo.FileID)
|
||||
ret[i] = FileId(photo.FileID)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
package tg
|
||||
|
||||
// Implementing the type provides
|
||||
// way to update stuff on the client side.
|
||||
// Things like panels, messages etc.
|
||||
type Updater interface {
|
||||
Update(Context) error
|
||||
}
|
||||
|
Loading…
Reference in a new issue