integram

package module
v0.0.0-...-dff46b9 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2022 License: GPL-3.0 Imports: 43 Imported by: 0

README ΒΆ

Integram 2.0

Framework and platform to integrate services with Telegram using the official Telegram Bot API

ℹ️ Individual integration repos are located at https://github.com/integram-org.

CircleCI Docker Image GoDoc

Screencast

How to use Integram in Telegram (using public bots)

Just use these links to add bots to your Telegram

Did not find your favorite service? 🀘 Vote for it

How to host Integram on your own server (using your private bots)

🐳 Docker way

   git clone https://github.com/GoTrellium/integram && cd integram
  • Check the docker-compose.yml file for the required ENV vars for each service
    • E.g. in order to run the Trello integration you will need to export:

      • INTEGRAM_BASE_URL – the base URL where your Integram host will be accessible, e.g. https://integram.org

      • INTEGRAM_PORT – if set to 443 Integram will use ssl.key/ssl.cert at /go/.conf.

        • For Let's Encrypt: ssl.cert has to be fullchain.pem, not cert.pem

        This directory is mounted on your host machine. Just get the path and put these files inside

           ## Get the path of config directory on the host machine
           docker volume inspect -f '{{ .Mountpoint }}' integram_data-mainapp
        
      • TRELLO_BOT_TOKEN – your bot's token you got from @BotFather

      • You will need to get your own OAuth credentials from Trello

        • TRELLO_OAUTH_ID – API Key
        • TRELLO_OAUTH_SECRET – OAuth Secret
    • For more detailed info about other services you should check the corresponding repo at https://github.com/integram-org

  • Export the variables you identified in the previous step, for instance on linux this should be something like:
   export INTEGRAM_PORT=xxxx
   export ...
  • Now you can run the services (linux: careful if you need to sudo this, the exports you just did will not be available) :
   docker-compose -p integram up trello gitlab ## Here you specify the services you want to run
  • Or in background mode (add -d):
   docker-compose -p integram up -d trello gitlab
  • You should now see Integram's startup logs in your console
  • In Telegram, you can now start your bots (/start) and follow their directions, configure them using /settings
  • Some useful commands:
   ## Check the containers status
   docker ps
   
   ## Fetch logs for main container
   docker logs -f $(docker ps -aqf "name=integram_integram")   
  • To update Integram to the latest version:
    ## Fetch last version of images
    docker-compose pull integram trello gitlab
    ## Restart containers using the new images
    docker-compose -p integram up -d trello gitlab

πŸ›  Old-school way (No docker)

    ## set the GOPATH to the absolute path of directory containing 'src' directory that you have created before
    export GOPATH=/var/integram
    
    cd $GOPATH/src/integram
    ## install dependencies
    dep init
    go build integram && ./integram
Dependencies

Dependencies are specified in Gopkg.toml and fetched using Go dep

Contributing

Feel free to send PRs. If you want to contribute new service integrations, please create an issue first. Just to make sure someone is not already working on it.

Libraries used in Integram
License

Code licensed under GPLV3 license

Analytics

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	// JobRetryLinear specify jobs retry politic as retry after fail
	JobRetryLinear = iota
	// JobRetryFibonacci specify jobs retry politic as delay after fail using fibonacci sequence
	JobRetryFibonacci
)

Variables ΒΆ

View Source
var Config config
View Source
var ErrorBadRequstPrefix = "Can't process your request: "
View Source
var ErrorFlood = fmt.Errorf("Too many messages. You could not send the same message more than once per %d sec", antiFloodSameMessageTimeout)
View Source
var GetFileMaxSizeExceedError = errors.New("Maximum allowed file size exceed")
View Source
var MaxMsgsToUpdateWithEventID = 10

MaxMsgsToUpdateWithEventID set the maximum number of last messages to update with EditMessagesTextWithEventID

Functions ΒΆ

func GetLocalFilePath ΒΆ

func GetLocalFilePath(c *Context, fileID string) (string, error)

func GetRemoteFilePath ΒΆ

func GetRemoteFilePath(c *Context, fileID string) (string, error)

func GetShortVersion ΒΆ

func GetShortVersion() string

GetVersion returns the current HEAD git commit(first 7 symbols) if .git exists

func GetVersion ΒΆ

func GetVersion() string

GetVersion returns the current HEAD git commit if .git exists

func Logger ΒΆ

func Logger() *log.Logger

func MigrateOAuthFromTo ΒΆ

func MigrateOAuthFromTo(c *Context, oldTS OAuthTokenStore, newTS OAuthTokenStore, onlyValid bool) (total int, migrated int, expired int, err error)

func ObjectIdHex ΒΆ

func ObjectIdHex(s string) bson.ObjectId

func Register ΒΆ

func Register(servicer Servicer, botToken string)

Register the service's config and corresponding botToken

func ReverseProxy ΒΆ

func ReverseProxy(target *url.URL) gin.HandlerFunc

func Run ΒΆ

func Run()

Run initiates Integram to listen webhooks, TG updates and start the workers pool

func ServiceWorkerAutorespawnGoroutine ΒΆ

func ServiceWorkerAutorespawnGoroutine(s *Service)

func SetOAuthTokenStore ΒΆ

func SetOAuthTokenStore(store OAuthTokenStore)

func SliceContainsString ΒΆ

func SliceContainsString(s []string, e string) bool

SliceContainsString returns true if []string contains string

func URLMustParse ΒΆ

func URLMustParse(s string) *url.URL

URLMustParse returns url.URL from static string. Don't use it with a dynamic param

Types ΒΆ

type Bot ΒΆ

type Bot struct {
	// Bot Telegram user id
	ID int64

	// Bot Telegram username
	Username string

	API *tg.BotAPI
	// contains filtered or unexported fields
}

Bot represents parsed auth data & API reference

func (*Bot) PMURL ΒΆ

func (c *Bot) PMURL(param string) string

PMURL return URL to private messaging with the bot like https://telegram.me/trello_bot?start=param

type BotConfig ΒΆ

type BotConfig struct {
	Token string `envconfig:"BOT_TOKEN" required:"true"`
}

type Button ΒΆ

type Button struct {
	Data string // data is stored in the DB. May be collisions if button text is not unique per keyboard
	Text string // should be unique per keyboard
}

Button contains the data to create Keyboard

func (Button) Keyboard ΒΆ

func (button Button) Keyboard() Keyboard

Keyboard generates keyboard from 1 button

type Buttons ΒΆ

type Buttons []Button

Buttons is a Shorthand for []Button

func (*Buttons) Append ΒΆ

func (buttons *Buttons) Append(data string, text string)

Append adds Button with URL to the end of Buttons(row)

func (*Buttons) InlineButtons ΒΆ

func (buttons *Buttons) InlineButtons() InlineButtons

InlineButtons converts Buttons to InlineButtons useful with universal methods that create keyboard (f.e. settigns) for both usual and inline keyboard

func (Buttons) Keyboard ΒΆ

func (buttons Buttons) Keyboard() Keyboard

Keyboard is generating Keyboard with 1 column

func (*Buttons) Markup ΒΆ

func (buttons *Buttons) Markup(columns int) Keyboard

Markup generate Keyboard from Buttons ([]Button), chunking buttons by columns number

func (*Buttons) Prepend ΒΆ

func (buttons *Buttons) Prepend(data string, text string)

Prepend adds InlineButton with URL to the begin of InlineButtons(row)

type Chat ΒΆ

