tg

package
v0.0.0-...-32ec32e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2023 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ScreenNotExistErr    = errors.New("screen does not exist")
	SessionNotExistErr   = errors.New("session does not exist")
	KeyboardNotExistErr  = errors.New("keyboard does not exist")
	NotAvailableErr      = errors.New("the context is not available")
	EmptyKeyboardTextErr = errors.New("got empty text for a keyboard")
	ActionNotDefinedErr  = errors.New("action was not defined")
	MapCollisionErr      = errors.New("map collision occured")
	ContextNotExistErr   = errors.New("the context does not exist")
)
View Source
var (
	Init func()
)
View Source
var (
	NewRawMessage = tgbotapi.NewMessage
)
View Source
var (
	UnknownFileTypeErr = errors.New("unknown file type")
)

Functions

func DefineAction

func DefineAction(typeName string, a Action) error

Define interface to make it marshalable to JSON etc. Like in GOB. Must be done both on client and server if one is provided.

func Escape2

func Escape2(str string) string

Escape special characters in Markdown 2 and return the resulting string.

Types

type Action

type Action interface {
	Act(*Context)
}

Customized actions for the bot.

type ActionFunc

type ActionFunc func(*Context)

func (ActionFunc) Act

func (af ActionFunc) Act(c *Context)

type Behaviour

type Behaviour struct {
	Root    Component
	Init    Action
	Screens ScreenMap
}

The type describes behaviour for the bot in personal chats.

func NewBehaviour

func NewBehaviour() *Behaviour

Returns new empty behaviour.

func (*Behaviour) GetScreen

func (beh *Behaviour) GetScreen(pth Path) *Screen

Returns the screen by it's ID.

func (*Behaviour) PathExist

func (beh *Behaviour) PathExist(pth Path) bool

Check whether the screen exists in the behaviour.

func (*Behaviour) WithInit

func (b *Behaviour) WithInit(a Action) *Behaviour

The Action will be called on session creation, not when starting or restarting the bot with the Start Action.

func (*Behaviour) WithInitFunc

func (b *Behaviour) WithInitFunc(
	fn ActionFunc,
) *Behaviour

Alias to WithInit to simplify behaviour definitions.

func (*Behaviour) WithRoot

func (b *Behaviour) WithRoot(root Component) *Behaviour

The function sets as the standard root widget CommandWidget and its commands..

func (*Behaviour) WithRootNode

func (b *Behaviour) WithRootNode(node *RootNode) *Behaviour

type Bot

type Bot struct {
	// Custom data value.
	Data any
	Api  *tgbotapi.BotAPI
	Me   *User
	// contains filtered or unexported fields
}

The wrapper around Telegram API.

func NewBot

func NewBot(token string) (*Bot, error)

Return the new bot with empty sessions and behaviour.

func (*Bot) Debug

func (bot *Bot) Debug(debug bool) *Bot

func (*Bot) DeleteCommands

func (bot *Bot) DeleteCommands()

func (*Bot) GetSession

func (bot *Bot) GetSession(
	sid SessionId,
) (*Session, bool)

Get session by its ID. Can be used for any scope including private, group and channel.

func (*Bot) Run

func (bot *Bot) Run() error

Run the bot with the Behaviour.

func (*Bot) Send

func (bot *Bot) Send(
	sid SessionId, v Sendable,
) (*Message, error)

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.

func (*Bot) SendRaw

func (bot *Bot) SendRaw(
	sid SessionId, v tgbotapi.Chattable,
) (*Message, error)

Send to the session specified its ID raw chattable from the tgbotapi.

func (*Bot) SetCommands

func (bot *Bot) SetCommands(
	scope tgbotapi.BotCommandScope,
	cmdMap CommandMap,
) error

Setting the command on the user side.

func (*Bot) WithBehaviour

func (b *Bot) WithBehaviour(beh *Behaviour) *Bot

func (*Bot) WithSessions

