botmeans

package module
v0.0.0-...-446eb1a Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2019 License: MIT Imports: 18 Imported by: 0

README

botmeans

GoDoc Go Report Card Build Status codebeat badge

Telegram bot framework

Documentation

Overview

Package botmeans provides a framework for creation of complex high-loaded Telegram bots with rich behaviour

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ActionFactory

func ActionFactory(
	sessionBase SessionBase,
	sessionFactory SessionFactory,
	getters actionExecuterFactoryConfig,
	senderFactory senderFactory,
	out chan Executer,
	handlersProvider ActionHandlersProvider,
)

ActionFactory generates Executers

func BotMessageInitDB

func BotMessageInitDB(db *gorm.DB)

BotMessageInitDB prepares sql tables for BotMessage

func CmdParser

func CmdParser(tgUpdate tgbotapi.Update, aliaser CommandAliaser) string

CmdParser parses command from Update

func RunMachine

func RunMachine(queueStream chan Executer, interval time.Duration) chan interface{}

RunMachine creates the machine, which executes Executers in parallel, but Executers with the same id are executed serially

func SessionInitDB

func SessionInitDB(db *gorm.DB)

SessionInitDB creates sql table for Session

Types

type AbortedContextError

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

AbortedContextError is used to distinguish aborted context from other panics

type Action

type Action struct {
	LastCommand string
	// contains filtered or unexported fields
}

Action provides the context for the user command

func (*Action) Args

func (a *Action) Args() Args

Args allow user to access command args inside ActionHandler through the Context()

func (*Action) Cmd

func (a *Action) Cmd() string

func (*Action) CreateSession

func (a *Action) CreateSession(base SessionBase) error

func (*Action) Error

func (a *Action) Error(e interface{})

Error allow user to terminate ActionHandler through the Context()

func (*Action) Execute

func (a *Action) Execute()

Execute implements Execute for BotMachine

func (*Action) ExecuteInSession

func (a *Action) ExecuteInSession(s ChatSession, f ActionHandler)

ExecuteInSession allows to execute some function in the same goroutine as other action for given session. Can be used to exec commands for chat created from another chat

func (*Action) Finish

func (a *Action) Finish()

Finish allow user to access finish command processing inside ActionHandler through the Context()

func (*Action) Id

func (a *Action) Id() int64

Id returns id based on chat id

func (*Action) Output

func (a *Action) Output() OutMsgFactoryInterface

Output allow user to access the OutMsgFactoryInterface inside ActionHandler through the Context()

func (*Action) Session

func (a *Action) Session() ChatSession

Session allow user to access the session inside ActionHandler through the Context()

func (*Action) SourceMessage

func (a *Action) SourceMessage() BotMessageInterface

SourceMessage allow user to access the session inside ActionHandler through the Context()

type ActionContextInterface

type ActionContextInterface interface {
	Cmd() string
	Args() Args
	Output() OutMsgFactoryInterface
	Error(interface{})
	Session() ChatSession
	SourceMessage() BotMessageInterface
	Finish()
	ExecuteInSession(s ChatSession, f ActionHandler)
	CreateSession(base SessionBase) error
}

ActionContextInterface defines the context for ActionHandler

type ActionExecuterFactory

type ActionExecuterFactory func(
	SessionBase,
	SessionFactory,
	actionExecuterFactoryConfig,
	chan Executer,
)

ActionExecuterFactory creates Executers from given session, cmd, args and source message

type ActionHandler

type ActionHandler func(context ActionContextInterface)

ActionHandler defines the type of handler function

type ActionHandlersProvider

type ActionHandlersProvider func(id string) (ActionHandler, bool)

ActionHandlersProvider returns ActionHandler for given command

type ActionSessionInterface

type ActionSessionInterface interface {
	DataGetSetter
	PersistentSaver
	ChatIdentifier
	IsNew() bool
	Locale() string
}

type Arg

type Arg interface {
	String() (string, bool)
	Float() (float64, bool)
	Mention() (SessionInterface, bool)
	NewSession() (SessionInterface, bool)
	LeftSession() (SessionInterface, bool)
	ComeSession() (SessionInterface, bool)
}

Arg defines the arg type, which is used to pass parsed args through the context

type Args

type Args interface {
	At(int) Arg
	Count() int
	Raw() string
}

func ArgsParser

func ArgsParser(tgUpdate tgbotapi.Update, sessionFactory SessionFactory, aliaser CommandAliaser) Args

ArgsParser parses arguments from Update

type ArgsParserFunc

type ArgsParserFunc func(tgbotapi.Update) Args

ArgsParserFunc returns args of command for the given update

type BotMessage

type BotMessage struct {
	ID             int64  `sql:"index;unique"`
	TelegramMsgID  int64  `sql:"index"`
	TelegramChatID int64  `sql:"index"`
	UserData       string `sql:"type:jsonb"`

	Timestamp time.Time
	// contains filtered or unexported fields
}

