Documentation ¶
Overview ¶
Package telemux is a flexible message router add-on for "go-telegram-bot-api".
Make sure to check "go-telegram-bot-api" documentation first: https://github.com/go-telegram-bot-api/telegram-bot-api/v5
Index ¶
- type ConversationPersistence
- type Data
- type FilePersistence
- type FilterFunc
- func And(filters ...FilterFunc) FilterFunc
- func Any() FilterFunc
- func HasAnimation() FilterFunc
- func HasAudio() FilterFunc
- func HasContact() FilterFunc
- func HasDocument() FilterFunc
- func HasLocation() FilterFunc
- func HasPhoto() FilterFunc
- func HasRegex(pattern string) FilterFunc
- func HasSticker() FilterFunc
- func HasText() FilterFunc
- func HasVenue() FilterFunc
- func HasVideo() FilterFunc
- func HasVideoNote() FilterFunc
- func HasVoice() FilterFunc
- func IsAnyCommandMessage() FilterFunc
- func IsCallbackQuery() FilterFunc
- func IsChannel() FilterFunc
- func IsChannelPost() FilterFunc
- func IsCommandMessage(cmd string) FilterFunc
- func IsEditedChannelPost() FilterFunc
- func IsEditedMessage() FilterFunc
- func IsGroup() FilterFunc
- func IsGroupOrSuperGroup() FilterFunc
- func IsInlineQuery() FilterFunc
- func IsLeftChatMember() FilterFunc
- func IsMessage() FilterFunc
- func IsNewChatMembers() FilterFunc
- func IsPrivate() FilterFunc
- func IsSuperGroup() FilterFunc
- func Not(filter FilterFunc) FilterFunc
- func Or(filters ...FilterFunc) FilterFunc
- type HandleFunc
- type Handler
- func NewCallbackQueryHandler(pattern string, filter FilterFunc, handles ...HandleFunc) *Handler
- func NewChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewCommandHandler(command string, filter FilterFunc, handles ...HandleFunc) *Handler
- func NewConversationHandler(conversationID string, persistence ConversationPersistence, states StateMap, ...) *Handler
- func NewEditedChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewEditedMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewInlineQueryHandler(pattern string, filter FilterFunc, handles ...HandleFunc) *Handler
- func NewMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewRegexHandler(pattern string, filter FilterFunc, handles ...HandleFunc) *Handler
- type LocalPersistence
- type Map
- type Mux
- func (m *Mux) AddHandler(handlers ...*Handler) *Mux
- func (m *Mux) AddMux(others ...*Mux) *Mux
- func (m *Mux) Dispatch(bot *tgbotapi.BotAPI, u tgbotapi.Update) bool
- func (m *Mux) Process(u *Update) bool
- func (m *Mux) SetGlobalFilter(filter FilterFunc) *Mux
- func (m *Mux) SetRecover(recover RecoverFunc) *Mux
- type PersistenceContext
- type PersistenceKey
- type Processor
- type RecoverFunc
- type StateMap
- type Update
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ConversationPersistence ¶
type ConversationPersistence interface { // GetState & SetState tell conversation handlers how to retrieve & set conversation state. GetState(pk PersistenceKey) string SetState(pk PersistenceKey, state string) // GetConversationData & SetConversationData allow conversation handlers to store intermediate data. GetData(pk PersistenceKey) Data SetData(pk PersistenceKey, data Data) }
ConversationPersistence interface tells conversation where to store & how to retrieve the current state of the conversation, i. e. which "step" the given user is currently at.
type FilePersistence ¶
type FilePersistence struct { Filename string // contains filtered or unexported fields }
FilePersistence is an implementation of Persistence. It stores conversation states & conversation data in file.
func NewFilePersistence ¶
func NewFilePersistence(filename string) *FilePersistence
NewFilePersistence creates new instance of FilePersistence.
func (*FilePersistence) GetData ¶
func (p *FilePersistence) GetData(pk PersistenceKey) Data
GetData reads conversation data from file
func (*FilePersistence) GetState ¶
func (p *FilePersistence) GetState(pk PersistenceKey) string
GetState reads conversation state from file
func (*FilePersistence) SetData ¶
func (p *FilePersistence) SetData(pk PersistenceKey, data Data)
SetData writes conversation data to file
func (*FilePersistence) SetState ¶
func (p *FilePersistence) SetState(pk PersistenceKey, state string)
SetState writes conversation state to file
type FilterFunc ¶
FilterFunc is used to check if this update should be processed by handler.
func And ¶
func And(filters ...FilterFunc) FilterFunc
And filters updates that pass ALL of the provided filters.
func HasAnimation ¶
func HasAnimation() FilterFunc
HasAnimation filters updates that contain an animation.
func HasDocument ¶
func HasDocument() FilterFunc
HasDocument filters updates that contain a document.
func HasLocation ¶
func HasLocation() FilterFunc
HasLocation filters updates that contain a location.
func HasRegex ¶
func HasRegex(pattern string) FilterFunc
HasRegex filters updates that match a regular expression. For example, HasRegex("^/get_(\d+)$") will handle commands like "/get_42".
func HasText ¶
func HasText() FilterFunc
HasText filters updates that look like text, i. e. have some text and do not start with a slash ("/").
func HasVideoNote ¶
func HasVideoNote() FilterFunc
HasVideoNote filters updates that contain a video note.
func IsAnyCommandMessage ¶
func IsAnyCommandMessage() FilterFunc
IsAnyCommandMessage filters updates that contain a message and look like a command, i. e. have some text and start with a slash ("/"). If command contains bot username, it is also checked.
func IsCallbackQuery ¶
func IsCallbackQuery() FilterFunc
IsCallbackQuery filters updates that are callbacks from button presses.
func IsChannelPost ¶
func IsChannelPost() FilterFunc
IsChannelPost filters updates that are channel posts.
func IsCommandMessage ¶
func IsCommandMessage(cmd string) FilterFunc
IsCommandMessage filters updates that contain a specific command. For example, IsCommandMessage("start") will handle a "/start" command. This will also allow the user to pass arguments, e. g. "/start foo bar". Commands in format "/start@bot_name" and "/start@bot_name foo bar" are also supported. If command contains bot username, it is also checked.
func IsEditedChannelPost ¶
func IsEditedChannelPost() FilterFunc
IsEditedChannelPost filters updates that are edits to existing channel posts.
func IsEditedMessage ¶
func IsEditedMessage() FilterFunc
IsEditedMessage filters updates that are edits to existing messages.
func IsGroup ¶
func IsGroup() FilterFunc
IsGroup filters updates that are sent in a group. See also IsGroupOrSuperGroup.
func IsGroupOrSuperGroup ¶
func IsGroupOrSuperGroup() FilterFunc
IsGroupOrSuperGroup filters updates that are sent in both groups and supergroups.
func IsInlineQuery ¶
func IsInlineQuery() FilterFunc
IsInlineQuery filters updates that are callbacks from inline queries.
func IsLeftChatMember ¶
func IsLeftChatMember() FilterFunc
IsLeftChatMember filters updates that have user in LeftChatMember property.
func IsMessage ¶
func IsMessage() FilterFunc
IsMessage filters updates that look like message (text, photo, location etc.)
func IsNewChatMembers ¶
func IsNewChatMembers() FilterFunc
IsNewChatMembers filters updates that have users in NewChatMembers property.
func IsPrivate ¶
func IsPrivate() FilterFunc
IsPrivate filters updates that are sent in private chats.
func IsSuperGroup ¶
func IsSuperGroup() FilterFunc
IsSuperGroup filters updates that are sent in a superbroup. See also IsGroupOrSuperGroup.
func Not ¶
func Not(filter FilterFunc) FilterFunc
Not filters updates that do not pass the provided filter.
func Or ¶
func Or(filters ...FilterFunc) FilterFunc
Or filters updates that pass ANY of the provided filters.
type Handler ¶
type Handler struct { Filter FilterFunc Handles []HandleFunc }
Handler defines a function that will handle updates that pass the filtering.
func NewCallbackQueryHandler ¶
func NewCallbackQueryHandler(pattern string, filter FilterFunc, handles ...HandleFunc) *Handler
NewCallbackQueryHandler creates a handler for updates that contain callback query which matches the pattern as regexp.
func NewChannelPostHandler ¶
func NewChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewChannelPostHandler creates a handler for updates that contain channel post.
func NewCommandHandler ¶
func NewCommandHandler(command string, filter FilterFunc, handles ...HandleFunc) *Handler
NewCommandHandler is an extension for NewMessageHandler that creates a handler for updates that contain message with command. It also populates u.Context["args"] with a slice of strings.
For example, when invoked as `/somecmd foo bar 1337`, u.Context["args"] will be set to []string{"foo", "bar", "1337"}
command can be a string (like "start" or "somecmd") or a space-delimited list of commands to accept (like "start somecmd othercmd")
Example ¶
package main import ( "fmt" "os" "strconv" tm "github.com/and3rson/telemux/v2" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) func main() { bot, _ := tgbotapi.NewBotAPI(os.Getenv("TG_TOKEN")) u := tgbotapi.NewUpdate(0) updates := bot.GetUpdatesChan(u) mux := tm.NewMux() mux.AddHandler(tm.NewCommandHandler( "add", nil, func(u *tm.Update) { args := u.Context["args"].([]string) if len(args) != 2 { bot.Send(tgbotapi.NewMessage( u.EffectiveChat().ID, "Wrong number of arguments. Example: /add 13 37"), ) return } a, err1 := strconv.Atoi(args[0]) b, err2 := strconv.Atoi(args[1]) if err1 != nil || err2 != nil { bot.Send(tgbotapi.NewMessage( u.EffectiveChat().ID, "Arguments must be numbers. Example: /add 13 37"), ) return } bot.Send(tgbotapi.NewMessage( u.EffectiveChat().ID, fmt.Sprintf("%d + %d = %d", a, b, a+b), )) }, )) for update := range updates { mux.Dispatch(bot, update) } }
Output:
func NewConversationHandler ¶
func NewConversationHandler( conversationID string, persistence ConversationPersistence, states StateMap, defaults []*Handler, ) *Handler
NewConversationHandler creates a conversation handler.
"conversationID" distinguishes this conversation from the others. The main goal of this identifier is to allow persistence to keep track of different conversation states independently without mixing them together.
"persistence" defines where to store conversation state & intermediate inputs from the user. Without persistence, a conversation would not be able to "remember" what "step" the user is at.
"states" define what handlers to use in which state. States are usually strings like "upload_photo", "send_confirmation", "wait_for_text" and describe the "step" the user is currently at. Empty string (`""`) should be used as an initial/final state (i. e. if the conversation has not started yet or has already finished.) For each state you must provide a slice with at least one Handler. If none of the handlers can handle the update, the default handlers are attempted (see below). In order to switch to a different state your Handler must call `u.PersistenceContext.SetState("STATE_NAME") ` replacing STATE_NAME with the name of the state you want to switch into. Conversation data can be accessed with `u.PersistenceContext.GetData()` and updated with `u.PersistenceContext.SetData(newData)`.
"defaults" are "appended" to every state except default state (`""`). They are useful to handle commands such as "/cancel" or to display some default message.
func NewEditedChannelPostHandler ¶
func NewEditedChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewEditedChannelPostHandler creates a handler for updates that contain edited channel post.
func NewEditedMessageHandler ¶
func NewEditedMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewEditedMessageHandler creates a handler for updates that contain edited message.
func NewHandler ¶
func NewHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewHandler creates a new generic handler.
func NewInlineQueryHandler ¶
func NewInlineQueryHandler(pattern string, filter FilterFunc, handles ...HandleFunc) *Handler
NewInlineQueryHandler creates a handler for updates that contain inline query which matches the pattern as regexp.
func NewMessageHandler ¶
func NewMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewMessageHandler creates a handler for updates that contain message.
func NewRegexHandler ¶
func NewRegexHandler(pattern string, filter FilterFunc, handles ...HandleFunc) *Handler
NewRegexHandler creates a handler for updates that contain message which matches the pattern as regexp.
type LocalPersistence ¶
type LocalPersistence struct { States map[PersistenceKey]string Data map[PersistenceKey]Data }
LocalPersistence is an implementation of Persistence. It stores conversation states & conversation data in memory.
All data in this implementation of persistence is lost if an application is restarted. If you want to store the data permanently you will need to implement your own Persistence which will use redis, database or something else to store states & conversation data.
func NewLocalPersistence ¶
func NewLocalPersistence() *LocalPersistence
NewLocalPersistence creates new instance of LocalPersistence.
func (*LocalPersistence) GetData ¶
func (p *LocalPersistence) GetData(pk PersistenceKey) Data
GetData returns conversation data from memory
func (*LocalPersistence) GetState ¶
func (p *LocalPersistence) GetState(pk PersistenceKey) string
GetState returns conversation state from memory
func (*LocalPersistence) SetData ¶
func (p *LocalPersistence) SetData(pk PersistenceKey, data Data)
SetData stores conversation data in memory
func (*LocalPersistence) SetState ¶
func (p *LocalPersistence) SetState(pk PersistenceKey, state string)
SetState stores conversation state in memory
type Mux ¶
type Mux struct { Processors []Processor // Contains instances of Mux & Handler Recover RecoverFunc GlobalFilter FilterFunc }
Mux contains handlers, nested multiplexers and global filter.
func NewMux ¶
func NewMux() *Mux
NewMux creates new multiplexer.
Example ¶
package main import ( "os" tm "github.com/and3rson/telemux/v2" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) func main() { // This part is a boilerplate from go-telegram-bot-api library. bot, _ := tgbotapi.NewBotAPI(os.Getenv("TG_TOKEN")) bot.Debug = true u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates := bot.GetUpdatesChan(u) // Create a multiplexer with two handlers: one for command and one for all messages. // If a handler cannot handle the update (fails the filter), // multiplexer will proceed to the next handler. mux := tm.NewMux(). AddHandler(tm.NewHandler( tm.IsCommandMessage("start"), func(u *tm.Update) { bot.Send(tgbotapi.NewMessage(u.Message.Chat.ID, "Hello! Say something. :)")) }, )). AddHandler(tm.NewHandler( tm.Any(), func(u *tm.Update) { bot.Send(tgbotapi.NewMessage(u.Message.Chat.ID, "You said: "+u.Message.Text)) }, )) // Dispatch all telegram updates to multiplexer for update := range updates { mux.Dispatch(bot, update) } }
Output:
func (*Mux) AddHandler ¶
AddHandler adds one or more handlers to multiplexer. This function returns the receiver for convenient chaining.
func (*Mux) AddMux ¶
AddMux adds one or more nested multiplexers to this multiplexer. This function returns the receiver for convenient chaining.
func (*Mux) Dispatch ¶
Dispatch tells Mux to process the update. Returns true if the update was processed by one of the handlers.
func (*Mux) SetGlobalFilter ¶
func (m *Mux) SetGlobalFilter(filter FilterFunc) *Mux
SetGlobalFilter sets a filter to be called for every update before any other filters. This function returns the receiver for convenient chaining.
func (*Mux) SetRecover ¶
func (m *Mux) SetRecover(recover RecoverFunc) *Mux
SetRecover registers a function to call when a panic occurs. This function returns the receiver for convenient chaining.
type PersistenceContext ¶
type PersistenceContext struct { Persistence ConversationPersistence PK PersistenceKey NewState *string }
PersistenceContext allows handler to get/set conversation data & change conversation state.
func (*PersistenceContext) ClearData ¶
func (c *PersistenceContext) ClearData()
ClearData clears data of current conversation.
func (*PersistenceContext) GetData ¶
func (c *PersistenceContext) GetData() Data
GetData returns data of current conversation.
func (*PersistenceContext) PutDataValue ¶
func (c *PersistenceContext) PutDataValue(key string, value interface{})
PutDataValue is a shortcut to insert value into conversation data in one line.
func (*PersistenceContext) SetData ¶
func (c *PersistenceContext) SetData(data Data)
SetData updates data of current conversation.
func (*PersistenceContext) SetState ¶
func (c *PersistenceContext) SetState(state string)
SetState changes state of current conversation.
type PersistenceKey ¶
type PersistenceKey struct { ConversationID string `gorm:"primaryKey;autoIncrement:false"` UserID int64 `gorm:"primaryKey;autoIncrement:false"` ChatID int64 `gorm:"primaryKey;autoIncrement:false"` }
PersistenceKey contains user & chat IDs. It is used to identify conversations with different users in different chats.
func (PersistenceKey) MarshalText ¶
func (k PersistenceKey) MarshalText() ([]byte, error)
MarshalText marshals persistence for use in map keys
func (PersistenceKey) String ¶
func (k PersistenceKey) String() string
String returns a string in form "USER_ID:CHAT_ID".
func (*PersistenceKey) UnmarshalText ¶
func (k *PersistenceKey) UnmarshalText(b []byte) error
UnmarshalText unmarshals persistence from "CONV:USER:CHAT" string
type RecoverFunc ¶
RecoverFunc handles panics which happen during Dispatch.
type Update ¶
type Update struct { tgbotapi.Update Bot *tgbotapi.BotAPI Consumed bool PersistenceContext *PersistenceContext Context Map }
Update wraps tgbotapi.Update and stores some additional data.
func (*Update) Consume ¶
func (u *Update) Consume()
Consume marks update as processed. Used by handler functions to interrupt further processing of the update.
func (*Update) EffectiveChat ¶
EffectiveChat retrieves chat object from update.
func (*Update) EffectiveMessage ¶
EffectiveMessage retrieves message object from update.
func (*Update) EffectiveUser ¶
EffectiveUser retrieves user object from update.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
examples
|
|
album_conversation
album_conversation is a bot that allows users to upload & share photos.
|
album_conversation is a bot that allows users to upload & share photos. |
cat_callback
echo is a bot that repeats whatever you tell him.
|
echo is a bot that repeats whatever you tell him. |
echo
echo is a bot that repeats whatever you tell him.
|
echo is a bot that repeats whatever you tell him. |
error_handling
error_handling is a bot that handles zero division panic.
|
error_handling is a bot that handles zero division panic. |
filters
filters is a bot that can receive photos, text messages & geolocations.
|
filters is a bot that can receive photos, text messages & geolocations. |
members
unknown_group is a bot that will say hello/goodbye when members enver/leave group.
|
unknown_group is a bot that will say hello/goodbye when members enver/leave group. |
nested_mux
nested_mux is a bot that demonstrates nested Mux usage
|
nested_mux is a bot that demonstrates nested Mux usage |
private_only
private_only is a bot that allows you to talk to him only in private chat.
|
private_only is a bot that allows you to talk to him only in private chat. |