type Chat struct {
	ID        int64  `bson:"_id"`
	Type      string `bson:",omitempty"`
	FirstName string
	LastName  string `bson:",omitempty"`
	UserName  string `bson:",omitempty"`
	Title     string `bson:",omitempty"`
	Tz        string `bson:",omitempty"`
	// contains filtered or unexported fields
}

Chat information initiated from TG

func (*Chat) BotWasKickedOrStopped ΒΆ

func (chat *Chat) BotWasKickedOrStopped() bool

OAuthValid checks if OAuthToken for service is set

func (*Chat) Cache ΒΆ

func (chat *Chat) Cache(key string, res interface{}) (exists bool)

Cache returns if Chat's cache for specific key exists and try to bind it to res

func (*Chat) ClearAllCacheKeys ΒΆ

func (chat *Chat) ClearAllCacheKeys() error

ClearAllCacheKeys removes all Chat's cache keys

func (*Chat) IsGroup ΒΆ

func (c *Chat) IsGroup() bool

IsGroup returns true if chat is a group chat

func (*Chat) IsPrivate ΒΆ

func (c *Chat) IsPrivate() bool

IsPrivate returns true if chat is a private chat

func (*Chat) SaveSetting ΒΆ

func (chat *Chat) SaveSetting(key string, value interface{}) error

SaveSetting sets Chat's setting for service with specific key

func (*Chat) SaveSettings ΒΆ

func (chat *Chat) SaveSettings(allSettings interface{}) error

SaveSettings save Chat's setting for service

func (*Chat) ServiceHookToken ΒΆ

func (chat *Chat) ServiceHookToken() string

ServiceHookToken returns Chats's hook token to use in webhook handling

func (*Chat) ServiceHookURL ΒΆ

func (chat *Chat) ServiceHookURL() string

ServiceHookURL returns Chats's webhook URL for service to use in webhook handling Used in case when user need to put webhook URL to receive notifications to chat

func (*Chat) SetCache ΒΆ

func (chat *Chat) SetCache(key string, val interface{}, ttl time.Duration) error

SetCache set the Chats's cache with specific key and TTL

func (*Chat) Setting ΒΆ

func (chat *Chat) Setting(key string) (result interface{}, exists bool)

Setting returns Chat's setting for service with specific key. NOTE! Only builtin types are supported (f.e. structs will become map)

func (*Chat) Settings ΒΆ

func (chat *Chat) Settings(out interface{}) error

Settings bind Chat's settings for service to the interface

func (*Chat) UpdateCache ΒΆ

func (chat *Chat) UpdateCache(key string, update interface{}, res interface{}) error

UpdateCache updates the per Chat cache using MongoDB Update query (see trello service as example)

type ChatConfig ΒΆ

type ChatConfig struct {
	tg.ChatConfig
}

type ChatConfigWithUser ΒΆ

type ChatConfigWithUser struct {
	tg.ChatConfigWithUser
}

type Context ΒΆ

type Context struct {
	ServiceName    string  // Actual service's name. Use context's Service() method to receive full service config
	ServiceBaseURL url.URL // Useful for self-hosted services. Default set to service's DefaultHost

	User               User                // User associated with current webhook or Telegram update.
	Chat               Chat                // Chat associated with current webhook or Telegram update
	Message            *IncomingMessage    // Telegram incoming message if it triggired current request
	MessageEdited      bool                // True if Message is edited message instead of the new one
	InlineQuery        *tg.InlineQuery     // Telegram inline query if it triggired current request
	ChosenInlineResult *chosenInlineResult // Telegram chosen inline result if it triggired current request

	Callback *callback // Telegram inline buttons callback if it it triggired current request
	// contains filtered or unexported fields
}

Context of the current request

func (*Context) AnswerCallbackQuery ΒΆ

func (c *Context) AnswerCallbackQuery(text string, showAlert bool) error

AnswerCallbackQuery answer the inline keyboard callback query that triggered this request with toast or alert

func (*Context) AnswerCallbackQueryWithURL ΒΆ

func (c *Context) AnswerCallbackQueryWithURL(url string) error

func (*Context) AnswerInlineQueryWithPM ΒΆ

func (c *Context) AnswerInlineQueryWithPM(text string, parameter string) error

AnswerInlineQueryWithPM answer the inline query that triggered this request with Private Message redirect tip

func (*Context) AnswerInlineQueryWithResults ΒΆ

func (c *Context) AnswerInlineQueryWithResults(res []interface{}, cacheTime int, isPersonal bool, nextOffset string) error

AnswerInlineQueryWithResults answer the inline query that triggered this request

func (*Context) AnswerInlineQueryWithResultsAndPM ΒΆ

func (c *Context) AnswerInlineQueryWithResultsAndPM(res []interface{}, cacheTime int, isPersonal bool, nextOffset string, PMText string, PMParameter string) error

AnswerInlineQueryWithResults answer the inline query that triggered this request

func (*Context) Bot ΒΆ

func (c *Context) Bot() *Bot

Bot related to the service of current request

func (*Context) Db ΒΆ

func (c *Context) Db() *mgo.Database

Db returns the MongoDB *mgo.Database instance

func (*Context) DeleteMessage ΒΆ

func (c *Context) DeleteMessage(om *OutgoingMessage) error

DeleteMessage deletes the outgoing message's text and inline keyboard

func (*Context) DeleteMessagesWithEventID ΒΆ

func (c *Context) DeleteMessagesWithEventID(eventID string) (deleted int, err error)

DeleteMessagesWithEventID deletes the last MaxMsgsToUpdateWithEventID messages' text and inline keyboard with the corresponding eventID in ALL chats

func (*Context) DownloadURL ΒΆ

func (c *Context) DownloadURL(url string) (filePath string, err error)

DownloadURL downloads the remote URL and returns the local file path

func (*Context) EditInlineButton ΒΆ

func (c *Context) EditInlineButton(om *OutgoingMessage, kbState string, buttonData string, newButtonText string) error

EditInlineButton edit the outgoing message's inline button

func (*Context) EditInlineKeyboard ΒΆ

func (c *Context) EditInlineKeyboard(om *OutgoingMessage, fromState string, kb InlineKeyboard) error

EditInlineKeyboard edit the outgoing message's inline keyboard

func (*Context) EditInlineStateButton ΒΆ

func (c *Context) EditInlineStateButton(om *OutgoingMessage, kbState string, oldButtonState int, buttonData string, newButtonState int, newButtonText string) error

EditInlineStateButton edit the outgoing message's inline button with a state

func (*Context) EditMessageText ΒΆ

func (c *Context) EditMessageText(om *OutgoingMessage, text string) error

EditMessageText edit the text of message previously sent by the bot

func (*Context) EditMessageTextAndInlineKeyboard ΒΆ

func (c *Context) EditMessageTextAndInlineKeyboard(om *OutgoingMessage, fromState string, text string, kb InlineKeyboard) error

EditMessageTextAndInlineKeyboard edit the outgoing message's text and inline keyboard

func (*Context) EditMessageTextWithMessageID ΒΆ

func (c *Context) EditMessageTextWithMessageID(msgID bson.ObjectId, text string) (edited int, err error)

EditMessagesTextWithMessageID edit the one message text with by message BSON ID

func (*Context) EditMessagesTextWithEventID ΒΆ

func (c *Context) EditMessagesTextWithEventID(eventID string, text string) (edited int, err error)

EditMessagesTextWithEventID edit the last MaxMsgsToUpdateWithEventID messages' text with the corresponding eventID in ALL chats

