botsfw

package
v0.40.4 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2024 License: Apache-2.0 Imports: 22 Imported by: 19

Documentation

Index

Constants

View Source
const (
	// MessageTextBotDidNotUnderstandTheCommand is an i18n constant
	MessageTextBotDidNotUnderstandTheCommand = "MessageTextBotDidNotUnderstandTheCommand"

	// MessageTextOopsSomethingWentWrong is an i18n constant
	MessageTextOopsSomethingWentWrong = "MessageTextOopsSomethingWentWrong"
)
View Source
const (
	// BotAPISendMessageOverHTTPS indicates message should be sent over HTTPS
	BotAPISendMessageOverHTTPS = BotAPISendMessageChannel("https")

	// BotAPISendMessageOverResponse indicates message should be sent in HTTP response
	BotAPISendMessageOverResponse = BotAPISendMessageChannel("response")
)
View Source
const DefaultTitle = "" //

DefaultTitle key

View Source
const NoMessageToSend = "<NO_MESSAGE_TO_SEND>"

NoMessageToSend returned explicitly if we don't want to reply to user intput

View Source
const ShortTitle = "short_title"

ShortTitle key

Variables

View Source
var EnvLocal = "local" // TODO: Consider adding this to init interface of setting config values
View Source
var EnvProduction = "production" // TODO: Consider adding this to init interface of setting config values
View Source
var (
	// ErrEntityNotFound is returned if entity not found in storage
	ErrEntityNotFound = errors.New("bots-framework: no such entity")
)
View Source
var ErrNoCommandsMatched = errors.New("no commands matched")
View Source
var ErrNotImplemented = errors.New("not implemented")

ErrNotImplemented if some feature is not implemented yet

View Source
var ErrUnknownBot = errors.New("unknown bot")
View Source
var IgnoreCommand = Command{
	Code: "bots.IgnoreCommand",
	Action: func(_ WebhookContext) (m MessageFromBot, err error) {
		return
	},
	CallbackAction: func(_ WebhookContext, _ *url.URL) (m MessageFromBot, err error) {
		return
	},
}

IgnoreCommand is a command that does nothing

Functions

func CommandTextNoTrans

func CommandTextNoTrans(title, icon string) string

CommandTextNoTrans returns a title for a command (pre-translated)

func NotFoundHandler

func NotFoundHandler(w http.ResponseWriter, _ *http.Request)

NotFoundHandler returns HTTP status code 404

func PingHandler

func PingHandler(w http.ResponseWriter, r *http.Request)

PingHandler returns 'Pong' back to user

func SetAccessGranted

func SetAccessGranted(whc WebhookContext, value bool) (err error)

SetAccessGranted marks current context as authenticated

Types

type AppContext added in v0.35.0

type AppContext interface {
	botsdal.AppUserDal

	i18n.TranslationContext
}

AppContext is a context for an app that uses the botsfw

type AppUserGetter added in v0.18.0

type AppUserGetter = func(
	ctx context.Context,
	tx dal.ReadSession,
	botID string,
	appUserID string,
) (
	appUser record.DataWithID[string, botsfwmodels.AppUserData],
	err error,
)

type Attachment

type Attachment interface {
	AttachmentType() AttachmentType
}

Attachment to a bot message

type AttachmentType

type AttachmentType int

AttachmentType to a bot message

const (
	// AttachmentTypeNone says there is no attachment
	AttachmentTypeNone AttachmentType = iota

	// AttachmentTypeAudio is for audio attachments
	AttachmentTypeAudio

	// AttachmentTypeFile is for file attachments
	AttachmentTypeFile

	// AttachmentTypeImage is for image attachments
	AttachmentTypeImage

	// AttachmentTypeVideo is for video attachments
	AttachmentTypeVideo
)

type BotAPISendMessageChannel

type BotAPISendMessageChannel string

BotAPISendMessageChannel specifies messenger channel

type BotContext

type BotContext struct {
	AppContext  AppContext
	BotHost     BotHost      // describes current bot app host environment
	BotSettings *BotSettings // keeps parameters of a bot that are static and are not changed in runtime
}

BotContext binds a bot to a specific hosting environment

func NewBotContext

func NewBotContext(botHost BotHost, botSettings *BotSettings) *BotContext

NewBotContext creates current bot host & settings

type BotContextProvider added in v0.35.0

type BotContextProvider interface {
	// GetBotContext returns BotContext by platformID & botID
	GetBotContext(ctx context.Context, platformID botsfwconst.Platform, botID string) (botContext *BotContext, err error)
}

BotContextProvider provides BotContext by platformID & botID

func NewBotContextProvider added in v0.35.0