func (b *Bot) WithSessions(sessions SessionMap) *Bot

type Button

type Button struct {
	Text         string
	Data         string
	Url          string
	SendLocation bool
	Action       Action
}

The type wraps Telegram API's button to provide Action functionality.

func NewButton

func NewButton(text string) *Button

Returns new button with the specified text and no action.

func (*Button) ActionFunc

func (btn *Button) ActionFunc(fn ActionFunc) *Button

func (*Button) Go

func (btn *Button) Go(pth Path, args ...any) *Button

func (*Button) Key

func (btn *Button) Key() string

Return the key of the button to identify it by messages and callbacks.

func (*Button) ToTelegram

func (btn *Button) ToTelegram() apix.KeyboardButton

func (*Button) ToTelegramInline

func (btn *Button) ToTelegramInline() apix.InlineKeyboardButton

func (*Button) WithAction

func (btn *Button) WithAction(a Action) *Button

Set the action when pressing the button. By default is nil and does nothing.

func (*Button) WithData

func (btn *Button) WithData(dat string) *Button

func (*Button) WithSendLocation

func (btn *Button) WithSendLocation(ok bool) *Button

Sets whether the button must send owner's location.

func (*Button) WithUrl

func (btn *Button) WithUrl(url string) *Button

Set the URL for the button. Only for inline buttons.

type ButtonMap

type ButtonMap map[string]*Button

func (ButtonMap) LocationButton

func (btnMap ButtonMap) LocationButton() *Button

Returns the only location button in the map.

type ButtonRow

type ButtonRow []*Button

Represents the reply button row.

func NewButtonRow

func NewButtonRow(btns ...*Button) ButtonRow

type CC

type CC = ChannelContext

type ChannelAction

type ChannelAction struct {
	Act (*ChannelContext)
}

type ChannelContext

type ChannelContext struct {
}

The argument for handling in channenl behaviours.

type Chat

type Chat = tgbotapi.Chat

type Command

type Command struct {
	Name        CommandName
	Type        CommandType
	Description string
	Action      Action
	Widget      Widget
}

func NewCommand

func NewCommand(name CommandName, desc string) *Command

func (*Command) ActionFunc

func (c *Command) ActionFunc(af ActionFunc) *Command

func (*Command) Go

func (c *Command) Go(pth Path, args ...any) *Command

func (*Command) ToApi

func (c *Command) ToApi() tgbotapi.BotCommand

func (*Command) WidgetFunc

func (c *Command) WidgetFunc(fn Func) *Command

func (*Command) WithAction

func (c *Command) WithAction(a Action) *Command

func (*Command) WithWidget

func (c *Command) WithWidget(w Widget) *Command

type CommandCompo

type CommandCompo struct {
	PreStart Action
	Commands CommandMap
	Usage    Action
}

The type is used to recognize commands and execute its actions and widgets .

func NewCommandCompo

func NewCommandCompo(cmds ...*Command) *CommandCompo

Returns new empty CommandCompo.

func (*CommandCompo) Filter

func (widget *CommandCompo) Filter(
	u *Update,
) bool

func (*CommandCompo) Serve

func (compo *CommandCompo) Serve(c *Context)

Implementing server.

func (*CommandCompo) WithCommands

func (w *CommandCompo) WithCommands(cmds ...*Command) *CommandCompo

Set the commands to handle.

func (*CommandCompo) WithPreStart

func (w *CommandCompo) WithPreStart(a Action) *CommandCompo

Set the prestart action.

func (*CommandCompo) WithPreStartFunc

func (w *CommandCompo) WithPreStartFunc(fn ActionFunc) *CommandCompo

Set the prestart action with function.

func (*CommandCompo) WithUsage

func (w *CommandCompo) WithUsage(a Action) *CommandCompo

Set the usage action.

func (*CommandCompo) WithUsageFunc

func (w *CommandCompo) WithUsageFunc(fn ActionFunc) *CommandCompo