func (*Context) EditMessagesWithEventID ΒΆ

func (c *Context) EditMessagesWithEventID(eventID string, fromState string, text string, kb InlineKeyboard) (edited int, err error)

EditMessagesWithEventID edit the last MaxMsgsToUpdateWithEventID messages' text and inline keyboard with the corresponding eventID in ALL chats

func (*Context) EditPressedInlineButton ΒΆ

func (c *Context) EditPressedInlineButton(newState int, newText string) error

EditPressedInlineButton edit the text and state of pressed inline button in case this request is triggered by inlineButton callback

func (*Context) EditPressedInlineKeyboard ΒΆ

func (c *Context) EditPressedInlineKeyboard(kb InlineKeyboard) error

EditPressedInlineKeyboard edit the inline keyboard in the msg where user taped it in case this request is triggered by inlineButton callback

func (*Context) EditPressedMessageText ΒΆ

func (c *Context) EditPressedMessageText(text string) error

EditPressedMessageText edit the text in the msg where user taped it in case this request is triggered by inlineButton callback

func (*Context) EditPressedMessageTextAndInlineKeyboard ΒΆ

func (c *Context) EditPressedMessageTextAndInlineKeyboard(text string, kb InlineKeyboard) error

EditPressedMessageTextAndInlineKeyboard edit the text and inline keyboard in the msg where user taped it in case this request is triggered by inlineButton callback

func (*Context) FindChat ΒΆ

func (c *Context) FindChat(query interface{}) (chatData, error)

func (*Context) FindChats ΒΆ

func (c *Context) FindChats(query interface{}) ([]chatData, error)

func (*Context) FindChatsLimit ΒΆ

func (c *Context) FindChatsLimit(query interface{}, limit int, sort ...string) ([]chatData, error)

func (*Context) FindMessageByEventID ΒΆ

func (c *Context) FindMessageByEventID(id string) (*Message, error)

FindMessageByEventID find message by event id

func (*Context) FindUser ΒΆ

func (c *Context) FindUser(query interface{}) (userData, error)

func (*Context) FindUsers ΒΆ

func (c *Context) FindUsers(query interface{}) ([]userData, error)

func (*Context) FindUsersLimit ΒΆ

func (c *Context) FindUsersLimit(query interface{}, limit int, sort ...string) ([]userData, error)

func (*Context) KeyboardAnswer ΒΆ

func (c *Context) KeyboardAnswer() (data string, buttonText string)

KeyboardAnswer retrieve the data related to pressed button buttonText will be returned only in case this button relates to the one in db for this chat

func (*Context) Log ΒΆ

func (c *Context) Log() *log.Entry

Log creates the logrus entry and attach corresponding info from the context

func (*Context) NewMessage ΒΆ

func (c *Context) NewMessage() *OutgoingMessage

NewMessage creates the message targeted to the current chat

func (*Context) OAuthProvider ΒΆ

func (c *Context) OAuthProvider() *OAuthProvider

OAuthProvider details. Useful for services that can be installed on your own side

func (*Context) SaveOAuthProvider ΒΆ

func (c *Context) SaveOAuthProvider(baseURL url.URL, id string, secret string) (*OAuthProvider, error)

SaveOAuthProvider add the OAuth client to DB. Useful when the new OAuth provider registred for self-hosted services

func (*Context) SendAction ΒΆ

func (c *Context) SendAction(s string) error

SendAction send the one of "typing", "upload_photo", "record_video", "upload_video", "record_audio", "upload_audio", "upload_document", "find_location"

func (*Context) Service ΒΆ

func (c *Context) Service() *Service

Service related to the current context

func (*Context) ServiceCache ΒΆ

func (c *Context) ServiceCache(key string, res interface{}) (exists bool)

ServiceCache returns if Services's cache for specific key exists and try to bind it to res

func (*Context) SetDb ΒΆ

func (c *Context) SetDb(database *mgo.Database)

func (*Context) SetServiceBaseURL ΒΆ

func (c *Context) SetServiceBaseURL(domainOrURL string)

SetServiceBaseURL set the baseURL for the current request. Useful when service can be self-hosted. The actual service URL can be found in the incoming webhook

func (*Context) SetServiceCache ΒΆ

func (c *Context) SetServiceCache(key string, val interface{}, ttl time.Duration) error

SetServiceCache set the Services's cache with specific key and TTL

func (*Context) StatInc ΒΆ

func (c *Context) StatInc(key StatKey) error

func (*Context) StatIncBy ΒΆ

func (c *Context) StatIncBy(key StatKey, uniqueID int64, inc int) error

func (*Context) StatIncChat ΒΆ

func (c *Context) StatIncChat(key StatKey) error

func (*Context) StatIncUser ΒΆ

func (c *Context) StatIncUser(key StatKey) error

func (*Context) UpdateServiceCache ΒΆ

func (c *Context) UpdateServiceCache(key string, update interface{}, res interface{}) error

UpdateServiceCache updates the Services's cache using MongoDB Update query (see trello service as example)

func (*Context) WebPreview ΒΆ

func (c *Context) WebPreview(title string, headline string, text string, serviceURL string, imageURL string) (WebPreviewURL string)

WebPreview generate fake webpreview and store it in DB. Telegram will resolve it as we need

type DefaultOAuth1 ΒΆ

type DefaultOAuth1 struct {
	Key                              string
	Secret                           string
	RequestTokenURL                  string
	AuthorizeTokenURL                string
	AccessTokenURL                   string
	AdditionalAuthorizationURLParams map[string]string
	HTTPMethod                       string
	AccessTokenReceiver              func(serviceContext *Context, r *http.Request, requestToken *oauth.RequestToken) (token string, err error)
}

DefaultOAuth1 is the default OAuth1 config for the service

type DefaultOAuth2 ΒΆ

type DefaultOAuth2 struct {
	oauth2.Config
	AccessTokenReceiver func(serviceContext *Context, r *http.Request) (token string, expiresAt *time.Time, refreshToken string, err error)

	// duration to cache temp token to associate with user
	// default(when zero) will be set to 30 days
	AuthTempTokenCacheTime time.Duration
}

DefaultOAuth2 is the default OAuth2 config for the service

type DefaultOAuthTokenMongoStore ΒΆ

type DefaultOAuthTokenMongoStore struct {
}

func (*DefaultOAuthTokenMongoStore) GetOAuthAccessToken ΒΆ

func (d *DefaultOAuthTokenMongoStore) GetOAuthAccessToken(user *User) (token string, expireDate *time.Time, err error)

func (*DefaultOAuthTokenMongoStore) GetOAuthRefreshToken ΒΆ

func (d *DefaultOAuthTokenMongoStore) GetOAuthRefreshToken(user *User) (string, error)

func (*DefaultOAuthTokenMongoStore) Name ΒΆ

func (*DefaultOAuthTokenMongoStore) SetOAuthAccessToken ΒΆ

func (d *DefaultOAuthTokenMongoStore) SetOAuthAccessToken(user *User, token string, expireDate *time.Time) error

func (*DefaultOAuthTokenMongoStore) SetOAuthRefreshToken ΒΆ

func (d *DefaultOAuthTokenMongoStore) SetOAuthRefreshToken(user *User, refreshToken string) error

type FileInfo ΒΆ

type FileInfo struct {
	ID   string
	Name string
	Type FileType
	Mime string
	Size int64
}

func (*FileInfo) Emoji ΒΆ