func NewBotContextProvider(botHost BotHost, appContext AppContext, botSettingProvider BotSettingsProvider) BotContextProvider

type BotHost

type BotHost interface {

	// Context returns a context.Context for a request. We need this as some platforms (as Google App Engine Standard)
	// require usage of a context with a specific wrapper
	Context(r *http.Request) context.Context

	// GetHTTPClient returns HTTP client for current host
	// We need this as some platforms (as Google App Engine Standard) require setting http client in a specific way.
	GetHTTPClient(c context.Context) *http.Client
}

BotHost describes current bot app host environment

type BotInputProvider

type BotInputProvider interface {
	// Input returns a webhook input from a specific bot interface (Telegram, FB Messenger, Viber, etc.)
	Input() botinput.WebhookInput
}

BotInputProvider provides an input from a specific bot interface (Telegram, FB Messenger, Viber, etc.)

type BotMessage

type BotMessage interface {
	BotMessageType() BotMessageType
}

BotMessage is an output message from bot to user

type BotMessageType

type BotMessageType int

BotMessageType defines type of an output message from bot to user

const (
	// BotMessageTypeUndefined unknown type
	BotMessageTypeUndefined BotMessageType = iota
	// BotMessageTypeCallbackAnswer sends callback answer
	BotMessageTypeCallbackAnswer
	// BotMessageTypeInlineResults sends inline results
	BotMessageTypeInlineResults
	// BotMessageTypeText sends text reply
	BotMessageTypeText
	// BotMessageTypeEditMessage edit previously sent message
	BotMessageTypeEditMessage
	// BotMessageTypeLeaveChat commands messenger to kick off bot from a botChat
	BotMessageTypeLeaveChat
	// BotMessageTypeExportChatInviteLink sends invite link
	BotMessageTypeExportChatInviteLink
)

type BotPlatform

type BotPlatform interface {

	// ID returns bot platform ID like 'telegram', 'fbmessenger', 'viber', etc.
	ID() string

	// Version returns a version of a bot platform adapter. It is used for debugging purposes.
	Version() string
}

BotPlatform describes current bot platform

type BotProfile added in v0.18.0

type BotProfile interface {
	ID() string
	Router() *WebhooksRouter
	DefaultLocale() i18n.Locale
	SupportedLocales() []i18n.Locale
	NewBotChatData() botsfwmodels.BotChatData
	NewPlatformUserData() botsfwmodels.PlatformUserData
	NewAppUserData() botsfwmodels.AppUserData // TODO: Can we get rit of it and instead use GetAppUserByID/CreateAppUser?
}

func NewBotProfile added in v0.18.0

func NewBotProfile(
	id string,
	router *WebhooksRouter,
	newBotChatData func() botsfwmodels.BotChatData,
	newBotUserData func() botsfwmodels.PlatformUserData,
	newAppUserData func() botsfwmodels.AppUserData,
	getAppUserByID AppUserGetter,
	defaultLocale i18n.Locale,
	supportedLocales []i18n.Locale,
) BotProfile

type BotRecordsFieldsSetter added in v0.16.0

type BotRecordsFieldsSetter interface {

	// Platform returns platform name, e.g. 'telegram', 'fbmessenger', etc.
	// This method is for debug pruposes and to indicate that different platforms may have different fields
	// Though '*' can be used for a generic setter that works for all platforms
	// If both '*' and platform specific setters are defined, the generic setter will be used first.
	Platform() string

	// SetAppUserFields sets fields of app user record
	SetAppUserFields(appUser botsfwmodels.AppUserData, sender botinput.WebhookSender) error

	// SetBotUserFields sets fields of bot user record
	SetBotUserFields(botUser botsfwmodels.PlatformUserData, sender botinput.WebhookSender, botID, botUserID, appUserID string) error

	// SetBotChatFields sets fields of bot botChat record
	// TODO: document isAccessGranted parameter
	SetBotChatFields(botChat botsfwmodels.BotChatData, chat botinput.WebhookChat, botID, botUserID, appUserID string, isAccessGranted bool) error
}

type BotSettings

