integram

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

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

Go to latest
Published: Oct 11, 2017 License: GPL-3.0 Imports: 36 Imported by: 0

README

Integram 2.0

Framework and platform for integrating services into Telegram using official Bot API

GoDoc CircleCI

Screencast

How to use Integram

Just use this links to add integrations you are interested in

Not found you favorite service? 🤘 Vote for it

Running Integram on your side

You can run Integram on your own server.

  • Create the main.go file (example is below)
  • Use your own bot created with Botfather.
  • For the each service you are want to use you need to create an OAuth client(application) in it
  • Set environment variable GOPATH to the directory contains main.go file
  • Run go get github.com/requilence/integram
  • Specify environment variables:
    • INTEGRAM_PORT - if set to 443, integram.crt and integram.key must be presented in the root
    • INTEGRAM_BASE_URL - the base URL the host accessible with, f.e. https://integram.org
  • Run go run main.go or go build && ./integram
  • In order to run test with go test you need to set some environment variables:
    • INTEGRAM_TEST_BOT_TOKEN - to perform some non-emulated Telegram tests
    • INTEGRAM_TEST_USER - Telegram user id that have a dialog with this bot

main.go example

package main

import (
	"github.com/requilence/integram"
	"github.com/requilence/integram/services/trello"
	"github.com/requilence/integram/services/gitlab"
)

func main() {
	integram.Debug=true
	
	integram.Register(
        trello.Config{
            integram.OAuthProvider{
                ID:     "TRELLO_APP_KEY",
                Secret: "TRELLO_APP_SECRET",
            },
        },
        "BOT_TOKEN_PROVIDED_BY_@BOTFATHER",
    )

    integram.Register(
        gitlab.Config{
            integram.OAuthProvider{
                ID:     "GITLAB_APP_ID",
                Secret: "GITLAB_APP_SECRET",
            },
        },
        "BOT_TOKEN_PROVIDED_BY_@BOTFATHER",
    )

		
	integram.Run()
}
Dependencies and vendor directory

All dependencies come with package itself and may be modified directly (see the Third party libraries)

Requirements

Go 1.5+, MongoDB 3.2+ (for data), Redis 3.2.0+ (for jobs queue)

Contributing

Feel free to send PRs. If you want to contribute new service integration, please create the issue first. Just to make sure developing is not already in progress.

Third party libraries

* - package source is modified

License

Code available on 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 BaseURL = "https://integram.org"

BaseURL of the Integram instance to handle the webhooks and resolve webpreviews properly

View Source
var Debug = false

Debug used to control logging verbose mode

View Source
var ErrorFlood = fmt.Errorf("Too many messages. You could not send the same message more than once per %d sec. The number of messages sent to chat must not exceed %d in %d sec", antiFloodTimeout, antiFloodChatLimit, antiFloodChatDuration)
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

View Source
var WorkerSuffix = ""

Functions

func Logger

func Logger() *log.Logger

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 Run

func Run()

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

func SeviceWorkerAutorespawnGoroutine

func SeviceWorkerAutorespawnGoroutine(s *Service)

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 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) 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) 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) 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) 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) 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) 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)
}

DefaultOAuth2 is the default OAuth2 config for the service

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
	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
	NewChatMember         *User               `json:"new_chat_member"`         // 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, fileName string, fileType FileType, 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 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:",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 OAuthProvider

type OAuthProvider struct {
	Service string  // Service name
	BaseURL url.URL // Scheme + Host. Default https://{service.DefaultHost}
	ID      string  // OAuth ID
	Secret  string  // 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 OutgoingMessage

type OutgoingMessage struct {
	Message              `bson:",inline"`
	TextHash             string         `bson:",omitempty"`
	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"`
	// 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 antiFloodTimeout 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) 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) 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

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

	// 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
}

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 User

type User struct {
	ID        int64 `bson:"_id"`
	FirstName string
	LastName  string `bson:",omitempty"`
	UserName  string `bson:",omitempty"`
	Tz        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) 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) 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) 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) 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) 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) 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{})

Directories

Path Synopsis
services
Package url created to provide Marshaling and Unmarshaling for url.URL
Package url created to provide Marshaling and Unmarshaling for url.URL

Jump to

Keyboard shortcuts

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