Set the usage action with function.

type CommandMap

type CommandMap map[CommandName]*Command

type CommandName

type CommandName string

type CommandType

type CommandType uint8
const (
	PrivateCommandType CommandType = iota
	GroupCommandType
	ChannelCommandType
)

type Component

type Component interface {
	Filterer
	Server
}

The type describes interfaces needed to be implemented to be endpoint handlers.

type Context

type Context struct {

	// The update that called the Context usage.
	*Update
	// contains filtered or unexported fields
}

Interface to interact with the user.

func (*Context) Arg

func (c *Context) Arg() any

func (*Context) Copy

func (c *Context) Copy() *Context

Returns copy of current context so it will not affect the current one. But be careful because most of the insides uses pointers which are not deeply copied.

func (*Context) Go

func (c *Context) Go(pth Path, args ...any)

Changes screen of user to the Id one.

func (*Context) History

func (c *Context) History() []Path

func (*Context) Input

func (c *Context) Input() chan *Update

Get the input for current widget. Should be used inside handlers (aka "Serve").

func (*Context) Path

func (c *Context) Path() Path

func (*Context) PathExist

func (c *Context) PathExist(pth Path) bool

func (*Context) ReadString

func (c *Context) ReadString(pref string, args ...any) string

Simple way to read strings for widgets.

func (*Context) Run

func (c *Context) Run(a Action)

func (*Context) RunCompo

func (c *Context) RunCompo(compo Component, args ...any) *UpdateChan

func (*Context) RunWidget

func (c *Context) RunWidget(widget Widget, args ...any) *UpdateChan

Run widget in background returning the new input channel for it.

func (*Context) Send

func (c *Context) Send(v Sendable) (*Message, error)

Sends to the Sendable object.

func (*Context) Sendf

func (c *Context) Sendf(format string, v ...any) (*Message, error)

Sends the formatted with fmt.Sprintf message to the user using default Markdown parsing format.

func (*Context) Sendf2

func (c *Context) Sendf2(format string, v ...any) (*Message, error)

Same as Sendf but uses Markdown 2 format for parsing.

func (*Context) SendfHTML

func (c *Context) SendfHTML(format string, v ...any) (*Message, error)

Same as Sendf but uses HTML format for parsing.

func (*Context) Skip

func (c *Context) Skip(u *Update)

Only for the root widget usage. Skip the update sending it down to the underlying widget.

func (*Context) WithArg

func (c *Context) WithArg(v any) *Context

func (*Context) WithInput

func (c *Context) WithInput(input *UpdateChan) *Context

func (*Context) WithUpdate

func (c *Context) WithUpdate(u *Update) *Context

type ContextType

type ContextType uint8
const (
	NoContextType ContextType = iota
	WidgetContextType
	ActionContextType
)

type Errorer

type Errorer interface {
	Err() error
}

type File

type File struct {
	*MessageCompo
	// contains filtered or unexported fields
}

func NewFile

func NewFile(path string) *File

func (*File) Caption

func (f *File) Caption(caption string) *File

func (*File) Image

func (f *File) Image() *File

func (*File) NeedsUpload

func (f *File) NeedsUpload() bool

func (*File) SendConfig

func (f *File) SendConfig(
	sid SessionId, bot *Bot,
) *SendConfig

func (*File) SendData

func (f *File) SendData() string

func (*File) Type

func (f *File) Type() FileType

func (*File) UploadData

func (f *File) UploadData() (string, io.Reader, error)

type FileType

type FileType int
const (
	NoFileType FileType = iota
	ImageFileType
)

type FilterFunc

type FilterFunc func(*Update) bool

func (FilterFunc) Filter

func (f FilterFunc) Filter(
	u *Update,
) bool

type Filterer

type Filterer interface {
	// Return true if should filter the update
	// and not send it inside the widget.
	Filter(*Update) bool
}

Implementing the interface provides way to know exactly what kind of updates the widget needs.