type BotSettings struct {

	// Platform is a platform that bot is running on
	// E.g.: Telegram, Viber, Facebook Messenger, WhatsApp, etc.
	Platform botsfwconst.Platform

	// Env is an environment where bot is running
	// E.g.: Production/Live, Local/Dev, Staging, etc.
	Env string

	// Profile is a bot profile that defines bot's behavior
	// It includes commands router and some other settings
	// More in BotProfile documentation.
	Profile BotProfile

	// Code is a human-readable ID of a bot.
	// When displayed it is usually prefixed with @.
	// For example:
	//   - @listus_bot for https://t.me/listus_bot
	Code string

	// ID is a bot-platform ID of a bot. For example, it could be a GUID.
	// Not all platforms use it. For example Telegram doesn't use it.
	ID string

	// Token is used to authenticate bot with a platform when it is not responding to a webhook
	// but calling platform APIs directly.
	Token string

	// PaymentToken is used to process payments on bot platform
	PaymentToken string

	// PaymentTestToken is used to process test payments on bot platform
	PaymentTestToken string

	// VerifyToken is used by Facebook Messenger - TODO: Document how it is used and add a link to Facebook docs
	VerifyToken string

	// GAToken is Google Analytics token - TODO: Refactor tu support multiple or move out
	GAToken string

	// Locale is a default locale for a bot.
	// While a bot profile can support multiple locales a bot can be dedicated to a specific country/language
	Locale i18n.Locale

	// GetDatabase returns connection to a database assigned to a bot.
	// You can use same database for multiple bots
	// but if you need you can use different databases for different bots.
	// It's up to bots creator how to map bots to a database.
	// In most cases a single DB is used for all bots.
	GetDatabase DbGetter
	// contains filtered or unexported fields
}

BotSettings keeps parameters of a bot that are static and are not changed in runtime

func NewBotSettings

func NewBotSettings(
	platform botsfwconst.Platform,
	environment string,
	profile BotProfile,
	code, id, token, gaToken string,
	locale i18n.Locale,
	getDatabase DbGetter,
	getAppUser AppUserGetter,
) BotSettings

NewBotSettings configures bot application

func (BotSettings) GetAppUserByID added in v0.18.0

func (v BotSettings) GetAppUserByID(ctx context.Context, tx dal.ReadSession, appUserID string) (appUser record.DataWithID[string, botsfwmodels.AppUserData], err error)

type BotSettingsBy added in v0.35.0

type BotSettingsBy struct {

	// ByCode keeps settings by bot code - it is a human-readable ID of a bot
	ByCode map[string]*BotSettings

	// ByID keeps settings by bot ID - it is a machine-readable ID of a bot.
	ByID map[string]*BotSettings

	ByProfile map[string][]*BotSettings
}

SettingsBy keeps settings per different keys (ID, code, API token, Locale) TODO: Decide if it should have map[string]*BotSettings instead of map[string]BotSettings

func NewBotSettingsBy

func NewBotSettingsBy(bots ...BotSettings) (settingsBy BotSettingsBy)

NewBotSettingsBy create settings per different keys (ID, code, API token, Locale)

type BotSettingsProvider added in v0.35.0

type BotSettingsProvider func(ctx context.Context) BotSettingsBy

SettingsProvider returns settings per different keys (ID, code, API token, Locale)

type BotState

type BotState interface {
	IsNewerThen(chatEntity botsfwmodels.BotChatData) bool
}

BotState provides state of the bot (TODO: document how is used)

type BotUserCreator added in v0.18.0

type BotUserCreator func(c context.Context, botID string, apiUser botinput.WebhookActor) (botsfwmodels.PlatformUserData, error)

type CallbackAction

type CallbackAction func(whc WebhookContext, callbackUrl *url.URL) (m MessageFromBot, err error)

CallbackAction defines a callback action bot can perform in response to a callback command

type ChatIntID

type ChatIntID int64

ChatIntID returns botChat ID as unique integer

func (ChatIntID) ChatUID

func (chatUID ChatIntID) ChatUID() string

ChatUID returns botChat ID as unique string

type ChatUID

type ChatUID interface {
	ChatUID() string
}

ChatUID returns botChat ID as unique string

type Command

type Command struct {
	InputTypes     []botinput.WebhookInputType // Instant match if != WebhookInputUnknown && == whc.InputTypes()
	Icon           string
	Replies        []Command
	Code           string
	Title          string
	Titles         map[string]string
	ExactMatch     string
	Commands       []string
	Matcher        CommandMatcher
	Action         CommandAction
	CallbackAction CallbackAction
}

Command defines command metadata and action

func NewCallbackCommand

func NewCallbackCommand(code string, action CallbackAction) Command

NewCallbackCommand create a definition of a callback command

func NewInlineQueryCommand

func NewInlineQueryCommand(code string, action CommandAction) Command

func (Command) DefaultTitle

func (c Command) DefaultTitle(whc WebhookContext) string

DefaultTitle returns a default title for a command in current Locale

func (Command) String

func (c Command) String() string

func (Command) TitleByKey

func (c Command) TitleByKey(key string, whc WebhookContext) string