func (info *FileInfo) Emoji() string

type FileType ΒΆ

type FileType string
const (
	FileTypeDocument FileType = "document"
	FileTypePhoto    FileType = "photo"
	FileTypeAudio    FileType = "audio"
	FileTypeSticker  FileType = "sticker"
	FileTypeVideo    FileType = "video"
	FileTypeVoice    FileType = "voice"
)

type HTMLRichText ΒΆ

type HTMLRichText struct{}

HTMLRichText produce HTML that can be sent to Telegram

func (HTMLRichText) Bold ΒΆ

func (hrt HTMLRichText) Bold(text string) string

Bold generates <b>text</b>

func (HTMLRichText) EncodeEntities ΒΆ

func (hrt HTMLRichText) EncodeEntities(s string) string

EncodeEntities encodes '<', '>'

func (HTMLRichText) Fixed ΒΆ

func (hrt HTMLRichText) Fixed(s string) string

Fixed generates <code>text</code>

func (HTMLRichText) Italic ΒΆ

func (hrt HTMLRichText) Italic(text string) string

Italic generates <i>text</I>

func (HTMLRichText) Pre ΒΆ

func (hrt HTMLRichText) Pre(s string) string

Pre generates <pre>text</pre>

func (HTMLRichText) URL ΒΆ

func (hrt HTMLRichText) URL(text string, url string) string

URL generates <a href="URL>text</a>

type IncomingMessage ΒΆ

type IncomingMessage struct {
	Message              `bson:",inline"`
	From                 User
	Chat                 Chat
	ForwardFrom          *User
	ForwardDate          time.Time
	ForwardFromMessageID int64

	ReplyToMessage        *Message            `bson:"-"`
	ForwardFromChat       *Chat               `json:"forward_from_chat"`       // optional
	EditDate              int                 `json:"edit_date"`               // optional
	Entities              *[]tg.MessageEntity `json:"entities"`                // optional
	Audio                 *tg.Audio           `json:"audio"`                   // optional
	Document              *tg.Document        `json:"document"`                // optional
	Photo                 *[]tg.PhotoSize     `json:"photo"`                   // optional
	Sticker               *tg.Sticker         `json:"sticker"`                 // optional
	Video                 *tg.Video           `json:"video"`                   // optional
	Voice                 *tg.Voice           `json:"voice"`                   // optional
	Caption               string              `json:"caption"`                 // optional
	Contact               *tg.Contact         `json:"contact"`                 // optional
	Location              *tg.Location        `json:"location"`                // optional
	Venue                 *tg.Venue           `json:"venue"`                   // optional
	NewChatMembers        []*User             `json:"new_chat_members"`        // optional
	LeftChatMember        *User               `json:"left_chat_member"`        // optional
	NewChatTitle          string              `json:"new_chat_title"`          // optional
	NewChatPhoto          *[]tg.PhotoSize     `json:"new_chat_photo"`          // optional
	DeleteChatPhoto       bool                `json:"delete_chat_photo"`       // optional
	GroupChatCreated      bool                `json:"group_chat_created"`      // optional
	SuperGroupChatCreated bool                `json:"supergroup_chat_created"` // optional
	ChannelChatCreated    bool                `json:"channel_chat_created"`    // optional
	MigrateToChatID       int64               `json:"migrate_to_chat_id"`      // optional
	MigrateFromChatID     int64               `json:"migrate_from_chat_id"`    // optional
	PinnedMessage         *Message            `json:"pinned_message"`          // optional
	// contains filtered or unexported fields
}

IncomingMessage specifies data that available for incoming message

func (*IncomingMessage) GetCommand ΒΆ

func (m *IncomingMessage) GetCommand() (string, string)

GetCommand parses received message text for bot command. Returns the command and after command text if presented

func (*IncomingMessage) GetFile ΒΆ

func (m *IncomingMessage) GetFile(c *Context, allowedTypes []FileType, maxSize int) (localPath string, fileInfo FileInfo, err error)

func (*IncomingMessage) GetFileInfo ΒΆ

func (m *IncomingMessage) GetFileInfo(c *Context, allowedTypes []FileType) (info FileInfo, err error)

func (*IncomingMessage) IsEventBotAddedToGroup ΒΆ

func (m *IncomingMessage) IsEventBotAddedToGroup() bool

IsEventBotAddedToGroup returns true if user created a new group with bot as member or add the bot to existing group

func (*IncomingMessage) SetCallbackAction ΒΆ

func (m *IncomingMessage) SetCallbackAction(handlerFunc interface{}, args ...interface{}) *IncomingMessage

SetCallbackAction sets the callback func that will be called when user press inline button with Data field !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

func (*IncomingMessage) SetEditAction ΒΆ

func (m *IncomingMessage) SetEditAction(handlerFunc interface{}, args ...interface{}) *IncomingMessage

SetEditAction sets the edited func that will be called when user edit the message !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

func (*IncomingMessage) SetReplyAction ΒΆ

func (m *IncomingMessage) SetReplyAction(handlerFunc interface{}, args ...interface{}) *IncomingMessage

SetReplyAction sets the reply func that will be called when user reply the message !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

type InlineButton ΒΆ

type InlineButton struct {
	Text                         string
	State                        int
	URL                          string `bson:",omitempty"`
	Data                         string `bson:",omitempty"` // maximum 64 bytes
	SwitchInlineQuery            string `bson:",omitempty"` //
	SwitchInlineQueryCurrentChat string `bson:",omitempty"`

	OutOfPagination bool `bson:",omitempty" json:"-"` // Only for the single button in first or last row. Use together with InlineKeyboard.MaxRows – for buttons outside of pagination list
}

InlineButton contains the data to create InlineKeyboard One of URL, Data, SwitchInlineQuery must be specified If more than one specified the first in order of (URL, Data, SwitchInlineQuery) will be used

func (InlineButton) Keyboard ΒΆ

func (button InlineButton) Keyboard() InlineKeyboard

Keyboard generates inline keyboard with 1 button

type InlineButtons ΒΆ

type InlineButtons []InlineButton

InlineButtons is a Shorthand for []InlineButton

func (*InlineButtons) AddURL ΒΆ

func (buttons *InlineButtons) AddURL(url string, text string)

AddURL adds InlineButton with URL to the end of InlineButtons(row)

func (*InlineButtons) Append ΒΆ

func (buttons *InlineButtons) Append(data string, text string)

Append adds 1 or more InlineButton (column) to the end of InlineButtons(row)

func (*InlineButtons) AppendWithState ΒΆ

func (buttons *InlineButtons) AppendWithState(state int, data string, text string)

AppendWithState add the InlineButton with state to the end of InlineButtons(row) Useful for checkbox or to revert the action

func (InlineButtons) Keyboard ΒΆ

func (buttons InlineButtons) Keyboard() InlineKeyboard

Keyboard generates inline keyboard with 1 column

func (*InlineButtons) Markup ΒΆ

func (buttons *InlineButtons) Markup(columns int, state string) InlineKeyboard

Markup generate InlineKeyboard from InlineButtons ([]Button), chunking buttons by columns number, and specifying current keyboard state Keyboard state useful for nested levels to determine current position

func (*InlineButtons) Prepend ΒΆ

func (buttons *InlineButtons) Prepend(data string, text string)

Prepend adds 1 or more InlineButton (column) to the begin of InlineButtons(row)

func (*InlineButtons) PrependWithState ΒΆ

func (buttons *InlineButtons) PrependWithState(state int, data string, text string)