type Func

type Func func(*Context)

General type function to define actions, single component widgets and components themselves.

func (Func) Act

func (f Func) Act(c *Context)

func (Func) Filter

func (f Func) Filter(_ *Update) bool

func (Func) Render

func (f Func) Render(_ *Context) UI

func (Func) Serve

func (f Func) Serve(c *Context)

type Inline

type Inline struct {
	*Keyboard
}

The type represents keyboard to be emdedded into the messages (inline in Telegram terms).

func (*Inline) ToApi

func (kbd *Inline) ToApi() tgbotapi.InlineKeyboardMarkup

Convert the inline keyboard to markup for the tgbotapi.

type InlineCompo

type InlineCompo struct {
	*MessageCompo
	*Inline
}

The type implements message with an inline keyboard.

func (*InlineCompo) Filter

func (compo *InlineCompo) Filter(u *Update) bool

Implementing the Filterer interface.

func (*InlineCompo) SendConfig

func (compo *InlineCompo) SendConfig(
	sid SessionId, bot *Bot,
) *SendConfig

Implementing the Sendable interface.

func (*InlineCompo) Serve

func (widget *InlineCompo) Serve(c *Context)

Implementing the Server interface.

func (*InlineCompo) Update

func (compo *InlineCompo) Update(c *Context)

type InvoiceCompo

type InvoiceCompo struct {
	*MessageCompo
	tgbotapi.InvoiceConfig
}

func (*InvoiceCompo) SendConfig

func (compo *InvoiceCompo) SendConfig(
	sid SessionId, bot *Bot,
) *SendConfig

type Keyboard

type Keyboard struct {
	// The action is called if there is no
	// defined action for the button.
	Action Action
	Rows   []ButtonRow
	// contains filtered or unexported fields
}

The general keyboard type used both in Reply and Inline.

func NewKeyboard

func NewKeyboard(rows ...ButtonRow) *Keyboard

Returns the new keyboard with specified rows.

func (*Keyboard) ActionFunc

func (kbd *Keyboard) ActionFunc(fn ActionFunc) *Keyboard

Alias to WithAction but better typing when setting a specific function

func (Keyboard) ButtonMap

func (kbd Keyboard) ButtonMap() ButtonMap

Returns the map of buttons. Used to define the Action.

func (*Keyboard) Inline

func (kbd *Keyboard) Inline() *Inline

Convert the keyboard to the more specific inline one.

func (*Keyboard) List

func (kbd *Keyboard) List(btns ...*Button) *Keyboard

Adds buttons as one column list.

func (*Keyboard) Reply

func (kbd *Keyboard) Reply() *Reply

Convert the keyboard to the more specific reply one.

func (*Keyboard) Row

func (kbd *Keyboard) Row(btns ...*Button) *Keyboard

Adds a new button row to the current keyboard.

func (*Keyboard) WithAction

func (kbd *Keyboard) WithAction(a Action) *Keyboard

Set the default action when no button provides key to the data we got.

type Location

type Location = tgbotapi.Location

type LocationCompo

type LocationCompo struct {
	*MessageCompo
	Location
}

func (*LocationCompo) SendConfig

func (compo *LocationCompo) SendConfig(
	sid SessionId, bot *Bot,
) *SendConfig

type Maker

type Maker[V any] interface {
	Make(*Context) V
}

type Message

type Message = tgbotapi.Message

type MessageCompo

type MessageCompo struct {
	Message   *Message
	ParseMode string
	Text      string
}

Simple text message component type.

func NewMessage

func NewMessage(text string) *MessageCompo

Return new message with the specified text.

func (*MessageCompo) Filter

func (compo *MessageCompo) Filter(_ *Update) bool

Filter that skips everything. Messages cannot do anything with updates.

func (*MessageCompo) HTML

func (msg *MessageCompo) HTML() *MessageCompo

Set the HTML parsing mode.

func (*MessageCompo) Inline