TitleByKey returns a short/long title for a command in current Locale

type CommandAction

type CommandAction func(whc WebhookContext) (m MessageFromBot, err error)

CommandAction defines an action bot can perform in response to a command

type CommandMatcher

type CommandMatcher func(Command, WebhookContext) bool

CommandMatcher returns true if action is matched to user input

type CreateWebhookContextArgs added in v0.18.0

type CreateWebhookContextArgs struct {
	HttpRequest  *http.Request // TODO: Can we get rid of it? Needed for botHost.GetHTTPClient()
	AppContext   AppContext
	BotContext   BotContext
	WebhookInput botinput.WebhookInput
	Tx           dal.ReadwriteTransaction
	//BotCoreStores botsfwdal.DataAccess
	GaMeasurement GaQueuer
}

func NewCreateWebhookContextArgs added in v0.18.0

func NewCreateWebhookContextArgs(
	httpRequest *http.Request,
	appContext AppContext,
	botContext BotContext,
	webhookInput botinput.WebhookInput,
	tx dal.ReadwriteTransaction,

	gaMeasurement GaQueuer,
) CreateWebhookContextArgs

type DbGetter added in v0.18.0

type DbGetter = func(ctx context.Context) (db dal.DB, err error)

type EntryInput

type EntryInput struct {
	Entry botinput.WebhookEntry
	Input botinput.WebhookInput
}

EntryInput provides information on parsed input from bot API request

func (*EntryInput) MarshalJSON

func (j *EntryInput) MarshalJSON() ([]byte, error)

MarshalJSON marshal bytes to json - template

func (*EntryInput) MarshalJSONBuf

func (j *EntryInput) MarshalJSONBuf(buf fflib.EncodingBuffer) error

MarshalJSONBuf marshal buff to json - template

func (*EntryInput) UnmarshalJSON

func (j *EntryInput) UnmarshalJSON(input []byte) error

UnmarshalJSON umarshall json - template of ffjson

func (*EntryInput) UnmarshalJSONFFLexer

func (j *EntryInput) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

UnmarshalJSONFFLexer fast json unmarshall - template ffjson

type EntryInputs

type EntryInputs struct {
	Entry  botinput.WebhookEntry
	Inputs []botinput.WebhookInput
}

EntryInputs provides information on parsed inputs from bot API request

func (*EntryInputs) MarshalJSON

func (j *EntryInputs) MarshalJSON() ([]byte, error)

MarshalJSON marshal bytes to json - template

func (*EntryInputs) MarshalJSONBuf

func (j *EntryInputs) MarshalJSONBuf(buf fflib.EncodingBuffer) error

MarshalJSONBuf marshal buff to json - template

func (*EntryInputs) UnmarshalJSON

func (j *EntryInputs) UnmarshalJSON(input []byte) error

UnmarshalJSON umarshall json - template of ffjson

func (*EntryInputs) UnmarshalJSONFFLexer

func (j *EntryInputs) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

UnmarshalJSONFFLexer fast json unmarshall - template ffjson

type ErrAuthFailed

type ErrAuthFailed string

ErrAuthFailed raised if authentication failed

func (ErrAuthFailed) Error

func (e ErrAuthFailed) Error() string

type ExecutionContext added in v0.25.0

type ExecutionContext interface {
	Context() context.Context
}

ExecutionContext TODO: either specify clear purpose and added value or remove

type GaContext

type GaContext interface {
	GaQueuer
	// Flush() error
	GaCommon() gamp.Common
	GaEvent(category, action string) *gamp.Event
	GaEventWithLabel(category, action, label string) *gamp.Event
}

GaContext provides context to Google Analytics - TODO: we should have an abstraction for analytics

type GaQueuer

type GaQueuer interface {
	Queue(message gamp.Message) error
}

GaQueuer queues messages for sending to Google Analytics

type HttpRouter added in v0.11.0

type HttpRouter interface {
	Handle(method string, path string, handle http.HandlerFunc)
}

type InputMessage

type InputMessage interface {
	Text() string
}

InputMessage represents single input message

type MessageFormat

type MessageFormat int

MessageFormat specify formatting of a text message to BOT (e.g. Text, HTML, MarkDown)

const (
	// MessageFormatText is for text messages
	MessageFormatText MessageFormat = iota
	// MessageFormatHTML is for HTML messages
	MessageFormatHTML
	// MessageFormatMarkdown is for markdown messages
	MessageFormatMarkdown
)

type MessageFromBot