PrependWithState add the InlineButton with state to the begin of InlineButtons(row) Useful for checkbox or to revert the action

type InlineKeyboard ΒΆ

type InlineKeyboard struct {
	Buttons    []InlineButtons // You must specify at least 1 InlineButton in slice
	FixedWidth bool            `bson:",omitempty"` // will add right padding to match all buttons text width
	State      string          // determine the current keyboard's state. Useful to change the behavior for branch cases and make it little thread safe while it is using by several users
	MaxRows    int             `bson:",omitempty"` // Will automatically add next/prev buttons. Zero means no limit
	RowOffset  int             `bson:",omitempty"` // Current offset when using MaxRows
}

InlineKeyboard contains the data to create the Inline keyboard for Telegram and store it in DB

func (*InlineKeyboard) AddPMSwitchButton ΒΆ

func (keyboard *InlineKeyboard) AddPMSwitchButton(b *Bot, text string, param string)

AddPMSwitchButton add the button to switch to PM as a first row in the InlineKeyboard

func (*InlineKeyboard) AppendRows ΒΆ

func (keyboard *InlineKeyboard) AppendRows(buttons ...InlineButtons)

AppendRows adds 1 or more InlineButtons (rows) to the end of InlineKeyboard

func (*InlineKeyboard) EditText ΒΆ

func (keyboard *InlineKeyboard) EditText(buttonData string, newText string)

EditText find the InlineButton in Keyboard by the Data and change the text of that button

func (*InlineKeyboard) Find ΒΆ

func (keyboard *InlineKeyboard) Find(buttonData string) (i, j int, but *InlineButton)

Find the InlineButton in Keyboard by the Data

func (InlineKeyboard) Keyboard ΒΆ

func (keyboard InlineKeyboard) Keyboard() InlineKeyboard

Keyboard generates inline keyboard from inline keyboard :-D

func (*InlineKeyboard) PrependRows ΒΆ

func (keyboard *InlineKeyboard) PrependRows(buttons ...InlineButtons)

PrependRows adds 1 or more InlineButtons (rows) to the begin of InlineKeyboard

type InlineKeyboardMarkup ΒΆ

type InlineKeyboardMarkup interface {
	Keyboard() InlineKeyboard
	// contains filtered or unexported methods
}

InlineKeyboardMarkup allow to generate TG and DB data from different states - (InlineButtons, []InlineButtons and InlineKeyboard)

type Job ΒΆ

type Job struct {
	HandlerFunc interface{} // Must be a func.
	Retries     uint        // Number of retries before fail
	RetryType   int         // JobRetryLinear or JobRetryFibonacci
}

Job 's handler that may be used when scheduling

type Keyboard ΒΆ

type Keyboard []Buttons

Keyboard is a Shorthand for [][]Button

func (*Keyboard) AddRows ΒΆ

func (keyboard *Keyboard) AddRows(buttons ...Buttons)

AddRows adds 1 or more Buttons (rows) to the end of InlineKeyboard

func (Keyboard) Keyboard ΒΆ

func (keyboard Keyboard) Keyboard() Keyboard

Keyboard generate keyboard for keyboard – just to match the KeyboardMarkup interface

type KeyboardMarkup ΒΆ

type KeyboardMarkup interface {
	Keyboard() Keyboard
	// contains filtered or unexported methods
}

KeyboardMarkup allow to generate TG and DB data from different states - (Buttons and Keyboard)

type Location ΒΆ

type Location struct {
	Latitude  float64
	Longitude float64
}

type MarkdownRichText ΒΆ

type MarkdownRichText struct{}

MarkdownRichText produce Markdown that can be sent to Telegram. Not recommended to use because of tricky escaping Use HTMLRichText instead

func (MarkdownRichText) Bold ΒΆ

func (mrt MarkdownRichText) Bold(text string) string

Bold generates *text*

func (MarkdownRichText) Esc ΒΆ

func (mrt MarkdownRichText) Esc(s string) string

Esc escapes '[', ']', '(', ')', "`", "_", "*" with \

func (MarkdownRichText) Fixed ΒΆ

func (mrt MarkdownRichText) Fixed(text string) string

Fixed generates`text`

func (MarkdownRichText) Italic ΒΆ

func (mrt MarkdownRichText) Italic(text string) string

Italic generates _text_

func (MarkdownRichText) Pre ΒΆ

func (mrt MarkdownRichText) Pre(text string) string

Pre generates```text```

func (MarkdownRichText) URL ΒΆ

func (mrt MarkdownRichText) URL(text string, url string) string

URL generates [text](URL)

type Message ΒΆ

type Message struct {
	ID               bson.ObjectId `bson:"_id,omitempty"` // Internal unique BSON ID
	EventID          []string      `bson:",omitempty"`
	MsgID            int           `bson:",omitempty"`         // Telegram Message ID. BotID+MsgID is unique
	InlineMsgID      string        `bson:",omitempty"`         // Telegram InlineMessage ID. ChatID+InlineMsgID is unique
	BotID            int64         `bson:",minsize"`           // TG bot's ID on which behalf message is sending or receiving
	FromID           int64         `bson:",minsize"`           // TG User's ID of sender. Equal to BotID in case of outgoinf message from bot
	ChatID           int64         `bson:",omitempty,minsize"` // Telegram chat's ID, equal to FromID in case of private message
	BackupChatID     int64         `bson:",omitempty,minsize"` // This chat will be used if chatid failed (bot not started or stopped or group deactivated)
	ReplyToMsgID     int           `bson:",omitempty"`         // If this message is reply, contains Telegram's Message ID of original message
	Date             time.Time
	Text             string    `bson:"-"` // Exclude text field
	TextHash         string    `bson:",omitempty"`
	Location         *Location `bson:",omitempty"`
	AntiFlood        bool      `bson:",omitempty"`
	Deleted          bool      `bson:",omitempty"` // f.e. admin can delete the message in supergroup and we can't longer edit or reply on it
	OnCallbackAction string    `bson:",omitempty"` // Func to call on inline button press
	OnCallbackData   []byte    `bson:",omitempty"` // Args to send to this func
	OnReplyAction    string    `bson:",omitempty"` // Func to call on message reply
	OnReplyData      []byte    `bson:",omitempty"` // Args to send to this func
	OnEditAction     string    `bson:",omitempty"` // Func to call on message edit
	OnEditData       []byte    `bson:",omitempty"` // Args to send to this func
	// contains filtered or unexported fields
}

Message represent both outgoing and incoming message data

func (*Message) GetTextHash ΒΆ

func (m *Message) GetTextHash() string

GetTextHash generate MD5 hash of message's text

func (*Message) SetCallbackAction ΒΆ

func (m *Message) SetCallbackAction(handlerFunc interface{}, args ...interface{}) *Message

SetCallbackAction sets the reply func that will be called when user reply the message !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

func (*Message) SetEditAction ΒΆ

func (m *Message) SetEditAction(handlerFunc interface{}, args ...interface{}) *Message

SetEditAction sets the edited func that will be called when user edit the message !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

func (*Message) SetReplyAction ΒΆ

func (m *Message) SetReplyAction(handlerFunc interface{}, args ...interface{}) *Message

SetReplyAction sets the reply func that will be called when user reply the message !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

func (*Message) Update ΒΆ

func (m *Message) Update(db *mgo.Database) error

Update will update existing message in DB

func (*Message) UpdateEventsID ΒΆ