func (msg *MessageCompo) Inline(inline *Inline) *InlineCompo

Transform the message component into one with reply keyboard.

func (*MessageCompo) Location

func (msg *MessageCompo) Location(
	lat, long float64,
) *LocationCompo

Transform the message component into the location one.

func (*MessageCompo) MD

func (msg *MessageCompo) MD() *MessageCompo

Set the default Markdown parsing mode.

func (*MessageCompo) MD2

func (msg *MessageCompo) MD2() *MessageCompo

Set the Markdown 2 parsing mode.

func (*MessageCompo) Reply

func (msg *MessageCompo) Reply(reply *Reply) *ReplyCompo

Transform the message component into one with reply keyboard.

func (*MessageCompo) SendConfig

func (config *MessageCompo) SendConfig(
	sid SessionId, bot *Bot,
) *SendConfig

Implementing the Sendable interface.

func (*MessageCompo) Serve

func (compo *MessageCompo) Serve(c *Context)

Empty serving to use messages in rendering.

func (*MessageCompo) SetMessage

func (compo *MessageCompo) SetMessage(msg *Message)

Is only implemented to make it sendable and so we can put it return of rendering functions.

func (*MessageCompo) Update

func (compo *MessageCompo) Update(c *Context)

type MessageId

type MessageId int64

type MessageMap

type MessageMap map[string]*Message

type Node

type Node struct {
	Path   Path
	Screen *Screen
	Subs   []*Node
}

The node is a simple way to represent tree-like structured applications.

func NewNode

func NewNode(relPath Path, widget Widget, subs ...*Node) *Node

func (*Node) ScreenMap

func (n *Node) ScreenMap(root Path) ScreenMap

type Path

type Path string

Unique identifier for the screen and relative paths to the screen.

func (Path) Clean

func (p Path) Clean() Path

Clean the path deleting exceed ., .. and / .

func (Path) Dir

func (p Path) Dir() Path

func (Path) IsAbs

func (p Path) IsAbs() bool

Returns true if the path is absolute.

func (Path) IsEmpty

func (p Path) IsEmpty() bool

Returns true if the path is empty.

type PhotoConfig

type PhotoConfig = tgbotapi.PhotoConfig

type Poll

type Poll struct {
}

type PollCompo

type PollCompo struct {
}

type RenderFunc

type RenderFunc func(c *Context) UI

The way to describe custom function based Widgets.

func (RenderFunc) Render

func (fn RenderFunc) Render(c *Context) UI

type Reply

type Reply struct {
	*Keyboard
	// If true will be removed after one press.
	OneTime bool
	// If true will remove the keyboard on send.
	Remove bool
}

The type represents reply keyboards.

func (*Reply) ToApi

func (kbd *Reply) ToApi() any

Convert the Keyboard to the Telegram API type of reply keyboard.

func (*Reply) WithOneTime

func (kbd *Reply) WithOneTime(oneTime bool) *Reply

Set if the keyboard should be hidden after one of buttons is pressede.

func (*Reply) WithRemove

func (kbd *Reply) WithRemove(remove bool) *Reply

Set if we should remove current keyboard on the user side when sending the keyboard.

type ReplyCompo

type ReplyCompo struct {
	*MessageCompo
	*Reply
}

The type implements reply keyboard widget.

func (*ReplyCompo) Filter

func (compo *ReplyCompo) Filter(
	u *Update,
) bool

func (*ReplyCompo) SendConfig

func (compo *ReplyCompo) SendConfig(
	sid SessionId, bot *Bot,
) *SendConfig

Implementing the sendable interface.

func (*ReplyCompo) Serve

func (compo *ReplyCompo) Serve(c *Context)

Implementing the UI interface.

type RootNode

type RootNode struct {
	Screen *Screen
	Subs   []*Node
}

The first node with the "/" path.

func NewRootNode

func NewRootNode(widget Widget, subs ...*Node) *RootNode