type MessageFromBot struct {
	ResponseChannel    BotAPISendMessageChannel `json:"-,omitempty"` // For debug purposes
	ToChat             ChatUID                  `json:",omitempty"`
	TextMessageFromBot                          // This is a shortcut to MessageFromBot{}.BotMessage = TextMessageFromBot{text: "abc"}
	BotMessage         BotMessage               `json:",omitempty"`
}

MessageFromBot keeps all the details of answer from bot to user

func (*MessageFromBot) MarshalJSON

func (j *MessageFromBot) MarshalJSON() ([]byte, error)

MarshalJSON marshal bytes to json - template

func (*MessageFromBot) MarshalJSONBuf

func (j *MessageFromBot) MarshalJSONBuf(buf fflib.EncodingBuffer) error

MarshalJSONBuf marshal buff to json - template

func (*MessageFromBot) UnmarshalJSON

func (j *MessageFromBot) UnmarshalJSON(input []byte) error

UnmarshalJSON umarshall json - template of ffjson

func (*MessageFromBot) UnmarshalJSONFFLexer

func (j *MessageFromBot) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

UnmarshalJSONFFLexer fast json unmarshall - template ffjson

type MessageUID

type MessageUID interface {
	UID() string
}

MessageUID is unique message ID as string

type MessengerResponse

type MessengerResponse interface {
}

MessengerResponse represents response from a messenger

type OnMessageSentResponse

type OnMessageSentResponse struct {
	StatusCode      int
	TelegramMessage MessengerResponse // TODO: change to some interface
}

OnMessageSentResponse represents response on message sent event

type TextMessageFromBot

type TextMessageFromBot struct {
	Text                  string              `json:",omitempty"`
	Format                MessageFormat       `json:",omitempty"`
	DisableWebPagePreview bool                `json:",omitempty"`
	DisableNotification   bool                `json:",omitempty"`
	Keyboard              botsgocore.Keyboard `json:",omitempty"`
	IsEdit                bool                `json:",omitempty"`
	EditMessageUID        MessageUID          `json:",omitempty"`
}

TextMessageFromBot is a text output message from bot to user

func (*TextMessageFromBot) BotMessageType

func (m *TextMessageFromBot) BotMessageType() BotMessageType

BotMessageType returns if we want to send a new message or edit existing one

func (*TextMessageFromBot) MarshalJSON

func (j *TextMessageFromBot) MarshalJSON() ([]byte, error)

MarshalJSON marshal bytes to json - template

func (*TextMessageFromBot) MarshalJSONBuf

func (j *TextMessageFromBot) MarshalJSONBuf(buf fflib.EncodingBuffer) error

MarshalJSONBuf marshal buff to json - template

func (*TextMessageFromBot) UnmarshalJSON

func (j *TextMessageFromBot) UnmarshalJSON(input []byte) error

UnmarshalJSON umarshall json - template of ffjson

func (*TextMessageFromBot) UnmarshalJSONFFLexer

func (j *TextMessageFromBot) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

UnmarshalJSONFFLexer fast json unmarshall - template ffjson

type TranslatorProvider

type TranslatorProvider func(c context.Context) i18n.Translator

TranslatorProvider translates texts

type TypeCommands

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

TypeCommands container for commands

type WebhookContext

type WebhookContext interface {
	//dal.TransactionCoordinator
	Environment() string
	BotInputProvider
	BotPlatform() BotPlatform

	Request() *http.Request

	// Context return context
	Context() context.Context

	// SetContext sets context
	SetContext(c context.Context)

	ExecutionContext() ExecutionContext

	AppContext() AppContext

	BotContext() BotContext

	MustBotChatID() string

	// GetBotCode returns bot code. This is a shortcut to BotSettings().Code
	GetBotCode() string

	// GetBotSettings returns bot settings
	GetBotSettings() *BotSettings

	// DB is a reference to database used to store data of current bot
	DB() dal.DB

	// Tx is a reference to database transaction used to get/save data of current bot
	Tx() dal.ReadwriteTransaction

	// ChatData returns data of current bot chat without ID/Key
	ChatData() botsfwmodels.BotChatData // Formerly ChatEntity()

	// BotUser returns record of current bot user
	BotUser() (botUser record.DataWithID[string, botsfwmodels.PlatformUserData], err error)
	GetBotUserID() string

	// IsInGroup indicates if message was received in a group botChat
	IsInGroup() (bool, error) // We  need to return an error as well (for Telegram chat instance).

	// CommandText TODO: needs to be documented
	CommandText(title, icon string) string

	// SetLocale sets Locale for current session
	SetLocale(code5 string) error

	NewMessage(text string) MessageFromBot
	NewMessageByCode(messageCode string, a ...interface{}) MessageFromBot
	NewEditMessage(text string, format MessageFormat) (MessageFromBot, error)

	UpdateLastProcessed(chatEntity botsfwmodels.BotChatData) error

	AppUserID() string

	AppUserData() (botsfwmodels.AppUserData, error)

	BotState

	// SaveBotChat // It is dangerous to allow user to pass context to this func as if it's a transactional context it might lead to deadlock
	// Previously: takes context as we might want to add timeout or cancellation or something else.
	SaveBotChat() error

	// RecordsFieldsSetter returns a helper that sets fields of bot related records
	RecordsFieldsSetter() BotRecordsFieldsSetter

	//botinput.WebhookInput // TODO: Should be removed!!!
	i18n.SingleLocaleTranslator

	Responder() WebhookResponder

	GA() GaContext // TODO: We should have an abstraction for analytics
}

WebhookContext provides context for current request from user to bot

type WebhookContextBase

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

WebhookContextBase provides base implementation of WebhookContext interface TODO: Document purpose of a dedicated base struct (e.g. example of usage by developers)

func NewWebhookContextBase

func NewWebhookContextBase(
	args CreateWebhookContextArgs,
	botPlatform BotPlatform,
	recordsFieldsSetter BotRecordsFieldsSetter,
	getIsInGroup func() (bool, error),
	getLocaleAndChatID func(c context.Context) (locale, chatID string, err error),
) (whcb *WebhookContextBase, err error)

NewWebhookContextBase creates base bot context

func (*WebhookContextBase) AppContext added in v0.35.0

func (whcb *WebhookContextBase) AppContext() AppContext

AppContext returns bot app context

func (*WebhookContextBase) AppUserData added in v0.29.0

func (whcb *WebhookContextBase) AppUserData() (appUserData botsfwmodels.AppUserData, err error)

func (*WebhookContextBase) AppUserEntity

func (whcb *WebhookContextBase) AppUserEntity() botsfwmodels.AppUserData

AppUserEntity current app user entity from data storage

func (*WebhookContextBase) AppUserID added in v0.13.0

func (whcb *WebhookContextBase) AppUserID() (appUserID string)

AppUserID return current app user ID as a string. AppUserIntID() is deprecated.

func (*WebhookContextBase) BotChatID

func (whcb *WebhookContextBase) BotChatID() (botChatID string, err error)

BotChatID returns bot botChat ID

func (*WebhookContextBase) BotContext

func (whcb *WebhookContextBase) BotContext() BotContext

func (*WebhookContextBase) BotPlatform

func (whcb *WebhookContextBase) BotPlatform() BotPlatform

BotPlatform indicates on which bot platform we process message

func (*WebhookContextBase) BotUser added in v0.21.0

func (*WebhookContextBase) Chat

Chat returns webhook botChat

func (*WebhookContextBase) ChatData added in v0.16.2

func (whcb *WebhookContextBase) ChatData() botsfwmodels.BotChatData

ChatData returns app entity for the context (loaded from DB)

func (*WebhookContextBase) CommandText

func (whcb *WebhookContextBase) CommandText(title, icon string) string

CommandText returns a title for a command

func (*WebhookContextBase) Context

func (whcb *WebhookContextBase) Context() context.Context

Context for current request

func (*WebhookContextBase) DB added in v0.18.0

func (whcb *WebhookContextBase) DB() dal.DB

func (*WebhookContextBase) Environment

func (whcb *WebhookContextBase) Environment() string

Environment defines current environment (PROD, DEV, LOCAL, etc)

func (*WebhookContextBase) ExecutionContext

func (whcb *WebhookContextBase) ExecutionContext() ExecutionContext

ExecutionContext returns an execution context for strongo app

func (*WebhookContextBase) GA

func (whcb *WebhookContextBase) GA() GaContext

GA provides interface to Google Analytics

func (*WebhookContextBase) GetAppUser

func (whcb *WebhookContextBase) GetAppUser() (botsfwmodels.AppUserData, error)

GetAppUser loads information about current app user from persistent storage

func (*WebhookContextBase) GetBotCode

func (whcb *WebhookContextBase) GetBotCode() string

GetBotCode returns current bot code

func (*WebhookContextBase) GetBotSettings

func (whcb *WebhookContextBase) GetBotSettings() *BotSettings

GetBotSettings settings of the current bot

func (*WebhookContextBase) GetBotToken

func (whcb *WebhookContextBase) GetBotToken() string

GetBotToken returns current bot API token

func (*WebhookContextBase) GetBotUserID added in v0.16.2

func (whcb *WebhookContextBase) GetBotUserID() string

func (*WebhookContextBase) GetRecipient

func (whcb *WebhookContextBase) GetRecipient() botinput.WebhookRecipient

GetRecipient returns receiver of the message

func (*WebhookContextBase) GetTime

func (whcb *WebhookContextBase) GetTime() time.Time

GetTime returns time of the message

func (*WebhookContextBase) HasChatData added in v0.16.2

func (whcb *WebhookContextBase) HasChatData() bool

HasChatData return true if messages is within botChat

func (*WebhookContextBase) Input

Input returns webhook input

func (*WebhookContextBase) InputType

func (whcb *WebhookContextBase) InputType() botinput.WebhookInputType

InputType returns input type

func (*WebhookContextBase) IsInGroup

func (whcb *WebhookContextBase) IsInGroup() (bool, error)

IsInGroup signals if the bot request is send within group botChat

func (*WebhookContextBase) IsInTransaction

func (whcb *WebhookContextBase) IsInTransaction(context.Context) bool

IsInTransaction detects if request is within a transaction

func (*WebhookContextBase) Locale

func (whcb *WebhookContextBase) Locale() i18n.Locale

Locale indicates current language

func (*WebhookContextBase) LogRequest

func (whcb *WebhookContextBase) LogRequest()

LogRequest logs request data to logging system

func (*WebhookContextBase) MessageText

func (whcb *WebhookContextBase) MessageText() string

MessageText returns text of a received message

func (*WebhookContextBase) MustBotChatID

func (whcb *WebhookContextBase) MustBotChatID() (chatID string)

MustBotChatID returns bot botChat ID and panic if missing it

func (*WebhookContextBase) NewMessage

func (whcb *WebhookContextBase) NewMessage(text string) (m MessageFromBot)

NewMessage creates a new text message from bot

func (*WebhookContextBase) NewMessageByCode

func (whcb *WebhookContextBase) NewMessageByCode(messageCode string, a ...interface{}) (m MessageFromBot)

NewMessageByCode creates new translated message by i18n code

func (*WebhookContextBase) NonTransactionalContext

func (whcb *WebhookContextBase) NonTransactionalContext(context.Context) context.Context

NonTransactionalContext creates a non transaction context for operations that needs to be executed outside of transaction.

func (*WebhookContextBase) RecordsFieldsSetter added in v0.16.2

func (whcb *WebhookContextBase) RecordsFieldsSetter() BotRecordsFieldsSetter

func (*WebhookContextBase) Request

func (whcb *WebhookContextBase) Request() *http.Request

Request returns reference to current HTTP request

func (*WebhookContextBase) SaveBotChat added in v0.18.0

func (whcb *WebhookContextBase) SaveBotChat() error

func (*WebhookContextBase) SaveBotUser added in v0.18.0

func (whcb *WebhookContextBase) SaveBotUser(ctx context.Context) error

func (*WebhookContextBase) SetChatID

func (whcb *WebhookContextBase) SetChatID(chatID string)

SetChatID sets botChat ID - TODO: Should it be private?

func (*WebhookContextBase) SetContext

func (whcb *WebhookContextBase) SetContext(c context.Context)

SetContext sets current context // TODO: explain why we need this as probably should be in constructor?

func (*WebhookContextBase) SetLocale

func (whcb *WebhookContextBase) SetLocale(code5 string) error

SetLocale sets current language

func (WebhookContextBase) Translate

func (t WebhookContextBase) Translate(key string, args ...interface{}) string

Translate translates string

func (WebhookContextBase) TranslateNoWarning

func (t WebhookContextBase) TranslateNoWarning(key string, args ...interface{}) string

TranslateNoWarning translates string without warnings

func (*WebhookContextBase) Tx added in v0.18.0

Tx returns a transaction that is used to read/write botChat & bot user data

type WebhookDriver

type WebhookDriver interface {
	RegisterWebhookHandlers(httpRouter HttpRouter, pathPrefix string, webhookHandlers ...WebhookHandler)
	HandleWebhook(w http.ResponseWriter, r *http.Request, webhookHandler WebhookHandler)
}

WebhookDriver is doing initial request & final response processing. That includes logging, creating input messages in a general format, sending response.

type WebhookHandler

type WebhookHandler interface {

	// RegisterHttpHandlers registers HTTP handlers for bot API
	RegisterHttpHandlers(driver WebhookDriver, botHost BotHost, router HttpRouter, pathPrefix string)

	// HandleWebhookRequest handles incoming webhook request
	HandleWebhookRequest(w http.ResponseWriter, r *http.Request)

	// GetBotContextAndInputs returns bot context and inputs for current request
	// It returns multiple inputs as some platforms (like Facebook Messenger)
	// may send multiple message in one request
	GetBotContextAndInputs(c context.Context, r *http.Request) (botContext *BotContext, entriesWithInputs []EntryInputs, err error)

	// CreateWebhookContext creates WebhookContext for current webhook request
	CreateWebhookContext(args CreateWebhookContextArgs) (WebhookContext, error)

	GetResponder(w http.ResponseWriter, whc WebhookContext) WebhookResponder
	HandleUnmatched(whc WebhookContext) (m MessageFromBot)
}