func (m *Message) UpdateEventsID(db *mgo.Database, eventID ...string) error

UpdateEventsID sets the event id and update it in DB

type MgoChange ΒΆ

type MgoChange struct {
	mgo.Change
}

type Mode ΒΆ

type Mode string
const (
	InstanceModeMultiProcessMain    Mode = "multi-main"    // run only the main worker. It will process the outgoing messages queue, route the incoming webhooks to specific services and resolve webpreviews
	InstanceModeMultiProcessService Mode = "multi-service" // run only one the registred services and their workers. Main instance must be running in order to the outgoing TG  messages could be sent
	InstanceModeSingleProcess       Mode = "single"        // run all-in-one process – main worker and all registred services
)

type Module ΒΆ

type Module struct {
	Jobs    []Job
	Actions []interface{}
}

type OAuthProvider ΒΆ

type OAuthProvider struct {
	Service string  // Service name
	BaseURL url.URL `envconfig:"OAUTH_BASEURL"`                // Scheme + Host. Default https://{service.DefaultHost}
	ID      string  `envconfig:"OAUTH_ID" required:"true"`     // OAuth ID
	Secret  string  `envconfig:"OAUTH_SECRET" required:"true"` // OAuth Secret
}

OAuthProvider contains OAuth application info

func (*OAuthProvider) IsSetup ΒΆ

func (o *OAuthProvider) IsSetup() bool

IsSetup returns true if OAuth provider(app,client) has ID and Secret. Should be always true for service's default provider

func (*OAuthProvider) OAuth1Client ΒΆ

func (o *OAuthProvider) OAuth1Client(c *Context) *oauth.Consumer

OAuth1Client returns oauth.Consumer using OAuthProvider details

func (*OAuthProvider) OAuth2Client ΒΆ

func (o *OAuthProvider) OAuth2Client(c *Context) *oauth2.Config

OAuth2Client returns oauth2.Config using OAuthProvider details

func (*OAuthProvider) RedirectURL ΒΆ

func (o *OAuthProvider) RedirectURL() string

RedirectURL returns impersonal Redirect URL, useful when setting up the OAuth Client

type OAuthTokenSource ΒΆ

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

func (*OAuthTokenSource) Token ΒΆ

func (tsw *OAuthTokenSource) Token() (*oauth2.Token, error)

type OAuthTokenStore ΒΆ

type OAuthTokenStore interface {
	Name() string
	GetOAuthAccessToken(user *User) (token string, expireDate *time.Time, err error)
	SetOAuthAccessToken(user *User, token string, expireDate *time.Time) error
	GetOAuthRefreshToken(user *User) (string, error)
	SetOAuthRefreshToken(user *User, token string) error
}

type OutgoingMessage ΒΆ

type OutgoingMessage struct {
	Message              `bson:",inline"`
	KeyboardHide         bool           `bson:",omitempty"`
	ResizeKeyboard       bool           `bson:",omitempty"`
	KeyboardMarkup       Keyboard       `bson:"-"`
	InlineKeyboardMarkup InlineKeyboard `bson:",omitempty"`
	Keyboard             bool           `bson:",omitempty"`
	ParseMode            string         `bson:",omitempty"`
	OneTimeKeyboard      bool           `bson:",omitempty"`
	Selective            bool           `bson:",omitempty"`
	ForceReply           bool           `bson:",omitempty"` // in the private dialog assume user's message as the reply for the last message sent by the bot if bot's message has Reply handler and ForceReply set
	WebPreview           bool           `bson:",omitempty"`
	Silent               bool           `bson:",omitempty"`
	FilePath             string         `bson:",omitempty"`
	FileName             string         `bson:",omitempty"`
	FileType             string         `bson:",omitempty"`
	FileRemoveAfter      bool           `bson:",omitempty"`
	SendAfter            *time.Time     `bson:",omitempty"`
	// contains filtered or unexported fields
}

OutgoingMessage specispecifiesfy data of performing or performed outgoing message

func (*OutgoingMessage) AddEventID ΒΆ

func (m *OutgoingMessage) AddEventID(id ...string) *OutgoingMessage

AddEventID attach one or more event ID. You can use eventid to edit the message in case of additional webhook received or to ignore in case of duplicate

func (*OutgoingMessage) DisableWebPreview ΒΆ

func (m *OutgoingMessage) DisableWebPreview() *OutgoingMessage

DisableWebPreview indicates TG clients to not trying to resolve the URL's in the message

func (*OutgoingMessage) EnableAntiFlood ΒΆ

func (m *OutgoingMessage) EnableAntiFlood() *OutgoingMessage

EnableAntiFlood will check if the message wasn't already sent within last antiFloodSameMessageTimeout seconds

func (*OutgoingMessage) EnableFileRemoveAfter ΒΆ

func (m *OutgoingMessage) EnableFileRemoveAfter() *OutgoingMessage

EnableFileRemoveAfter adds the flag to remove the file after message will be sent

func (*OutgoingMessage) EnableForceReply ΒΆ

func (m *OutgoingMessage) EnableForceReply() *OutgoingMessage

EnableForceReply will automatically set the reply to this message and focus on the input field

func (*OutgoingMessage) EnableHTML ΒΆ

func (m *OutgoingMessage) EnableHTML() *OutgoingMessage

EnableHTML sets parseMode to HTML

func (*OutgoingMessage) EnableMarkdown ΒΆ

func (m *OutgoingMessage) EnableMarkdown() *OutgoingMessage

EnableMarkdown sets parseMode to Markdown

func (*OutgoingMessage) HideKeyboard ΒΆ

func (m *OutgoingMessage) HideKeyboard() *OutgoingMessage

HideKeyboard will hide existing keyboard in the chat where message will be sent

func (*OutgoingMessage) Send ΒΆ

func (m *OutgoingMessage) Send() error

Send put the message to the jobs queue

func (*OutgoingMessage) SetBackupChat ΒΆ

func (m *OutgoingMessage) SetBackupChat(id int64) *OutgoingMessage

SetBackupChat set backup chat id that will be used in case message failed to sent to private chat (f.e. bot stopped or not initialized)

func (*OutgoingMessage) SetCallbackAction ΒΆ

func (m *OutgoingMessage) SetCallbackAction(handlerFunc interface{}, args ...interface{}) *OutgoingMessage

SetCallbackAction sets the callback func that will be called when user press inline button with Data field

func (*OutgoingMessage) SetChat ΒΆ

func (m *OutgoingMessage) SetChat(id int64) *OutgoingMessage

SetChat sets the target chat to send the message

func (*OutgoingMessage) SetDocument ΒΆ

func (m *OutgoingMessage) SetDocument(localPath string, fileName string) *OutgoingMessage

SetDocument adds the file located at localPath with name fileName to the message

func (*OutgoingMessage) SetImage ΒΆ

func (m *OutgoingMessage) SetImage(localPath string, fileName string) *OutgoingMessage

SetImage adds the image file located at localPath with name fileName to the message

func (*OutgoingMessage) SetInlineKeyboard ΒΆ

func (m *OutgoingMessage) SetInlineKeyboard(k InlineKeyboardMarkup) *OutgoingMessage

SetInlineKeyboard sets the inline keyboard markup

func (*OutgoingMessage) SetKeyboard ΒΆ

func (m *OutgoingMessage) SetKeyboard(k KeyboardMarkup, selective bool) *OutgoingMessage

SetKeyboard sets the keyboard markup and Selective bool. If Selective is true keyboard will sent only for target users that you must @mention people in text or specify with SetReplyToMsgID

func (*OutgoingMessage) SetLocation ΒΆ

func (m *OutgoingMessage) SetLocation(latitude, longitude float64) *OutgoingMessage

SetLocation set the location

func (*OutgoingMessage) SetOneTimeKeyboard ΒΆ

func (m *OutgoingMessage) SetOneTimeKeyboard(b bool) *OutgoingMessage

SetOneTimeKeyboard sets the Onetime mode for keyboard. Keyboard will be hided after 1st use

func (*OutgoingMessage) SetParseMode ΒΆ

func (m *OutgoingMessage) SetParseMode(s string) *OutgoingMessage

SetParseMode sets parseMode: 'HTML' and 'markdown' supporting for now

func (*OutgoingMessage) SetReplyAction ΒΆ

func (m *OutgoingMessage) SetReplyAction(handlerFunc interface{}, args ...interface{}) *OutgoingMessage

SetReplyAction sets the reply func that will be called when user reply the message !!! Please note that you must omit first arg *integram.Context, because it will be automatically prepended as message reply received and will contain actual context

func (*OutgoingMessage) SetReplyToMsgID ΒΆ

func (m *OutgoingMessage) SetReplyToMsgID(id int) *OutgoingMessage

SetReplyToMsgID sets parseMode: 'HTML' and 'markdown' supporting for now

func (*OutgoingMessage) SetResizeKeyboard ΒΆ

func (m *OutgoingMessage) SetResizeKeyboard(b bool) *OutgoingMessage

SetResizeKeyboard sets the ResizeKeyboard to collapse keyboard wrapper to match the actual underneath keyboard

func (*OutgoingMessage) SetSelective ΒΆ

func (m *OutgoingMessage) SetSelective(b bool) *OutgoingMessage

SetSelective sets the Selective mode for the keyboard. If Selective is true keyboard make sure to @mention people in text or specify message to reply with SetReplyToMsgID

func (*OutgoingMessage) SetSendAfter ΒΆ

func (m *OutgoingMessage) SetSendAfter(after time.Time) *OutgoingMessage

SetSendAfter set the time to send the message

func (*OutgoingMessage) SetSilent ΒΆ

func (m *OutgoingMessage) SetSilent(b bool) *OutgoingMessage

SetSilent turns off notifications on iOS and make it silent on Android

func (*OutgoingMessage) SetText ΒΆ

func (m *OutgoingMessage) SetText(text string) *OutgoingMessage

SetText set the text of message to sent In case of documents and photo messages this text will be used in the caption

func (*OutgoingMessage) SetTextFmt ΒΆ

func (m *OutgoingMessage) SetTextFmt(text string, a ...interface{}) *OutgoingMessage

SetTextFmt is a shorthand for SetText(fmt.Sprintf("%s %s %s", a, b, c))

type Service ΒΆ

type Service struct {
	Name        string // Service lowercase name
	NameToPrint string // Service print name
	ImageURL    string // Service thumb image to use in WebPreview if there is no image specified in message. Useful for non-interactive integrations that uses main Telegram's bot.

	DefaultBaseURL url.URL        // Cloud(not self-hosted) URL
	DefaultOAuth1  *DefaultOAuth1 // Cloud(not self-hosted) app data
	DefaultOAuth2  *DefaultOAuth2 // Cloud(not self-hosted) app data
	OAuthRequired  bool           // Is OAuth required in order to receive webhook updates

	JobsPool int // Worker pool to be created for service. Default to 1 worker. Workers will be inited only if jobs types are available

	JobOldPrefix string
	Jobs         []Job // Job types that can be scheduled

	Modules []Module // you can inject modules and use it across different services

	// Functions that can be triggered after message reply, inline button press or Auth success f.e. API query to comment the card on replying.
	// Please note that first argument must be an *integram.Context. Because all actions is triggered in some context.
	// F.e. when using action with onReply triggered with context of replied message (user, chat, bot).
	Actions []interface{}

	// Handler to produce the user/chat search query based on the http request. Set queryChat to true to perform chat search
	TokenHandler func(ctx *Context, request *WebhookContext) (queryChat bool, bsonQuery map[string]interface{}, err error)

	// Handler to receive webhooks from outside
	WebhookHandler func(ctx *Context, request *WebhookContext) error

	// Handler to receive already prepared data. Useful for manual interval grabbing jobs
	EventHandler func(ctx *Context, data interface{}) error

	// Worker wil be run in goroutine after service and framework started. In case of error or crash it will be restarted
	Worker func(ctx *Context) error

	// Handler to receive new messages from Telegram
	TGNewMessageHandler func(ctx *Context) error

	// Handler to receive new messages from Telegram
	TGEditMessageHandler func(ctx *Context) error

	// Handler to receive inline queries from Telegram
	TGInlineQueryHandler func(ctx *Context) error

	// Handler to receive chosen inline results from Telegram
	TGChosenInlineResultHandler func(ctx *Context) error

	OAuthSuccessful func(ctx *Context) error
	// Can be used for services with tiny load
	UseWebhookInsteadOfLongPolling bool

	// Can be used to automatically clean up old messages metadata from database
	RemoveMessagesOlderThan *time.Duration
	// contains filtered or unexported fields
}

Service configuration

func (*Service) Bot ΒΆ

func (s *Service) Bot() *Bot

Bot returns corresponding bot for the service

func (*Service) DefaultOAuthProvider ΒΆ

func (s *Service) DefaultOAuthProvider() *OAuthProvider

DefaultOAuthProvider returns default(means cloud-based) OAuth client

func (*Service) DoJob ΒΆ

func (s *Service) DoJob(handlerFunc interface{}, data ...interface{}) (*jobs.Job, error)

DoJob queues the job to run. The job must be registred in Service's config (Jobs field). Arguments must be identically types with hudlerFunc's input args

func (*Service) EmptyContext ΒΆ

func (s *Service) EmptyContext() *Context

EmptyContext returns context on behalf of service without user/chat relation

func (*Service) Log ΒΆ

func (s *Service) Log() *log.Entry

Log returns logrus instance with related context info attached

func (*Service) SheduleJob ΒΆ

func (s *Service) SheduleJob(handlerFunc interface{}, priority int, time time.Time, data ...interface{}) (*jobs.Job, error)

SheduleJob schedules the job for specific time with specific priority. The job must be registred in Service's config (Jobs field). Arguments must be identically types with hudlerFunc's input args

func (*Service) TriggerEventHandler ΒΆ

func (s *Service) TriggerEventHandler(queryChat bool, bsonQuery map[string]interface{}, data interface{}) error

TriggerEventHandler perform search query and trigger EventHandler in context of each chat/user

type Servicer ΒΆ

type Servicer interface {
	Service() *Service
}

Servicer is interface to match service's config from which the service itself can be produced

type StatKey ΒΆ

type StatKey string
const (
	StatInlineQueryAnswered        StatKey = "iq_answered"
	StatInlineQueryNotAnswered     StatKey = "iq_not_answered"
	StatInlineQueryTimeouted       StatKey = "iq_timeouted"
	StatInlineQueryCanceled        StatKey = "iq_canceled"
	StatInlineQueryChosen          StatKey = "iq_chosen"
	StatInlineQueryProcessingError StatKey = "iq_error"

	StatWebhookHandled               StatKey = "wh_handled"
	StatWebhookProducedMessageToChat StatKey = "wh_message"
	StatWebhookProcessingError       StatKey = "wh_error"

	StatIncomingMessageAnswered    StatKey = "im_replied"
	StatIncomingMessageNotAnswered StatKey = "im_not_replied"

	StatOAuthSuccess StatKey = "oauth_success"
)

type User ΒΆ

type User struct {
	ID        int64 `bson:"_id"`
	FirstName string
	LastName  string `bson:",omitempty"`
	UserName  string `bson:",omitempty"`
	Tz        string
	Lang      string
	// contains filtered or unexported fields
}

User information initiated from TG

func (*User) AddChatToHook ΒΆ

func (user *User) AddChatToHook(chatID int64) error

AddChatToHook adds the target chat to user's existing hook

func (*User) AuthTempToken ΒΆ

func (user *User) AuthTempToken() string

AuthTempToken returns Auth token used in OAuth process to associate TG user with OAuth creditianals

func (*User) Cache ΒΆ

func (user *User) Cache(key string, res interface{}) (exists bool)

Cache returns if User's cache for specific key exists and try to bind it to res

func (*User) Chat ΒΆ

func (user *User) Chat() Chat

func (*User) ClearAllCacheKeys ΒΆ

func (user *User) ClearAllCacheKeys() error

ClearAllCacheKeys removes all User's cache keys

func (*User) IsPrivateStarted ΒΆ

func (user *User) IsPrivateStarted() bool

IsPrivateStarted indicates if user started the private dialog with a bot (e.g. pressed the start button)

func (*User) Mention ΒΆ

func (u *User) Mention() string

Mention returns @username if available. First + Last name otherwise

func (*User) OAuthHTTPClient ΒΆ

func (user *User) OAuthHTTPClient() *http.Client

OAuthHTTPClient returns HTTP client with Bearer authorization headers

func (*User) OAuthToken ΒΆ

func (user *User) OAuthToken() string

OAuthToken returns OAuthToken for service

func (*User) OAuthTokenSource ΒΆ

func (user *User) OAuthTokenSource() (oauth2.TokenSource, error)

OAuthTokenSource returns OAuthTokenSource to use within http client to get OAuthToken

func (*User) OAuthTokenStore ΒΆ

func (user *User) OAuthTokenStore() string

OAuthTokenStore returns current OAuthTokenStore name used to get/set access and refresh tokens

func (*User) OAuthValid ΒΆ

func (user *User) OAuthValid() bool

OAuthValid checks if OAuthToken for service is set

func (*User) OauthInitURL ΒΆ

func (user *User) OauthInitURL() string

OauthInitURL used in OAuth process as returning URL

func (*User) OauthRedirectURL ΒΆ

func (user *User) OauthRedirectURL() string

OauthRedirectURL used in OAuth process as returning URL

func (*User) ResetOAuthToken ΒΆ

func (user *User) ResetOAuthToken() error

ResetOAuthToken reset OAuthToken for service

func (*User) SaveSetting ΒΆ

func (user *User) SaveSetting(key string, value interface{}) error

SaveSetting sets User's setting for service with specific key

func (*User) SaveSettings ΒΆ

func (user *User) SaveSettings(allSettings interface{}) error

SaveSettings save User's setting for service

func (*User) ServiceHookToken ΒΆ

func (user *User) ServiceHookToken() string

ServiceHookToken returns User's hook token to use in webhook handling

func (*User) ServiceHookURL ΒΆ

func (user *User) ServiceHookURL() string

ServiceHookURL returns User's webhook URL for service to use in webhook handling Used in case when incoming webhooks despatching on the user behalf to chats

func (*User) SetAfterAuthAction ΒΆ

func (user *User) SetAfterAuthAction(handlerFunc interface{}, args ...interface{}) error

SetAfterAuthAction sets the handlerFunc and it's args that will be triggered on success user Auth. F.e. you can use it to resume action interrupted because user didn't authed !!! Please note that you must ommit first arg *integram.Context, because it will be automatically prepended on auth success and will contains actual action context

func (*User) SetCache ΒΆ

func (user *User) SetCache(key string, val interface{}, ttl time.Duration) error

SetCache set the User's cache with specific key and TTL

func (*User) SetOAuthTokenStore ΒΆ

func (user *User) SetOAuthTokenStore(storeName string) error

SetOAuthTokenStore stores the new name for OAuth Store to get/set access and refresh tokens

func (*User) Setting ΒΆ

func (user *User) Setting(key string) (result interface{}, exists bool)

Setting returns Chat's setting for service with specific key

func (*User) Settings ΒΆ

func (user *User) Settings(out interface{}) error

Settings bind User's settings for service to the interface

func (*User) String ΒΆ

func (u *User) String() string

Method to implement String interface

func (*User) TzLocation ΒΆ

func (u *User) TzLocation() *time.Location

TzLocation retrieve User's timezone if stored in DB

func (*User) UpdateCache ΒΆ

func (user *User) UpdateCache(key string, update interface{}, res interface{}) error

UpdateCache updates the per User cache using MongoDB Update query

type WebhookContext ΒΆ

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

WebhookContext is passed to WebhookHandler of service

func (*WebhookContext) File ΒΆ

func (wc *WebhookContext) File(path string)

File serves local file

func (*WebhookContext) FirstParse ΒΆ

func (wc *WebhookContext) FirstParse() bool

FirstParse indicates that the request body is not yet readed

func (*WebhookContext) Form ΒΆ

func (wc *WebhookContext) Form() uurl.Values

Form decodes the POST form in the request's body to the out interface

func (*WebhookContext) FormValue ΒΆ

func (wc *WebhookContext) FormValue(key string) string

FormValue return form data with specific key

func (*WebhookContext) Get ΒΆ

func (wc *WebhookContext) Get(key string) (interface{}, bool)

func (*WebhookContext) Header ΒΆ

func (wc *WebhookContext) Header(key string) string

Header returns the request header with the name

func (*WebhookContext) Headers ΒΆ

func (wc *WebhookContext) Headers() map[string][]string

Headers returns the headers of request

func (*WebhookContext) HookID ΒΆ

func (wc *WebhookContext) HookID() string

HookID returns the HookID from the URL

func (*WebhookContext) JSON ΒΆ

func (wc *WebhookContext) JSON(out interface{}) error

JSON decodes the JSON in the request's body to the out interface

func (*WebhookContext) Param ΒΆ

func (wc *WebhookContext) Param(s string) string

Param return param from url

func (*WebhookContext) QueryValue ΒΆ

func (wc *WebhookContext) QueryValue(key string) string

FormValue return form data with specific key

func (*WebhookContext) RAW ΒΆ

func (wc *WebhookContext) RAW() (*[]byte, error)

RAW returns request's body

func (*WebhookContext) Redirect ΒΆ

func (wc *WebhookContext) Redirect(code int, s string)

Redirect send the Location header

func (*WebhookContext) Request ΒΆ

func (wc *WebhookContext) Request() *http.Request

func (*WebhookContext) RequestID ΒΆ

func (wc *WebhookContext) RequestID() string

RequestID returns the unique generated request ID

func (*WebhookContext) Response ΒΆ

func (wc *WebhookContext) Response(code int, s string)

Header returns the request header with the name

func (*WebhookContext) Store ΒΆ

func (wc *WebhookContext) Store(key string, b interface{})

func (*WebhookContext) Writer ΒΆ

func (wc *WebhookContext) Writer() http.ResponseWriter

Directories ΒΆ

Path Synopsis
cmd
modules

Jump to

Keyboard shortcuts

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