BotMessage implements BotMessageInterface

func (*BotMessage) CallbackID

func (botMessage *BotMessage) CallbackID() string

CallbackID returns the telegram CallbackID for the message produced the callback

func (*BotMessage) GetData

func (botMessage *BotMessage) GetData(value interface{})

GetData extracts internal UserData field to given value

func (*BotMessage) Id

func (botMessage *BotMessage) Id() int64

Id identifies the message

func (*BotMessage) Save

func (botMessage *BotMessage) Save() error

Save implements PersistentSaver

func (*BotMessage) SetData

func (botMessage *BotMessage) SetData(value interface{})

SetData sets internal UserData field to JSON representation of given value. Automatically saves information for the value's type, so you don't need to care about it. Just use the same types of value for SetData and GetData

func (*BotMessage) SetID

func (botMessage *BotMessage) SetID(i int64)

SetID updates the Id

type BotMessageFactory

type BotMessageFactory func(int64, int64, string) BotMessageInterface

BotMessageFactory loads bot message from given chat id, msg id and callback id

type BotMessageInterface

type BotMessageInterface interface {
	PersistentSaver
	DataGetSetter
	Id() int64
	CallbackID() string
	SetID(int64)
}

BotMessageInterface defines abstract message generated by the bot

func BotMessageDBLoader

func BotMessageDBLoader(TelegramChatID int64, TelegramMsgID int64, CallbackID string, db *gorm.DB) BotMessageInterface

BotMessageDBLoader loads the message from db

func NewBotMessage

func NewBotMessage(TelegramChatID int64, db *gorm.DB) BotMessageInterface

NewBotMessage creates empty message

type ChatIdentifier

type ChatIdentifier interface {
	ChatId() int64
}

ChatIdentifier defines something that knows which chat it belongs to

type ChatSession

type ChatSession interface {
	Identifiable
	ChatIdentifier
	UserIdentifier
	DataGetSetter
	PersistentSaver
	UserName() string
	ChatTitle() string
	IsOneToOne() bool
	SetLocale(string)
	Locale() string
}

type CmdParserFunc

type CmdParserFunc func(tgbotapi.Update) string

CmdParserFunc returns command for the given update

type CommandAliaser

type CommandAliaser func(string) (string, Args, bool)

CommandAliaser converts any text to cmd and args

func AliaserFromTemplateDir

func AliaserFromTemplateDir(p string) CommandAliaser

AliaserFromTemplateDir reads the given dir and calls AliaserFromTemplates

func AliaserFromTemplates

func AliaserFromTemplates(sourceList []io.Reader) CommandAliaser

AliaserFromTemplates creates aliaser from given set of templates

type DataGetSetter

type DataGetSetter interface {
	SetData(value interface{})
	GetData(value interface{})
}

DataGetSetter defines interface for saving/loading custom data inside the object

type Executer

type Executer interface {
	Id() int64
	Execute()
}

Executer is a executable operation

type Identifiable

type Identifiable interface {
	Id() int64
}

type Localizer

type Localizer interface {
	Locale() string
}

type MeansBot

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

MeansBot is a body of botmeans framework instance.

func New

func New(DB *gorm.DB, netConfig NetConfig, tlgConfig TelegramConfig) (*MeansBot, error)

New creates new MeansBot instance

func (*MeansBot) Find

func (ui *MeansBot) Find(val ...Identifiable) (err error)

func (*MeansBot) FindSession

func (ui *MeansBot) FindSession(id int64) ChatSession

func (*MeansBot) GetBotMessagesByChatAndType

func (ui *MeansBot) GetBotMessagesByChatAndType(session ChatIdentifier, typeSample interface{}) (ret []BotMessageInterface)

GetBotMessagesByChatAndType returns Bot messages from session's chat with given UserData type

func (*MeansBot) GetChatSessions

func (ui *MeansBot) GetChatSessions(session ChatSession) (ret []ChatSession)

GetNeighborSessions returns all sessions that are in the same chat as given session

func (*MeansBot) GetUserSessions

func (ui *MeansBot) GetUserSessions(session UserIdentifier) (ret []ChatSession)

GetSessionsByTelegramUserID returns all sessions with given Telegram User ID

func (*MeansBot) Run

func (ui *MeansBot) Run(handlersProvider ActionHandlersProvider) chan interface{}

Run starts updates handling. Returns stop chan

func (*MeansBot) SetChatLocale

func (ui *MeansBot) SetChatLocale(session ChatSession, locale string)

SetChatLocale sets the locale of all sessions in this chat

type MessageButton

type MessageButton struct {
	Text    string
	Command string
	Args    string
}

MessageButton represents a button in Telegram UI

type MessageTemplate

type MessageTemplate struct {
	ParseMode     string
	Keyboard      map[string][][]MessageButton
	Template      map[string]string
	ReplyKeyboard map[string][][]MessageButton
}

MessageTemplate defines the structure of the message template