Return new root node with the specified widget in the screen.

func (*RootNode) ScreenMap

func (n *RootNode) ScreenMap() ScreenMap

type Screen

type Screen struct {
	// The widget to run when reaching the screen.
	Widget Widget
}

Screen statement of the bot. Mostly what buttons to show.

func NewScreen

func NewScreen(widget Widget) *Screen

Returns the new screen with specified name and widget.

type ScreenGo

type ScreenGo struct {
	Path Path
	Args []any
}

The type implements changing screen to the underlying ScreenId

func (ScreenGo) Act

func (sc ScreenGo) Act(c *Context)

func (ScreenGo) Serve

func (sc ScreenGo) Serve(c *Context)

The same as Act.

type ScreenMap

type ScreenMap map[Path]*Screen

Map structure for the screens.

type SendConfig

type SendConfig struct {
	// The name will be used to store
	// the message in the map.
	Name string
	// Message with text and keyboard.
	Message *tgbotapi.MessageConfig

	// The image to be sent.
	Image    *tgbotapi.PhotoConfig
	Location *tgbotapi.LocationConfig
	Error    error
}

The type is used as an endpoint to send messages via bot.Send .

func (*SendConfig) ToApi

func (config *SendConfig) ToApi() tgbotapi.Chattable

Convert to the bot.Api.Send format.

func (*SendConfig) WithName

func (cfg *SendConfig) WithName(name string) *SendConfig

type Sendable

type Sendable interface {
	SendConfig(SessionId, *Bot) *SendConfig
	SetMessage(*Message)
}

Implementing the interface provides way to define what message will be sent to the side of a user.

type Server

type Server interface {
	Serve(*Context)
}

Implementing the interface provides the way to define how to handle updates.

type Session

type Session struct {
	// Id of the chat of the user.
	Id    SessionId
	Scope SessionScope
	// Custom value for each user.
	Data any
}

The type represents current state of user interaction per each of them.

func NewSession

func NewSession(id SessionId, scope SessionScope) *Session

Return new empty session with specified user ID.

type SessionId

type SessionId int64

Represents unique value to identify chats. In fact is simply ID of the chat.

func (SessionId) ToApi

func (si SessionId) ToApi() int64

Convert the SessionId to Telegram API's type.

type SessionMap

type SessionMap map[SessionId]*Session

The type represents map of sessions using as key.

func (SessionMap) Add

func (sm SessionMap) Add(sid SessionId, scope SessionScope) *Session

Add new empty session by it's ID.

type SessionScope

type SessionScope uint8

The way to determine where the context is related to.

const (
	NoSessionScope SessionScope = iota
	PrivateSessionScope
	GroupSessionScope
	ChannelSessionScope
)

type UI

type UI []Component

The type that represents endpoint user interface via set of components that will work on the same screen in the same time.

type Update

type Update = tgbotapi.Update

type UpdateChan

type UpdateChan struct {
	// contains filtered or unexported fields
}

The type represents general update channel.

func NewUpdateChan

func NewUpdateChan() *UpdateChan

Return new update channel.

func (*UpdateChan) Chan

func (updates *UpdateChan) Chan() chan *Update

func (*UpdateChan) Close

func (updates *UpdateChan) Close()

Close the channel. Used in defers.

func (*UpdateChan) Closed

func (updates *UpdateChan) Closed() bool

Returns true if the channel is closed.

func (*UpdateChan) Read

func (updates *UpdateChan) Read() *Update

Read an update from the channel.

func (*UpdateChan) Send

func (updates *UpdateChan) Send(u *Update) bool

Send an update to the channel. Returns true if the update was sent.

type User

type User = tgbotapi.User

type Widget

type Widget interface {
	Render(*Context) UI
}

The type describes dynamic screen widget That can have multiple UI components.

type WrongUpdateType

type WrongUpdateType struct {
	Type string
}

func (WrongUpdateType) Error

func (wut WrongUpdateType) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL