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
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(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, ...) *Handler
- func NewEditedChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewEditedMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewInlineQueryHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- func NewMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
- type LocalPersistence
- 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 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 ¶ added in v1.1.5
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 ¶ added in v1.1.5
func NewFilePersistence(filename string) *FilePersistence
NewFilePersistence creates new instance of FilePersistence.
func (*FilePersistence) GetData ¶ added in v1.3.0
func (p *FilePersistence) GetData(pk PersistenceKey) Data
GetData reads conversation data from file
func (*FilePersistence) GetState ¶ added in v1.1.5
func (p *FilePersistence) GetState(pk PersistenceKey) string
GetState reads conversation state from file
func (*FilePersistence) SetData ¶ added in v1.3.0
func (p *FilePersistence) SetData(pk PersistenceKey, data Data)
SetData writes conversation data to file
func (*FilePersistence) SetState ¶ added in v1.1.5
func (p *FilePersistence) SetState(pk PersistenceKey, state string)
SetState writes conversation state to file
type FilterFunc ¶ added in v1.6.0
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 ¶ added in v1.1.4
func HasAnimation() FilterFunc
HasAnimation filters updates that contain an animation.
func HasAudio ¶ added in v1.1.4
func HasAudio() FilterFunc
HasAudio filters updates that contain an audio.
func HasContact ¶ added in v1.1.4
func HasContact() FilterFunc
HasContact filters updates that contain a contact.
func HasDocument ¶ added in v1.1.4
func HasDocument() FilterFunc
HasDocument filters updates that contain a document.
func HasLocation ¶ added in v1.1.4
func HasLocation() FilterFunc
HasLocation filters updates that contain a location.
func HasPhoto ¶ added in v1.1.4
func HasPhoto() FilterFunc
HasPhoto filters updates that contain a photo.
func HasRegex ¶ added in v1.1.4
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 HasSticker ¶ added in v1.1.4
func HasSticker() FilterFunc
HasSticker filters updates that contain a sticker.
func HasText ¶ added in v1.1.4
func HasText() FilterFunc
HasText filters updates that look like text, i. e. have some text and do not start with a slash ("/").
func HasVenue ¶ added in v1.1.4
func HasVenue() FilterFunc
HasVenue filters updates that contain a venue.
func HasVideo ¶ added in v1.1.4
func HasVideo() FilterFunc
HasVideo filters updates that contain a video.
func HasVideoNote ¶ added in v1.1.4
func HasVideoNote() FilterFunc
HasVideoNote filters updates that contain a video note.
func HasVoice ¶ added in v1.1.4
func HasVoice() FilterFunc
HasVoice filters updates that contain a voice message.
func IsAnyCommandMessage ¶ added in v1.1.4
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 ¶ added in v1.0.2
func IsCallbackQuery() FilterFunc
IsCallbackQuery filters updates that are callbacks from button presses.
func IsChannelPost ¶ added in v1.0.2
func IsChannelPost() FilterFunc
IsChannelPost filters updates that are channel posts.
func IsCommandMessage ¶ added in v1.1.4
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 ¶ added in v1.0.2
func IsEditedChannelPost() FilterFunc
IsEditedChannelPost filters updates that are edits to existing channel posts.
func IsEditedMessage ¶ added in v1.0.2
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 ¶ added in v1.0.2
func IsInlineQuery() FilterFunc
IsInlineQuery filters updates that are callbacks from inline queries.
func IsLeftChatMember ¶ added in v1.1.1
func IsLeftChatMember() FilterFunc
IsLeftChatMember filters updates that have user in LeftChatMember property.
func IsMessage ¶ added in v1.0.3
func IsMessage() FilterFunc
IsMessage filters updates that look like message (text, photo, location etc.)
func IsNewChatMembers ¶ added in v1.1.1
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 ¶ added in v1.8.0
func NewCallbackQueryHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewCallbackQueryHandler creates a handler for updates that contain callback query.
func NewChannelPostHandler ¶ added in v1.8.0
func NewChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewChannelPostHandler creates a handler for updates that contain channel post.
func NewCommandHandler ¶ added in v1.8.0
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"}
Example ¶
package main import ( "fmt" "os" "strconv" tm "github.com/and3rson/telemux" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) 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 ¶ added in v1.0.1
func NewConversationHandler( conversationID string, persistence ConversationPersistence, states map[string][]*Handler, 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. It's recommended to have an empty string (`""`) as an initial 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. They are useful to handle commands such as "/cancel" or to display some default message.
func NewEditedChannelPostHandler ¶ added in v1.8.0
func NewEditedChannelPostHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewEditedChannelPostHandler creates a handler for updates that contain edited channel post.
func NewEditedMessageHandler ¶ added in v1.8.0
func NewEditedMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewEditedMessageHandler creates a handler for updates that contain edited message.
func NewHandler ¶ added in v1.0.1
func NewHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewHandler creates a new generic handler.
func NewInlineQueryHandler ¶ added in v1.8.0
func NewInlineQueryHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewInlineQueryHandler creates a handler for updates that contain inline query.
func NewMessageHandler ¶ added in v1.8.0
func NewMessageHandler(filter FilterFunc, handles ...HandleFunc) *Handler
NewMessageHandler creates a handler for updates that contain message.
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 ¶ added in v1.3.0
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 ¶ added in v1.3.0
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 ¶ added in v1.0.1
func NewMux() *Mux
NewMux creates new multiplexer.
Example ¶
package main import ( "os" tm "github.com/and3rson/telemux" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" ) 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 ¶ added in v1.5.1
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 ¶ added in v1.5.1
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 ¶ added in v1.7.0
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 ¶ added in v1.3.0
type PersistenceContext struct { Persistence ConversationPersistence PK PersistenceKey NewState *string }
PersistenceContext allows handler to get/set conversation data & change conversation state.
func (*PersistenceContext) ClearData ¶ added in v1.3.0
func (c *PersistenceContext) ClearData()
ClearData clears data of current conversation.
func (*PersistenceContext) GetData ¶ added in v1.3.0
func (c *PersistenceContext) GetData() Data
GetData returns data of current conversation.
func (*PersistenceContext) PutDataValue ¶ added in v1.8.4
func (c *PersistenceContext) PutDataValue(key string, value string)
PutValueData is a shortcut to insert value into conversation data in one line.
func (*PersistenceContext) SetData ¶ added in v1.3.0
func (c *PersistenceContext) SetData(data Data)
SetData updates data of current conversation.
func (*PersistenceContext) SetState ¶ added in v1.3.0
func (c *PersistenceContext) SetState(state string)
SetState changes state of current conversation.
type PersistenceKey ¶
type PersistenceKey struct { ConversationID string `gorm:"primaryKey;autoIncrement:false"` UserID int `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 ¶ added in v1.1.5
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 ¶ added in v1.1.5
func (k *PersistenceKey) UnmarshalText(b []byte) error
UnmarshalText unmarshals persistence from "CONV:USER:CHAT" string
type RecoverFunc ¶ added in v1.7.0
RecoverFunc handles panics which happen during Dispatch.
type Update ¶
type Update struct { tgbotapi.Update Bot *tgbotapi.BotAPI Consumed bool PersistenceContext *PersistenceContext Context map[string]interface{} }
Update wraps tgbotapi.Update and stores some additional data.
func (*Update) Consume ¶ added in v1.4.3
func (u *Update) Consume()
Consume marks update as processed. Used by handler functions to interrupt further processing of the update.
func (*Update) EffectiveChat ¶ added in v1.0.5
EffectiveChat retrieves chat object from update.
func (*Update) EffectiveMessage ¶ added in v1.0.5
EffectiveMessage retrieves message object from update.
func (*Update) EffectiveUser ¶ added in v1.0.5
EffectiveUser retrieves user object from update.
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. |
gormpersistence
module
|