WebhookHandler handles requests from a specific bot API This is implemented by different botsfw packages, e.g. https://github.com/bots-go-framework/bots-fw-telegram TODO: Simplify interface by decomposing it into smaller interfaces? Probably next method could/should be decoupled: CreateBotCoreStores()

type WebhookHandlerBase added in v0.16.0

type WebhookHandlerBase struct {
	WebhookDriver
	BotHost
	BotPlatform
	//RecordsMaker        botsfwmodels.BotRecordsMaker
	RecordsFieldsSetter BotRecordsFieldsSetter
	TranslatorProvider  TranslatorProvider
}

WebhookHandlerBase provides base implementation for a bot handler

func (*WebhookHandlerBase) MarshalJSON added in v0.16.0

func (j *WebhookHandlerBase) MarshalJSON() ([]byte, error)

MarshalJSON marshal bytes to json - template

func (*WebhookHandlerBase) MarshalJSONBuf added in v0.16.0

func (j *WebhookHandlerBase) MarshalJSONBuf(buf fflib.EncodingBuffer) error

MarshalJSONBuf marshal buff to json - template

func (*WebhookHandlerBase) Register added in v0.16.0

func (bh *WebhookHandlerBase) Register(d WebhookDriver, h BotHost)

Register driver

func (*WebhookHandlerBase) UnmarshalJSON added in v0.16.0

func (j *WebhookHandlerBase) UnmarshalJSON(input []byte) error

UnmarshalJSON umarshall json - template of ffjson

func (*WebhookHandlerBase) UnmarshalJSONFFLexer added in v0.16.0

func (j *WebhookHandlerBase) UnmarshalJSONFFLexer(fs *fflib.FFLexer, state fflib.FFParseState) error

UnmarshalJSONFFLexer fast json unmarshall - template ffjson

type WebhookInlineQueryContext

type WebhookInlineQueryContext interface {
}

WebhookInlineQueryContext provides context for inline query (TODO: check & document)

type WebhookNewContext

type WebhookNewContext struct {
	BotContext
	botinput.WebhookInput
}

WebhookNewContext TODO: needs to be checked & described

type WebhookResponder

type WebhookResponder interface {
	SendMessage(c context.Context, m MessageFromBot, channel BotAPISendMessageChannel) (OnMessageSentResponse, error)
}

WebhookResponder is an API provider to send messages through a messenger

type WebhooksRouter

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

WebhooksRouter maps routes to commands

func NewWebhookRouter

func NewWebhookRouter(errorFooterText func() string) WebhooksRouter

NewWebhookRouter creates new router

func (*WebhooksRouter) AddCommands

func (whRouter *WebhooksRouter) AddCommands(commands ...Command)

AddCommands adds commands to router. It should be called just once with the current implementation of AddCommandsForInputType() TODO: Either leave this one or RegisterCommands

func (*WebhooksRouter) AddCommandsForInputType added in v0.39.0

func (whRouter *WebhooksRouter) AddCommandsForInputType(inputType botinput.WebhookInputType, commands ...Command)

AddCommandsForInputType adds commands for the given input type

func (*WebhooksRouter) AddCommandsGroupedByType added in v0.39.0

func (whRouter *WebhooksRouter) AddCommandsGroupedByType(commandsByType map[botinput.WebhookInputType][]Command)

AddCommandsGroupedByType adds commands grouped by input type

func (*WebhooksRouter) CommandsCount

func (whRouter *WebhooksRouter) CommandsCount() int

func (*WebhooksRouter) Dispatch

func (whRouter *WebhooksRouter) Dispatch(webhookHandler WebhookHandler, responder WebhookResponder, whc WebhookContext) (err error)

Dispatch query to commands

func (*WebhooksRouter) DispatchInlineQuery

func (whRouter *WebhooksRouter) DispatchInlineQuery(responder WebhookResponder)

DispatchInlineQuery dispatches inlines query

func (*WebhooksRouter) RegisterCommands

func (whRouter *WebhooksRouter) RegisterCommands(commands ...Command)

RegisterCommands is registering commands with router TODO: Either leave this one or AddCommands()

Jump to

Keyboard shortcuts

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