type NetConfig

type NetConfig struct {
	ListenIP   string
	ListenPort int16
}

NetConfig is a MeansBot network config for using with New function

type NewSessionCreator

type NewSessionCreator func(chatId int64, username string) (SessionInterface, error)

type OutMsgFactoryInterface

type OutMsgFactoryInterface interface {
	Create(templateName string, Data interface{}) error
	CreateWithCustomReplyKeyboard(templateName string, Data interface{}, kdb [][]MessageButton) error
	Edit(msg BotMessageInterface, templateName string, Data interface{}) error
	Notify(BotMessageInterface, string, bool)
	SimpleText(text string) error
}

OutMsgFactoryInterface allows users to create or edit messages inside ActionHandlers

type PersistentSaver

type PersistentSaver interface {
	Save() error
}

PersistentSaver can save itself to permanent storage

type Sendable

type Sendable interface {
	Send() bool
}

Sendable defines something that can be Send

type Sender

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

Sender implements SenderInterface

func (*Sender) Create

func (f *Sender) Create(templateName string, Data interface{}) error

Create creates new telegram message from template

func (*Sender) CreateWithCustomReplyKeyboard

func (f *Sender) CreateWithCustomReplyKeyboard(templateName string, Data interface{}, kbd [][]MessageButton) error

Create creates new telegram message from template using custom reply keyboard

func (*Sender) Edit

func (f *Sender) Edit(msg BotMessageInterface, templateName string, Data interface{}) error

Edit allows to edit existing messages

func (*Sender) Notify

func (f *Sender) Notify(msg BotMessageInterface, callbackNotification string, showAlert bool)

Notify creates notification for callback queries

func (*Sender) SimpleText

func (f *Sender) SimpleText(text string) error

SimpleText creates new telegram message with given text

type SenderInterface

type SenderInterface interface {
	OutMsgFactoryInterface
}

SenderInterface is the abstraction for the Sender

type Session

type Session struct {
	SessionBase
	ID       int64  `sql:"index;unique"`
	UserData string `sql:"type:jsonb"`

	FirstName string
	LastName  string
	ChatName  string
	CreatedAt time.Time
	// contains filtered or unexported fields
}

Session represents the user in chat.

func (*Session) ChatId

func (session *Session) ChatId() int64

ChatId returns chat id

func (*Session) ChatTitle

func (session *Session) ChatTitle() string

ChatName returns name of the chat of this session

func (*Session) GetData

func (session *Session) GetData(value interface{})

GetData extracts internal UserData field to given value

func (*Session) HasCome

func (session *Session) HasCome() bool

HasCome returns true if the user has come to chat

func (*Session) HasLeft

func (session *Session) HasLeft() bool

HasLeft returns true if the user has gone from chat

func (*Session) Id

func (session *Session) Id() int64

func (*Session) IsNew

func (session *Session) IsNew() bool

IsNew should return true if the session has not been saved yet

func (*Session) IsOneToOne

func (session *Session) IsOneToOne() bool

IsOneToOne should return true if the session represents one-to-one chat with bot

func (*Session) Locale

func (session *Session) Locale() string

Locale returns the locale for this user

func (*Session) Save

func (session *Session) Save() error

Save saves the session to sql table

func (*Session) SetData

func (session *Session) SetData(value interface{})

SetData sets internal UserData field to JSON representation of given value

func (*Session) SetLocale

func (session *Session) SetLocale(locale string)

func (*Session) String

func (session *Session) String() string

String represents the session as string

func (*Session) UserId

func (session *Session) UserId() int64

func (*Session) UserName

func (session *Session) UserName() string

UserName returns name of the user of this session

type SessionBase

type SessionBase struct {
	TelegramUserID   int64  `sql:"index"`
	TelegramUserName string `sql:"index"`
	TelegramChatID   int64  `sql:"index"`
	// contains filtered or unexported fields
}

SessionBase passes core session identifiers

type SessionFactory

type SessionFactory func(base SessionBase) (SessionInterface, error)

SessionFactory creates the session from given session base

type SessionInterface

type SessionInterface interface {
	ChatIdentifier
	UserIdentifier
	PersistentSaver
	DataGetSetter
	IsNew() bool
	HasLeft() bool
	HasCome() bool
	Locale() string
	UserName() string
	Identifiable
	SetLocale(string)
	ChatTitle() string
	IsOneToOne() bool
}

SessionInterface defines the user session

func SessionLoader

func SessionLoader(base SessionBase, db *gorm.DB, BotID int64, api *tgbotapi.BotAPI) (SessionInterface, error)

SessionLoader creates the session and loads the data if the session exists

type TelegramConfig

type TelegramConfig struct {
	BotToken    string
	WebhookHost string
	SSLCertFile string
	BotName     string
	TemplateDir string
}

TelegramConfig is a MeansBot telegram API config for using with New function

type UserIdentifier

type UserIdentifier interface {
	UserId() int64
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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